You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dialect_mssql.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. "xorm.io/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) SupportEngine() bool {
  276. return false
  277. }
  278. func (db *mssql) AutoIncrStr() string {
  279. return "IDENTITY"
  280. }
  281. func (db *mssql) DropTableSql(tableName string) string {
  282. return fmt.Sprintf("IF EXISTS (SELECT * FROM sysobjects WHERE id = "+
  283. "object_id(N'%s') and OBJECTPROPERTY(id, N'IsUserTable') = 1) "+
  284. "DROP TABLE \"%s\"", tableName, tableName)
  285. }
  286. func (db *mssql) SupportCharset() bool {
  287. return false
  288. }
  289. func (db *mssql) IndexOnTable() bool {
  290. return true
  291. }
  292. func (db *mssql) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
  293. args := []interface{}{idxName}
  294. sql := "select name from sysindexes where id=object_id('" + tableName + "') and name=?"
  295. return sql, args
  296. }
  297. /*func (db *mssql) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
  298. args := []interface{}{tableName, colName}
  299. sql := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
  300. return sql, args
  301. }*/
  302. func (db *mssql) IsColumnExist(tableName, colName string) (bool, error) {
  303. query := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
  304. return db.HasRecords(query, tableName, colName)
  305. }
  306. func (db *mssql) TableCheckSql(tableName string) (string, []interface{}) {
  307. args := []interface{}{}
  308. sql := "select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsUserTable') = 1"
  309. return sql, args
  310. }
  311. func (db *mssql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  312. args := []interface{}{}
  313. s := `select a.name as name, b.name as ctype,a.max_length,a.precision,a.scale,a.is_nullable as nullable,
  314. replace(replace(isnull(c.text,''),'(',''),')','') as vdefault,
  315. ISNULL(i.is_primary_key, 0)
  316. from sys.columns a
  317. left join sys.types b on a.user_type_id=b.user_type_id
  318. left join sys.syscomments c on a.default_object_id=c.id
  319. LEFT OUTER JOIN
  320. sys.index_columns ic ON ic.object_id = a.object_id AND ic.column_id = a.column_id
  321. LEFT OUTER JOIN
  322. sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
  323. where a.object_id=object_id('` + tableName + `')`
  324. db.LogSQL(s, args)
  325. rows, err := db.DB().Query(s, args...)
  326. if err != nil {
  327. return nil, nil, err
  328. }
  329. defer rows.Close()
  330. cols := make(map[string]*core.Column)
  331. colSeq := make([]string, 0)
  332. for rows.Next() {
  333. var name, ctype, vdefault string
  334. var maxLen, precision, scale int
  335. var nullable, isPK bool
  336. err = rows.Scan(&name, &ctype, &maxLen, &precision, &scale, &nullable, &vdefault, &isPK)
  337. if err != nil {
  338. return nil, nil, err
  339. }
  340. col := new(core.Column)
  341. col.Indexes = make(map[string]int)
  342. col.Name = strings.Trim(name, "` ")
  343. col.Nullable = nullable
  344. col.Default = vdefault
  345. col.IsPrimaryKey = isPK
  346. ct := strings.ToUpper(ctype)
  347. if ct == "DECIMAL" {
  348. col.Length = precision
  349. col.Length2 = scale
  350. } else {
  351. col.Length = maxLen
  352. }
  353. switch ct {
  354. case "DATETIMEOFFSET":
  355. col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
  356. case "NVARCHAR":
  357. col.SQLType = core.SQLType{Name: core.NVarchar, DefaultLength: 0, DefaultLength2: 0}
  358. case "IMAGE":
  359. col.SQLType = core.SQLType{Name: core.VarBinary, DefaultLength: 0, DefaultLength2: 0}
  360. default:
  361. if _, ok := core.SqlTypes[ct]; ok {
  362. col.SQLType = core.SQLType{Name: ct, DefaultLength: 0, DefaultLength2: 0}
  363. } else {
  364. return nil, nil, fmt.Errorf("Unknown colType %v for %v - %v", ct, tableName, col.Name)
  365. }
  366. }
  367. if col.SQLType.IsText() || col.SQLType.IsTime() {
  368. if col.Default != "" {
  369. col.Default = "'" + col.Default + "'"
  370. } else {
  371. if col.DefaultIsEmpty {
  372. col.Default = "''"
  373. }
  374. }
  375. }
  376. cols[col.Name] = col
  377. colSeq = append(colSeq, col.Name)
  378. }
  379. return colSeq, cols, nil
  380. }
  381. func (db *mssql) GetTables() ([]*core.Table, error) {
  382. args := []interface{}{}
  383. s := `select name from sysobjects where xtype ='U'`
  384. db.LogSQL(s, args)
  385. rows, err := db.DB().Query(s, args...)
  386. if err != nil {
  387. return nil, err
  388. }
  389. defer rows.Close()
  390. tables := make([]*core.Table, 0)
  391. for rows.Next() {
  392. table := core.NewEmptyTable()
  393. var name string
  394. err = rows.Scan(&name)
  395. if err != nil {
  396. return nil, err
  397. }
  398. table.Name = strings.Trim(name, "` ")
  399. tables = append(tables, table)
  400. }
  401. return tables, nil
  402. }
  403. func (db *mssql) GetIndexes(tableName string) (map[string]*core.Index, error) {
  404. args := []interface{}{tableName}
  405. s := `SELECT
  406. IXS.NAME AS [INDEX_NAME],
  407. C.NAME AS [COLUMN_NAME],
  408. IXS.is_unique AS [IS_UNIQUE]
  409. FROM SYS.INDEXES IXS
  410. INNER JOIN SYS.INDEX_COLUMNS IXCS
  411. ON IXS.OBJECT_ID=IXCS.OBJECT_ID AND IXS.INDEX_ID = IXCS.INDEX_ID
  412. INNER JOIN SYS.COLUMNS C ON IXS.OBJECT_ID=C.OBJECT_ID
  413. AND IXCS.COLUMN_ID=C.COLUMN_ID
  414. WHERE IXS.TYPE_DESC='NONCLUSTERED' and OBJECT_NAME(IXS.OBJECT_ID) =?
  415. `
  416. db.LogSQL(s, args)
  417. rows, err := db.DB().Query(s, args...)
  418. if err != nil {
  419. return nil, err
  420. }
  421. defer rows.Close()
  422. indexes := make(map[string]*core.Index, 0)
  423. for rows.Next() {
  424. var indexType int
  425. var indexName, colName, isUnique string
  426. err = rows.Scan(&indexName, &colName, &isUnique)
  427. if err != nil {
  428. return nil, err
  429. }
  430. i, err := strconv.ParseBool(isUnique)
  431. if err != nil {
  432. return nil, err
  433. }
  434. if i {
  435. indexType = core.UniqueType
  436. } else {
  437. indexType = core.IndexType
  438. }
  439. colName = strings.Trim(colName, "` ")
  440. var isRegular bool
  441. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  442. indexName = indexName[5+len(tableName):]
  443. isRegular = true
  444. }
  445. var index *core.Index
  446. var ok bool
  447. if index, ok = indexes[indexName]; !ok {
  448. index = new(core.Index)
  449. index.Type = indexType
  450. index.Name = indexName
  451. index.IsRegular = isRegular
  452. indexes[indexName] = index
  453. }
  454. index.AddColumn(colName)
  455. }
  456. return indexes, nil
  457. }
  458. func (db *mssql) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string {
  459. var sql string
  460. if tableName == "" {
  461. tableName = table.Name
  462. }
  463. sql = "IF NOT EXISTS (SELECT [name] FROM sys.tables WHERE [name] = '" + tableName + "' ) CREATE TABLE "
  464. sql += db.Quote(tableName) + " ("
  465. pkList := table.PrimaryKeys
  466. for _, colName := range table.ColumnsSeq() {
  467. col := table.GetColumn(colName)
  468. if col.IsPrimaryKey && len(pkList) == 1 {
  469. sql += col.String(db)
  470. } else {
  471. sql += col.StringNoPk(db)
  472. }
  473. sql = strings.TrimSpace(sql)
  474. sql += ", "
  475. }
  476. if len(pkList) > 1 {
  477. sql += "PRIMARY KEY ( "
  478. sql += strings.Join(pkList, ",")
  479. sql += " ), "
  480. }
  481. sql = sql[:len(sql)-2] + ")"
  482. sql += ";"
  483. return sql
  484. }
  485. func (db *mssql) ForUpdateSql(query string) string {
  486. return query
  487. }
  488. func (db *mssql) Filters() []core.Filter {
  489. return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}}
  490. }
  491. type odbcDriver struct {
  492. }
  493. func (p *odbcDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
  494. var dbName string
  495. if strings.HasPrefix(dataSourceName, "sqlserver://") {
  496. u, err := url.Parse(dataSourceName)
  497. if err != nil {
  498. return nil, err
  499. }
  500. dbName = u.Query().Get("database")
  501. } else {
  502. kv := strings.Split(dataSourceName, ";")
  503. for _, c := range kv {
  504. vv := strings.Split(strings.TrimSpace(c), "=")
  505. if len(vv) == 2 {
  506. switch strings.ToLower(vv[0]) {
  507. case "database":
  508. dbName = vv[1]
  509. }
  510. }
  511. }
  512. }
  513. if dbName == "" {
  514. return nil, errors.New("no db name provided")
  515. }
  516. return &core.Uri{DbName: dbName, DbType: core.MSSQL}, nil
  517. }