mssql_dialect.go 14 KB

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