mssql_dialect.go 15 KB

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