dialect_mssql.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. // Copyright 2015 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "github.com/xormplus/core"
  12. )
  13. var (
  14. mssqlReservedWords = map[string]bool{
  15. "ADD": true,
  16. "EXTERNAL": true,
  17. "PROCEDURE": true,
  18. "ALL": true,
  19. "FETCH": true,
  20. "PUBLIC": true,
  21. "ALTER": true,
  22. "FILE": true,
  23. "RAISERROR": true,
  24. "AND": true,
  25. "FILLFACTOR": true,
  26. "READ": true,
  27. "ANY": true,
  28. "FOR": true,
  29. "READTEXT": true,
  30. "AS": true,
  31. "FOREIGN": true,
  32. "RECONFIGURE": true,
  33. "ASC": true,
  34. "FREETEXT": true,
  35. "REFERENCES": true,
  36. "AUTHORIZATION": true,
  37. "FREETEXTTABLE": true,
  38. "REPLICATION": true,
  39. "BACKUP": true,
  40. "FROM": true,
  41. "RESTORE": true,
  42. "BEGIN": true,
  43. "FULL": true,
  44. "RESTRICT": true,
  45. "BETWEEN": true,
  46. "FUNCTION": true,
  47. "RETURN": true,
  48. "BREAK": true,
  49. "GOTO": true,
  50. "REVERT": true,
  51. "BROWSE": true,
  52. "GRANT": true,
  53. "REVOKE": true,
  54. "BULK": true,
  55. "GROUP": true,
  56. "RIGHT": true,
  57. "BY": true,
  58. "HAVING": true,
  59. "ROLLBACK": true,
  60. "CASCADE": true,
  61. "HOLDLOCK": true,
  62. "ROWCOUNT": true,
  63. "CASE": true,
  64. "IDENTITY": true,
  65. "ROWGUIDCOL": true,
  66. "CHECK": true,
  67. "IDENTITY_INSERT": true,
  68. "RULE": true,
  69. "CHECKPOINT": true,
  70. "IDENTITYCOL": true,
  71. "SAVE": true,
  72. "CLOSE": true,
  73. "IF": true,
  74. "SCHEMA": true,
  75. "CLUSTERED": true,
  76. "IN": true,
  77. "SECURITYAUDIT": true,
  78. "COALESCE": true,
  79. "INDEX": true,
  80. "SELECT": true,
  81. "COLLATE": true,
  82. "INNER": true,
  83. "SEMANTICKEYPHRASETABLE": true,
  84. "COLUMN": true,
  85. "INSERT": true,
  86. "SEMANTICSIMILARITYDETAILSTABLE": true,
  87. "COMMIT": true,
  88. "INTERSECT": true,
  89. "SEMANTICSIMILARITYTABLE": true,
  90. "COMPUTE": true,
  91. "INTO": true,
  92. "SESSION_USER": true,
  93. "CONSTRAINT": true,
  94. "IS": true,
  95. "SET": true,
  96. "CONTAINS": true,
  97. "JOIN": true,
  98. "SETUSER": true,
  99. "CONTAINSTABLE": true,
  100. "KEY": true,
  101. "SHUTDOWN": true,
  102. "CONTINUE": true,
  103. "KILL": true,
  104. "SOME": true,
  105. "CONVERT": true,
  106. "LEFT": true,
  107. "STATISTICS": true,
  108. "CREATE": true,
  109. "LIKE": true,
  110. "SYSTEM_USER": true,
  111. "CROSS": true,
  112. "LINENO": true,
  113. "TABLE": true,
  114. "CURRENT": true,
  115. "LOAD": true,
  116. "TABLESAMPLE": true,
  117. "CURRENT_DATE": true,
  118. "MERGE": true,
  119. "TEXTSIZE": true,
  120. "CURRENT_TIME": true,
  121. "NATIONAL": true,
  122. "THEN": true,
  123. "CURRENT_TIMESTAMP": true,
  124. "NOCHECK": true,
  125. "TO": true,
  126. "CURRENT_USER": true,
  127. "NONCLUSTERED": true,
  128. "TOP": true,
  129. "CURSOR": true,
  130. "NOT": true,
  131. "TRAN": true,
  132. "DATABASE": true,
  133. "NULL": true,
  134. "TRANSACTION": true,
  135. "DBCC": true,
  136. "NULLIF": true,
  137. "TRIGGER": true,
  138. "DEALLOCATE": true,
  139. "OF": true,
  140. "TRUNCATE": true,
  141. "DECLARE": true,
  142. "OFF": true,
  143. "TRY_CONVERT": true,
  144. "DEFAULT": true,
  145. "OFFSETS": true,
  146. "TSEQUAL": true,
  147. "DELETE": true,
  148. "ON": true,
  149. "UNION": true,
  150. "DENY": true,
  151. "OPEN": true,
  152. "UNIQUE": true,
  153. "DESC": true,
  154. "OPENDATASOURCE": true,
  155. "UNPIVOT": true,
  156. "DISK": true,
  157. "OPENQUERY": true,
  158. "UPDATE": true,
  159. "DISTINCT": true,
  160. "OPENROWSET": true,
  161. "UPDATETEXT": true,
  162. "DISTRIBUTED": true,
  163. "OPENXML": true,
  164. "USE": true,
  165. "DOUBLE": true,
  166. "OPTION": true,
  167. "USER": true,
  168. "DROP": true,
  169. "OR": true,
  170. "VALUES": true,
  171. "DUMP": true,
  172. "ORDER": true,
  173. "VARYING": true,
  174. "ELSE": true,
  175. "OUTER": true,
  176. "VIEW": true,
  177. "END": true,
  178. "OVER": true,
  179. "WAITFOR": true,
  180. "ERRLVL": true,
  181. "PERCENT": true,
  182. "WHEN": true,
  183. "ESCAPE": true,
  184. "PIVOT": true,
  185. "WHERE": true,
  186. "EXCEPT": true,
  187. "PLAN": true,
  188. "WHILE": true,
  189. "EXEC": true,
  190. "PRECISION": true,
  191. "WITH": true,
  192. "EXECUTE": true,
  193. "PRIMARY": true,
  194. "WITHIN": true,
  195. "EXISTS": true,
  196. "PRINT": true,
  197. "WRITETEXT": true,
  198. "EXIT": true,
  199. "PROC": true,
  200. }
  201. )
  202. type mssql struct {
  203. core.Base
  204. }
  205. func (db *mssql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
  206. return db.Base.Init(d, db, uri, drivername, dataSourceName)
  207. }
  208. func (db *mssql) SqlType(c *core.Column) string {
  209. var res string
  210. switch t := c.SQLType.Name; t {
  211. case core.Bool:
  212. res = core.Bit
  213. if strings.EqualFold(c.Default, "true") {
  214. c.Default = "1"
  215. } else if strings.EqualFold(c.Default, "false") {
  216. c.Default = "0"
  217. }
  218. case core.Serial:
  219. c.IsAutoIncrement = true
  220. c.IsPrimaryKey = true
  221. c.Nullable = false
  222. res = core.Int
  223. case core.BigSerial:
  224. c.IsAutoIncrement = true
  225. c.IsPrimaryKey = true
  226. c.Nullable = false
  227. res = core.BigInt
  228. case core.Bytea, core.Blob, core.Binary, core.TinyBlob, core.MediumBlob, core.LongBlob:
  229. res = core.VarBinary
  230. if c.Length == 0 {
  231. c.Length = 50
  232. }
  233. case core.TimeStamp:
  234. res = core.DateTime
  235. case core.TimeStampz:
  236. res = "DATETIMEOFFSET"
  237. c.Length = 7
  238. case core.MediumInt:
  239. res = core.Int
  240. case core.Text, core.MediumText, core.TinyText, core.LongText, core.Json:
  241. res = core.Varchar + "(MAX)"
  242. case core.Double:
  243. res = core.Real
  244. case core.Uuid:
  245. res = core.Varchar
  246. c.Length = 40
  247. case core.TinyInt:
  248. res = core.TinyInt
  249. c.Length = 0
  250. default:
  251. res = t
  252. }
  253. if res == core.Int {
  254. return core.Int
  255. }
  256. hasLen1 := (c.Length > 0)
  257. hasLen2 := (c.Length2 > 0)
  258. if hasLen2 {
  259. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  260. } else if hasLen1 {
  261. res += "(" + strconv.Itoa(c.Length) + ")"
  262. }
  263. return res
  264. }
  265. func (db *mssql) SupportInsertMany() bool {
  266. return true
  267. }
  268. func (db *mssql) IsReserved(name string) bool {
  269. _, ok := mssqlReservedWords[name]
  270. return ok
  271. }
  272. func (db *mssql) Quote(name string) string {
  273. return "\"" + name + "\""
  274. }
  275. func (db *mssql) QuoteStr() string {
  276. return "\""
  277. }
  278. func (db *mssql) SupportEngine() bool {
  279. return false
  280. }
  281. func (db *mssql) AutoIncrStr() string {
  282. return "IDENTITY"
  283. }
  284. func (db *mssql) DropTableSql(tableName string) string {
  285. return fmt.Sprintf("IF EXISTS (SELECT * FROM sysobjects WHERE id = "+
  286. "object_id(N'%s') and OBJECTPROPERTY(id, N'IsUserTable') = 1) "+
  287. "DROP TABLE \"%s\"", tableName, tableName)
  288. }
  289. func (db *mssql) SupportCharset() bool {
  290. return false
  291. }
  292. func (db *mssql) IndexOnTable() bool {
  293. return true
  294. }
  295. func (db *mssql) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
  296. args := []interface{}{idxName}
  297. sql := "select name from sysindexes where id=object_id('" + tableName + "') and name=?"
  298. return sql, args
  299. }
  300. /*func (db *mssql) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
  301. args := []interface{}{tableName, colName}
  302. sql := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
  303. return sql, args
  304. }*/
  305. func (db *mssql) IsColumnExist(tableName, colName string) (bool, error) {
  306. query := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
  307. return db.HasRecords(query, tableName, colName)
  308. }
  309. func (db *mssql) TableCheckSql(tableName string) (string, []interface{}) {
  310. args := []interface{}{}
  311. sql := "select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsUserTable') = 1"
  312. return sql, args
  313. }
  314. func (db *mssql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  315. args := []interface{}{}
  316. s := `select a.name as name, b.name as ctype,a.max_length,a.precision,a.scale,a.is_nullable as nullable,
  317. replace(replace(isnull(c.text,''),'(',''),')','') as vdefault,
  318. ISNULL(i.is_primary_key, 0)
  319. from sys.columns a
  320. left join sys.types b on a.user_type_id=b.user_type_id
  321. left join sys.syscomments c on a.default_object_id=c.id
  322. LEFT OUTER JOIN
  323. sys.index_columns ic ON ic.object_id = a.object_id AND ic.column_id = a.column_id
  324. LEFT OUTER JOIN
  325. sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
  326. where a.object_id=object_id('` + tableName + `')`
  327. db.LogSQL(s, args)
  328. rows, err := db.DB().Query(s, args...)
  329. if err != nil {
  330. return nil, nil, err
  331. }
  332. defer rows.Close()
  333. cols := make(map[string]*core.Column)
  334. colSeq := make([]string, 0)
  335. for rows.Next() {
  336. var name, ctype, vdefault string
  337. var maxLen, precision, scale int
  338. var nullable, isPK bool
  339. err = rows.Scan(&name, &ctype, &maxLen, &precision, &scale, &nullable, &vdefault, &isPK)
  340. if err != nil {
  341. return nil, nil, err
  342. }
  343. col := new(core.Column)
  344. col.Indexes = make(map[string]int)
  345. col.Name = strings.Trim(name, "` ")
  346. col.Nullable = nullable
  347. col.Default = vdefault
  348. col.IsPrimaryKey = isPK
  349. ct := strings.ToUpper(ctype)
  350. if ct == "DECIMAL" {
  351. col.Length = precision
  352. col.Length2 = scale
  353. } else {
  354. col.Length = maxLen
  355. }
  356. switch ct {
  357. case "DATETIMEOFFSET":
  358. col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
  359. case "NVARCHAR":
  360. col.SQLType = core.SQLType{Name: core.NVarchar, DefaultLength: 0, DefaultLength2: 0}
  361. case "IMAGE":
  362. col.SQLType = core.SQLType{Name: core.VarBinary, DefaultLength: 0, DefaultLength2: 0}
  363. default:
  364. if _, ok := core.SqlTypes[ct]; ok {
  365. col.SQLType = core.SQLType{Name: ct, DefaultLength: 0, DefaultLength2: 0}
  366. } else {
  367. return nil, nil, fmt.Errorf("Unknown colType %v for %v - %v", ct, tableName, col.Name)
  368. }
  369. }
  370. if col.SQLType.IsText() || col.SQLType.IsTime() {
  371. if col.Default != "" {
  372. col.Default = "'" + col.Default + "'"
  373. } else {
  374. if col.DefaultIsEmpty {
  375. col.Default = "''"
  376. }
  377. }
  378. }
  379. cols[col.Name] = col
  380. colSeq = append(colSeq, col.Name)
  381. }
  382. return colSeq, cols, nil
  383. }
  384. func (db *mssql) GetTables() ([]*core.Table, error) {
  385. args := []interface{}{}
  386. s := `select name from sysobjects where xtype ='U'`
  387. db.LogSQL(s, args)
  388. rows, err := db.DB().Query(s, args...)
  389. if err != nil {
  390. return nil, err
  391. }
  392. defer rows.Close()
  393. tables := make([]*core.Table, 0)
  394. for rows.Next() {
  395. table := core.NewEmptyTable()
  396. var name string
  397. err = rows.Scan(&name)
  398. if err != nil {
  399. return nil, err
  400. }
  401. table.Name = strings.Trim(name, "` ")
  402. tables = append(tables, table)
  403. }
  404. return tables, nil
  405. }
  406. func (db *mssql) GetIndexes(tableName string) (map[string]*core.Index, error) {
  407. args := []interface{}{tableName}
  408. s := `SELECT
  409. IXS.NAME AS [INDEX_NAME],
  410. C.NAME AS [COLUMN_NAME],
  411. IXS.is_unique AS [IS_UNIQUE]
  412. FROM SYS.INDEXES IXS
  413. INNER JOIN SYS.INDEX_COLUMNS IXCS
  414. ON IXS.OBJECT_ID=IXCS.OBJECT_ID AND IXS.INDEX_ID = IXCS.INDEX_ID
  415. INNER JOIN SYS.COLUMNS C ON IXS.OBJECT_ID=C.OBJECT_ID
  416. AND IXCS.COLUMN_ID=C.COLUMN_ID
  417. WHERE IXS.TYPE_DESC='NONCLUSTERED' and OBJECT_NAME(IXS.OBJECT_ID) =?
  418. `
  419. db.LogSQL(s, args)
  420. rows, err := db.DB().Query(s, args...)
  421. if err != nil {
  422. return nil, err
  423. }
  424. defer rows.Close()
  425. indexes := make(map[string]*core.Index, 0)
  426. for rows.Next() {
  427. var indexType int
  428. var indexName, colName, isUnique string
  429. err = rows.Scan(&indexName, &colName, &isUnique)
  430. if err != nil {
  431. return nil, err
  432. }
  433. i, err := strconv.ParseBool(isUnique)
  434. if err != nil {
  435. return nil, err
  436. }
  437. if i {
  438. indexType = core.UniqueType
  439. } else {
  440. indexType = core.IndexType
  441. }
  442. colName = strings.Trim(colName, "` ")
  443. var isRegular bool
  444. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  445. indexName = indexName[5+len(tableName):]
  446. isRegular = true
  447. }
  448. var index *core.Index
  449. var ok bool
  450. if index, ok = indexes[indexName]; !ok {
  451. index = new(core.Index)
  452. index.Type = indexType
  453. index.Name = indexName
  454. index.IsRegular = isRegular
  455. indexes[indexName] = index
  456. }
  457. index.AddColumn(colName)
  458. }
  459. return indexes, nil
  460. }
  461. func (db *mssql) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string {
  462. var sql string
  463. if tableName == "" {
  464. tableName = table.Name
  465. }
  466. sql = "IF NOT EXISTS (SELECT [name] FROM sys.tables WHERE [name] = '" + tableName + "' ) CREATE TABLE "
  467. sql += db.Quote(tableName) + " ("
  468. pkList := table.PrimaryKeys
  469. for _, colName := range table.ColumnsSeq() {
  470. col := table.GetColumn(colName)
  471. if col.IsPrimaryKey && len(pkList) == 1 {
  472. sql += col.String(db)
  473. } else {
  474. sql += col.StringNoPk(db)
  475. }
  476. sql = strings.TrimSpace(sql)
  477. sql += ", "
  478. }
  479. if len(pkList) > 1 {
  480. sql += "PRIMARY KEY ( "
  481. sql += strings.Join(pkList, ",")
  482. sql += " ), "
  483. }
  484. sql = sql[:len(sql)-2] + ")"
  485. sql += ";"
  486. return sql
  487. }
  488. func (db *mssql) ForUpdateSql(query string) string {
  489. return query
  490. }
  491. func (db *mssql) CreateIndexSql(tableName string, index *core.Index) string {
  492. quote := db.Quote
  493. return fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(tableName, index.Name)),
  494. quote(tableName), quote(strings.Join(index.Cols, quote(","))))
  495. }
  496. func (db *mssql) Filters() []core.Filter {
  497. return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}}
  498. }
  499. type odbcDriver struct {
  500. }
  501. func (p *odbcDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
  502. var dbName string
  503. if strings.HasPrefix(dataSourceName, "sqlserver://") {
  504. u, err := url.Parse(dataSourceName)
  505. if err != nil {
  506. return nil, err
  507. }
  508. dbName = u.Query().Get("database")
  509. } else {
  510. kv := strings.Split(dataSourceName, ";")
  511. for _, c := range kv {
  512. vv := strings.Split(strings.TrimSpace(c), "=")
  513. if len(vv) == 2 {
  514. switch strings.ToLower(vv[0]) {
  515. case "database":
  516. dbName = vv[1]
  517. }
  518. }
  519. }
  520. }
  521. if dbName == "" {
  522. return nil, errors.New("no db name provided")
  523. }
  524. return &core.Uri{DbName: dbName, DbType: core.MSSQL}, nil
  525. }