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 15KB

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