gf/database/gdb/gdb_driver_mssql.go

240 lines
7.0 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2018-11-19 11:38:57 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2019-07-13 11:35:22 +08:00
//
2020-01-06 20:43:59 +08:00
// Note:
2020-03-08 00:17:42 +08:00
// 1. It needs manually import: _ "github.com/denisenkom/go-mssqldb"
2020-01-06 20:43:59 +08:00
// 2. It does not support Save/Replace features.
// 3. It does not support LastInsertId.
2018-11-19 11:38:57 +08:00
package gdb
import (
"database/sql"
"fmt"
"github.com/gogf/gf/internal/intlog"
"github.com/gogf/gf/text/gstr"
2018-11-19 11:38:57 +08:00
"strconv"
"strings"
"github.com/gogf/gf/text/gregex"
2018-11-19 11:38:57 +08:00
)
2020-03-08 00:17:42 +08:00
// DriverMssql is the driver for SQL server database.
type DriverMssql struct {
*Core
}
// New creates and returns a database object for SQL server.
// It implements the interface of gdb.Driver for extra database driver installation.
2020-03-08 00:17:42 +08:00
func (d *DriverMssql) New(core *Core, node *ConfigNode) (DB, error) {
return &DriverMssql{
Core: core,
}, nil
2018-11-19 11:38:57 +08:00
}
// Open creates and returns a underlying sql.DB object for mssql.
2020-03-08 00:17:42 +08:00
func (d *DriverMssql) Open(config *ConfigNode) (*sql.DB, error) {
source := ""
if config.LinkInfo != "" {
source = config.LinkInfo
2018-11-19 11:38:57 +08:00
} else {
2020-01-06 20:43:59 +08:00
source = fmt.Sprintf(
"user id=%s;password=%s;server=%s;port=%s;database=%s;encrypt=disable",
config.User, config.Pass, config.Host, config.Port, config.Name,
)
2018-11-19 11:38:57 +08:00
}
intlog.Printf("Open: %s", source)
2018-11-19 11:38:57 +08:00
if db, err := sql.Open("sqlserver", source); err == nil {
return db, nil
} else {
return nil, err
}
}
2020-03-08 00:17:42 +08:00
// GetChars returns the security char for this type of database.
func (d *DriverMssql) GetChars() (charLeft string, charRight string) {
2018-12-14 18:35:51 +08:00
return "\"", "\""
2018-11-19 11:38:57 +08:00
}
// HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.
func (d *DriverMssql) HandleSqlBeforeCommit(link Link, query string, args []interface{}) (string, []interface{}) {
var index int
// Convert place holder char '?' to string "@px".
2018-12-14 18:35:51 +08:00
str, _ := gregex.ReplaceStringFunc("\\?", query, func(s string) string {
2018-11-19 11:38:57 +08:00
index++
return fmt.Sprintf("@p%d", index)
})
str, _ = gregex.ReplaceString("\"", "", str)
return d.parseSql(str), args
2018-11-19 11:38:57 +08:00
}
2020-03-08 00:17:42 +08:00
func (d *DriverMssql) parseSql(sql string) string {
2020-01-07 22:14:32 +08:00
// SELECT * FROM USER WHERE ID=1 LIMIT 1
if m, _ := gregex.MatchString(`^SELECT(.+)LIMIT 1$`, sql); len(m) > 1 {
return fmt.Sprintf(`SELECT TOP 1 %s`, m[1])
}
// SELECT * FROM USER WHERE AGE>18 ORDER BY ID DESC LIMIT 100, 200
2018-11-19 11:38:57 +08:00
patten := `^\s*(?i)(SELECT)|(LIMIT\s*(\d+)\s*,\s*(\d+))`
2018-12-14 18:35:51 +08:00
if gregex.IsMatchString(patten, sql) == false {
2018-11-19 11:38:57 +08:00
return sql
}
2018-12-14 18:35:51 +08:00
res, err := gregex.MatchAllString(patten, sql)
2018-11-19 11:38:57 +08:00
if err != nil {
2018-12-14 18:35:51 +08:00
return ""
2018-11-19 11:38:57 +08:00
}
index := 0
keyword := strings.TrimSpace(res[index][0])
keyword = strings.ToUpper(keyword)
index++
switch keyword {
2019-06-19 09:06:52 +08:00
case "SELECT":
2020-01-06 20:43:59 +08:00
// 不含LIMIT关键字则不处理
if len(res) < 2 ||
(strings.HasPrefix(res[index][0], "LIMIT") == false &&
strings.HasPrefix(res[index][0], "limit") == false) {
2019-06-19 09:06:52 +08:00
break
}
2020-01-06 20:43:59 +08:00
// 不含LIMIT则不处理
2019-06-19 09:06:52 +08:00
if gregex.IsMatchString("((?i)SELECT)(.+)((?i)LIMIT)", sql) == false {
break
}
2020-01-06 20:43:59 +08:00
// 判断SQL中是否含有order by
2019-06-19 09:06:52 +08:00
selectStr := ""
2020-01-06 20:43:59 +08:00
orderStr := ""
2020-01-07 22:14:32 +08:00
haveOrder := gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
if haveOrder {
2020-01-06 20:43:59 +08:00
// 取order by 前面的字符串
2019-06-19 09:06:52 +08:00
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
if len(queryExpr) != 4 ||
strings.EqualFold(queryExpr[1], "SELECT") == false ||
strings.EqualFold(queryExpr[3], "ORDER BY") == false {
2018-11-19 11:38:57 +08:00
break
}
2019-06-19 09:06:52 +08:00
selectStr = queryExpr[2]
2018-11-19 11:38:57 +08:00
2020-01-06 20:43:59 +08:00
// 取order by表达式的值
orderExpr, _ := gregex.MatchString("((?i)ORDER BY)(.+)((?i)LIMIT)", sql)
if len(orderExpr) != 4 ||
strings.EqualFold(orderExpr[1], "ORDER BY") == false ||
strings.EqualFold(orderExpr[3], "LIMIT") == false {
2018-11-19 11:38:57 +08:00
break
}
2020-01-06 20:43:59 +08:00
orderStr = orderExpr[2]
2019-06-19 09:06:52 +08:00
} else {
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)LIMIT)", sql)
if len(queryExpr) != 4 ||
strings.EqualFold(queryExpr[1], "SELECT") == false ||
strings.EqualFold(queryExpr[3], "LIMIT") == false {
2019-06-19 09:06:52 +08:00
break
}
selectStr = queryExpr[2]
}
2020-01-06 20:43:59 +08:00
// 取limit后面的取值范围
2019-06-19 09:06:52 +08:00
first, limit := 0, 0
for i := 1; i < len(res[index]); i++ {
if len(strings.TrimSpace(res[index][i])) == 0 {
continue
2018-11-19 11:38:57 +08:00
}
if strings.HasPrefix(res[index][i], "LIMIT") ||
strings.HasPrefix(res[index][i], "limit") {
2019-06-19 09:06:52 +08:00
first, _ = strconv.Atoi(res[index][i+1])
limit, _ = strconv.Atoi(res[index][i+2])
break
2018-11-19 11:38:57 +08:00
}
2019-06-19 09:06:52 +08:00
}
2018-11-19 11:38:57 +08:00
2020-01-07 22:14:32 +08:00
if haveOrder {
2020-01-06 20:43:59 +08:00
sql = fmt.Sprintf(
"SELECT * FROM "+
"(SELECT ROW_NUMBER() OVER (ORDER BY %s) as ROWNUMBER_, %s ) as TMP_ "+
"WHERE TMP_.ROWNUMBER_ > %d AND TMP_.ROWNUMBER_ <= %d",
orderStr, selectStr, first, limit,
)
2019-06-19 09:06:52 +08:00
} else {
if first == 0 {
first = limit
2018-11-19 11:38:57 +08:00
} else {
2019-06-19 09:06:52 +08:00
first = limit - first
2018-11-19 11:38:57 +08:00
}
2020-01-06 20:43:59 +08:00
sql = fmt.Sprintf(
"SELECT * FROM (SELECT TOP %d * FROM (SELECT TOP %d %s) as TMP1_ ) as TMP2_ ",
first, limit, selectStr,
)
2019-06-19 09:06:52 +08:00
}
default:
2018-11-19 11:38:57 +08:00
}
return sql
}
// Tables retrieves and returns the tables of current schema.
// It's mainly used in cli tool chain for automatically generating the models.
2020-03-08 00:17:42 +08:00
func (d *DriverMssql) Tables(schema ...string) (tables []string, err error) {
var result Result
2020-03-08 00:17:42 +08:00
link, err := d.DB.GetSlave(schema...)
if err != nil {
return nil, err
}
2020-03-08 00:17:42 +08:00
result, err = d.DB.DoGetAll(link, `SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' AND STATUS >= 0 ORDER BY NAME`)
if err != nil {
return
}
for _, m := range result {
for _, v := range m {
2020-03-06 11:01:03 +08:00
tables = append(tables, v.String())
}
}
return
}
// TableFields retrieves and returns the fields information of specified table of current schema.
2020-03-08 00:17:42 +08:00
func (d *DriverMssql) TableFields(table string, schema ...string) (fields map[string]*TableField, err error) {
table = gstr.Trim(table)
if gstr.Contains(table, " ") {
panic("function TableFields supports only single table operations")
}
2020-03-08 00:17:42 +08:00
checkSchema := d.DB.GetSchema()
2020-01-07 22:14:32 +08:00
if len(schema) > 0 && schema[0] != "" {
checkSchema = schema[0]
}
2020-03-08 00:17:42 +08:00
v := d.DB.GetCache().GetOrSetFunc(
2020-01-07 22:14:32 +08:00
fmt.Sprintf(`mssql_table_fields_%s_%s`, table, checkSchema), func() interface{} {
var result Result
var link *sql.DB
2020-03-08 00:17:42 +08:00
link, err = d.DB.GetSlave(checkSchema)
2020-01-07 22:14:32 +08:00
if err != nil {
return nil
}
2020-03-08 00:17:42 +08:00
result, err = d.DB.DoGetAll(link, fmt.Sprintf(`
2020-01-07 22:14:32 +08:00
SELECT c.name as FIELD, CASE t.name
WHEN 'numeric' THEN t.name + '(' + convert(varchar(20),c.xprec) + ',' + convert(varchar(20),c.xscale) + ')'
WHEN 'char' THEN t.name + '(' + convert(varchar(20),c.length)+ ')'
WHEN 'varchar' THEN t.name + '(' + convert(varchar(20),c.length)+ ')'
ELSE t.name + '(' + convert(varchar(20),c.length)+ ')' END as TYPE
FROM systypes t,syscolumns c WHERE t.xtype=c.xtype
AND c.id = (SELECT id FROM sysobjects WHERE name='%s')
ORDER BY c.colid`, strings.ToUpper(table)))
if err != nil {
return nil
}
fields = make(map[string]*TableField)
for i, m := range result {
fields[strings.ToLower(m["FIELD"].String())] = &TableField{
Index: i,
Name: strings.ToLower(m["FIELD"].String()),
Type: strings.ToLower(m["TYPE"].String()),
}
}
return fields
}, 0)
if err == nil {
fields = v.(map[string]*TableField)
}
return
}