mssql.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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 dialects
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "xorm.io/xorm/core"
  13. "xorm.io/xorm/schemas"
  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. mssqlQuoter = schemas.Quoter{
  204. Prefix: '[',
  205. Suffix: ']',
  206. IsReserved: schemas.AlwaysReserve,
  207. }
  208. )
  209. type mssql struct {
  210. Base
  211. defaultVarchar string
  212. defaultChar string
  213. }
  214. func (db *mssql) Init(uri *URI) error {
  215. db.quoter = mssqlQuoter
  216. return db.Base.Init(db, uri)
  217. }
  218. func (db *mssql) SetParams(params map[string]string) {
  219. defaultVarchar, ok := params["DEFAULT_VARCHAR"]
  220. if ok {
  221. var t = strings.ToUpper(defaultVarchar)
  222. switch t {
  223. case "NVARCHAR", "VARCHAR":
  224. db.defaultVarchar = t
  225. default:
  226. db.defaultVarchar = "VARCHAR"
  227. }
  228. } else {
  229. db.defaultVarchar = "VARCHAR"
  230. }
  231. defaultChar, ok := params["DEFAULT_CHAR"]
  232. if ok {
  233. var t = strings.ToUpper(defaultChar)
  234. switch t {
  235. case "NCHAR", "CHAR":
  236. db.defaultChar = t
  237. default:
  238. db.defaultChar = "CHAR"
  239. }
  240. } else {
  241. db.defaultChar = "CHAR"
  242. }
  243. }
  244. func (db *mssql) SQLType(c *schemas.Column) string {
  245. var res string
  246. switch t := c.SQLType.Name; t {
  247. case schemas.Bool:
  248. res = schemas.Bit
  249. if strings.EqualFold(c.Default, "true") {
  250. c.Default = "1"
  251. } else if strings.EqualFold(c.Default, "false") {
  252. c.Default = "0"
  253. }
  254. return res
  255. case schemas.Serial:
  256. c.IsAutoIncrement = true
  257. c.IsPrimaryKey = true
  258. c.Nullable = false
  259. res = schemas.Int
  260. case schemas.BigSerial:
  261. c.IsAutoIncrement = true
  262. c.IsPrimaryKey = true
  263. c.Nullable = false
  264. res = schemas.BigInt
  265. case schemas.Bytea, schemas.Blob, schemas.Binary, schemas.TinyBlob, schemas.MediumBlob, schemas.LongBlob:
  266. res = schemas.VarBinary
  267. if c.Length == 0 {
  268. c.Length = 50
  269. }
  270. case schemas.TimeStamp:
  271. res = schemas.DateTime
  272. case schemas.TimeStampz:
  273. res = "DATETIMEOFFSET"
  274. c.Length = 7
  275. case schemas.MediumInt:
  276. res = schemas.Int
  277. case schemas.Text, schemas.MediumText, schemas.TinyText, schemas.LongText, schemas.Json:
  278. res = db.defaultVarchar + "(MAX)"
  279. case schemas.Double:
  280. res = schemas.Real
  281. case schemas.Uuid:
  282. res = schemas.Varchar
  283. c.Length = 40
  284. case schemas.TinyInt:
  285. res = schemas.TinyInt
  286. c.Length = 0
  287. case schemas.BigInt:
  288. res = schemas.BigInt
  289. c.Length = 0
  290. case schemas.NVarchar:
  291. res = t
  292. if c.Length == -1 {
  293. res += "(MAX)"
  294. }
  295. case schemas.Varchar:
  296. res = db.defaultVarchar
  297. if c.Length == -1 {
  298. res += "(MAX)"
  299. }
  300. case schemas.Char:
  301. res = db.defaultChar
  302. if c.Length == -1 {
  303. res += "(MAX)"
  304. }
  305. case schemas.NChar:
  306. res = t
  307. if c.Length == -1 {
  308. res += "(MAX)"
  309. }
  310. default:
  311. res = t
  312. }
  313. if res == schemas.Int || res == schemas.Bit || res == schemas.DateTime {
  314. return res
  315. }
  316. hasLen1 := (c.Length > 0)
  317. hasLen2 := (c.Length2 > 0)
  318. if hasLen2 {
  319. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  320. } else if hasLen1 {
  321. res += "(" + strconv.Itoa(c.Length) + ")"
  322. }
  323. return res
  324. }
  325. func (db *mssql) IsReserved(name string) bool {
  326. _, ok := mssqlReservedWords[strings.ToUpper(name)]
  327. return ok
  328. }
  329. func (db *mssql) SetQuotePolicy(quotePolicy QuotePolicy) {
  330. switch quotePolicy {
  331. case QuotePolicyNone:
  332. var q = mssqlQuoter
  333. q.IsReserved = schemas.AlwaysNoReserve
  334. db.quoter = q
  335. case QuotePolicyReserved:
  336. var q = mssqlQuoter
  337. q.IsReserved = db.IsReserved
  338. db.quoter = q
  339. case QuotePolicyAlways:
  340. fallthrough
  341. default:
  342. db.quoter = mssqlQuoter
  343. }
  344. }
  345. func (db *mssql) AutoIncrStr() string {
  346. return "IDENTITY"
  347. }
  348. func (db *mssql) DropTableSQL(tableName string) (string, bool) {
  349. return fmt.Sprintf("IF EXISTS (SELECT * FROM sysobjects WHERE id = "+
  350. "object_id(N'%s') and OBJECTPROPERTY(id, N'IsUserTable') = 1) "+
  351. "DROP TABLE \"%s\"", tableName, tableName), true
  352. }
  353. func (db *mssql) ModifyColumnSQL(tableName string, col *schemas.Column) string {
  354. s, _ := ColumnString(db.dialect, col, false)
  355. return fmt.Sprintf("ALTER TABLE %s ALTER COLUMN %s", tableName, s)
  356. }
  357. func (db *mssql) IndexCheckSQL(tableName, idxName string) (string, []interface{}) {
  358. args := []interface{}{idxName}
  359. sql := "select name from sysindexes where id=object_id('" + tableName + "') and name=?"
  360. return sql, args
  361. }
  362. func (db *mssql) IsColumnExist(queryer core.Queryer, ctx context.Context, tableName, colName string) (bool, error) {
  363. query := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
  364. return db.HasRecords(queryer, ctx, query, tableName, colName)
  365. }
  366. func (db *mssql) IsTableExist(queryer core.Queryer, ctx context.Context, tableName string) (bool, error) {
  367. sql := "select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsUserTable') = 1"
  368. return db.HasRecords(queryer, ctx, sql)
  369. }
  370. func (db *mssql) GetColumns(queryer core.Queryer, ctx context.Context, tableName string) ([]string, map[string]*schemas.Column, error) {
  371. args := []interface{}{}
  372. s := `select a.name as name, b.name as ctype,a.max_length,a.precision,a.scale,a.is_nullable as nullable,
  373. "default_is_null" = (CASE WHEN c.text is null THEN 1 ELSE 0 END),
  374. replace(replace(isnull(c.text,''),'(',''),')','') as vdefault,
  375. ISNULL(p.is_primary_key, 0), a.is_identity as is_identity
  376. from sys.columns a
  377. left join sys.types b on a.user_type_id=b.user_type_id
  378. left join sys.syscomments c on a.default_object_id=c.id
  379. LEFT OUTER JOIN (SELECT i.object_id, ic.column_id, i.is_primary_key
  380. FROM sys.indexes i
  381. LEFT JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
  382. WHERE i.is_primary_key = 1
  383. ) as p on p.object_id = a.object_id AND p.column_id = a.column_id
  384. where a.object_id=object_id('` + tableName + `')`
  385. rows, err := queryer.QueryContext(ctx, s, args...)
  386. if err != nil {
  387. return nil, nil, err
  388. }
  389. defer rows.Close()
  390. cols := make(map[string]*schemas.Column)
  391. colSeq := make([]string, 0)
  392. for rows.Next() {
  393. var name, ctype, vdefault string
  394. var maxLen, precision, scale int
  395. var nullable, isPK, defaultIsNull, isIncrement bool
  396. err = rows.Scan(&name, &ctype, &maxLen, &precision, &scale, &nullable, &defaultIsNull, &vdefault, &isPK, &isIncrement)
  397. if err != nil {
  398. return nil, nil, err
  399. }
  400. col := new(schemas.Column)
  401. col.Indexes = make(map[string]int)
  402. col.Name = strings.Trim(name, "` ")
  403. col.Nullable = nullable
  404. col.DefaultIsEmpty = defaultIsNull
  405. if !defaultIsNull {
  406. col.Default = vdefault
  407. }
  408. col.IsPrimaryKey = isPK
  409. col.IsAutoIncrement = isIncrement
  410. ct := strings.ToUpper(ctype)
  411. if ct == "DECIMAL" {
  412. col.Length = precision
  413. col.Length2 = scale
  414. } else {
  415. col.Length = maxLen
  416. }
  417. switch ct {
  418. case "DATETIMEOFFSET":
  419. col.SQLType = schemas.SQLType{Name: schemas.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
  420. case "NVARCHAR":
  421. col.SQLType = schemas.SQLType{Name: schemas.NVarchar, DefaultLength: 0, DefaultLength2: 0}
  422. if col.Length > 0 {
  423. col.Length /= 2
  424. col.Length2 /= 2
  425. }
  426. case "IMAGE":
  427. col.SQLType = schemas.SQLType{Name: schemas.VarBinary, DefaultLength: 0, DefaultLength2: 0}
  428. case "NCHAR":
  429. if col.Length > 0 {
  430. col.Length /= 2
  431. col.Length2 /= 2
  432. }
  433. fallthrough
  434. default:
  435. if _, ok := schemas.SqlTypes[ct]; ok {
  436. col.SQLType = schemas.SQLType{Name: ct, DefaultLength: 0, DefaultLength2: 0}
  437. } else {
  438. return nil, nil, fmt.Errorf("Unknown colType %v for %v - %v", ct, tableName, col.Name)
  439. }
  440. }
  441. cols[col.Name] = col
  442. colSeq = append(colSeq, col.Name)
  443. }
  444. return colSeq, cols, nil
  445. }
  446. func (db *mssql) GetTables(queryer core.Queryer, ctx context.Context) ([]*schemas.Table, error) {
  447. args := []interface{}{}
  448. s := `select name from sysobjects where xtype ='U'`
  449. rows, err := queryer.QueryContext(ctx, s, args...)
  450. if err != nil {
  451. return nil, err
  452. }
  453. defer rows.Close()
  454. tables := make([]*schemas.Table, 0)
  455. for rows.Next() {
  456. table := schemas.NewEmptyTable()
  457. var name string
  458. err = rows.Scan(&name)
  459. if err != nil {
  460. return nil, err
  461. }
  462. table.Name = strings.Trim(name, "` ")
  463. tables = append(tables, table)
  464. }
  465. return tables, nil
  466. }
  467. func (db *mssql) GetIndexes(queryer core.Queryer, ctx context.Context, tableName string) (map[string]*schemas.Index, error) {
  468. args := []interface{}{tableName}
  469. s := `SELECT
  470. IXS.NAME AS [INDEX_NAME],
  471. C.NAME AS [COLUMN_NAME],
  472. IXS.is_unique AS [IS_UNIQUE]
  473. FROM SYS.INDEXES IXS
  474. INNER JOIN SYS.INDEX_COLUMNS IXCS
  475. ON IXS.OBJECT_ID=IXCS.OBJECT_ID AND IXS.INDEX_ID = IXCS.INDEX_ID
  476. INNER JOIN SYS.COLUMNS C ON IXS.OBJECT_ID=C.OBJECT_ID
  477. AND IXCS.COLUMN_ID=C.COLUMN_ID
  478. WHERE IXS.TYPE_DESC='NONCLUSTERED' and OBJECT_NAME(IXS.OBJECT_ID) =?
  479. `
  480. rows, err := queryer.QueryContext(ctx, s, args...)
  481. if err != nil {
  482. return nil, err
  483. }
  484. defer rows.Close()
  485. indexes := make(map[string]*schemas.Index, 0)
  486. for rows.Next() {
  487. var indexType int
  488. var indexName, colName, isUnique string
  489. err = rows.Scan(&indexName, &colName, &isUnique)
  490. if err != nil {
  491. return nil, err
  492. }
  493. i, err := strconv.ParseBool(isUnique)
  494. if err != nil {
  495. return nil, err
  496. }
  497. if i {
  498. indexType = schemas.UniqueType
  499. } else {
  500. indexType = schemas.IndexType
  501. }
  502. colName = strings.Trim(colName, "` ")
  503. var isRegular bool
  504. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  505. indexName = indexName[5+len(tableName):]
  506. isRegular = true
  507. }
  508. var index *schemas.Index
  509. var ok bool
  510. if index, ok = indexes[indexName]; !ok {
  511. index = new(schemas.Index)
  512. index.Type = indexType
  513. index.Name = indexName
  514. index.IsRegular = isRegular
  515. indexes[indexName] = index
  516. }
  517. index.AddColumn(colName)
  518. }
  519. return indexes, nil
  520. }
  521. func (db *mssql) CreateTableSQL(table *schemas.Table, tableName string) ([]string, bool) {
  522. var sql string
  523. if tableName == "" {
  524. tableName = table.Name
  525. }
  526. sql = "IF NOT EXISTS (SELECT [name] FROM sys.tables WHERE [name] = '" + tableName + "' ) CREATE TABLE "
  527. sql += db.Quoter().Quote(tableName) + " ("
  528. pkList := table.PrimaryKeys
  529. for _, colName := range table.ColumnsSeq() {
  530. col := table.GetColumn(colName)
  531. s, _ := ColumnString(db, col, col.IsPrimaryKey && len(pkList) == 1)
  532. sql += s
  533. sql = strings.TrimSpace(sql)
  534. sql += ", "
  535. }
  536. if len(pkList) > 1 {
  537. sql += "PRIMARY KEY ( "
  538. sql += strings.Join(pkList, ",")
  539. sql += " ), "
  540. }
  541. sql = sql[:len(sql)-2] + ")"
  542. sql += ";"
  543. return []string{sql}, true
  544. }
  545. func (db *mssql) ForUpdateSQL(query string) string {
  546. return query
  547. }
  548. func (db *mssql) Filters() []Filter {
  549. return []Filter{}
  550. }
  551. type odbcDriver struct {
  552. }
  553. func (p *odbcDriver) Parse(driverName, dataSourceName string) (*URI, error) {
  554. var dbName string
  555. if strings.HasPrefix(dataSourceName, "sqlserver://") {
  556. u, err := url.Parse(dataSourceName)
  557. if err != nil {
  558. return nil, err
  559. }
  560. dbName = u.Query().Get("database")
  561. } else {
  562. kv := strings.Split(dataSourceName, ";")
  563. for _, c := range kv {
  564. vv := strings.Split(strings.TrimSpace(c), "=")
  565. if len(vv) == 2 {
  566. switch strings.ToLower(vv[0]) {
  567. case "database":
  568. dbName = vv[1]
  569. }
  570. }
  571. }
  572. }
  573. if dbName == "" {
  574. return nil, errors.New("no db name provided")
  575. }
  576. return &URI{DBName: dbName, DBType: schemas.MSSQL}, nil
  577. }