mssql_dialect.go 14 KB

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