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.

mssql.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. "database/sql"
  8. "errors"
  9. "fmt"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "xorm.io/xorm/core"
  14. "xorm.io/xorm/schemas"
  15. )
  16. var (
  17. mssqlReservedWords = map[string]bool{
  18. "ADD": true,
  19. "EXTERNAL": true,
  20. "PROCEDURE": true,
  21. "ALL": true,
  22. "FETCH": true,
  23. "PUBLIC": true,
  24. "ALTER": true,
  25. "FILE": true,
  26. "RAISERROR": true,
  27. "AND": true,
  28. "FILLFACTOR": true,
  29. "READ": true,
  30. "ANY": true,
  31. "FOR": true,
  32. "READTEXT": true,
  33. "AS": true,
  34. "FOREIGN": true,
  35. "RECONFIGURE": true,
  36. "ASC": true,
  37. "FREETEXT": true,
  38. "REFERENCES": true,
  39. "AUTHORIZATION": true,
  40. "FREETEXTTABLE": true,
  41. "REPLICATION": true,
  42. "BACKUP": true,
  43. "FROM": true,
  44. "RESTORE": true,
  45. "BEGIN": true,
  46. "FULL": true,
  47. "RESTRICT": true,
  48. "BETWEEN": true,
  49. "FUNCTION": true,
  50. "RETURN": true,
  51. "BREAK": true,
  52. "GOTO": true,
  53. "REVERT": true,
  54. "BROWSE": true,
  55. "GRANT": true,
  56. "REVOKE": true,
  57. "BULK": true,
  58. "GROUP": true,
  59. "RIGHT": true,
  60. "BY": true,
  61. "HAVING": true,
  62. "ROLLBACK": true,
  63. "CASCADE": true,
  64. "HOLDLOCK": true,
  65. "ROWCOUNT": true,
  66. "CASE": true,
  67. "IDENTITY": true,
  68. "ROWGUIDCOL": true,
  69. "CHECK": true,
  70. "IDENTITY_INSERT": true,
  71. "RULE": true,
  72. "CHECKPOINT": true,
  73. "IDENTITYCOL": true,
  74. "SAVE": true,
  75. "CLOSE": true,
  76. "IF": true,
  77. "SCHEMA": true,
  78. "CLUSTERED": true,
  79. "IN": true,
  80. "SECURITYAUDIT": true,
  81. "COALESCE": true,
  82. "INDEX": true,
  83. "SELECT": true,
  84. "COLLATE": true,
  85. "INNER": true,
  86. "SEMANTICKEYPHRASETABLE": true,
  87. "COLUMN": true,
  88. "INSERT": true,
  89. "SEMANTICSIMILARITYDETAILSTABLE": true,
  90. "COMMIT": true,
  91. "INTERSECT": true,
  92. "SEMANTICSIMILARITYTABLE": true,
  93. "COMPUTE": true,
  94. "INTO": true,
  95. "SESSION_USER": true,
  96. "CONSTRAINT": true,
  97. "IS": true,
  98. "SET": true,
  99. "CONTAINS": true,
  100. "JOIN": true,
  101. "SETUSER": true,
  102. "CONTAINSTABLE": true,
  103. "KEY": true,
  104. "SHUTDOWN": true,
  105. "CONTINUE": true,
  106. "KILL": true,
  107. "SOME": true,
  108. "CONVERT": true,
  109. "LEFT": true,
  110. "STATISTICS": true,
  111. "CREATE": true,
  112. "LIKE": true,
  113. "SYSTEM_USER": true,
  114. "CROSS": true,
  115. "LINENO": true,
  116. "TABLE": true,
  117. "CURRENT": true,
  118. "LOAD": true,
  119. "TABLESAMPLE": true,
  120. "CURRENT_DATE": true,
  121. "MERGE": true,
  122. "TEXTSIZE": true,
  123. "CURRENT_TIME": true,
  124. "NATIONAL": true,
  125. "THEN": true,
  126. "CURRENT_TIMESTAMP": true,
  127. "NOCHECK": true,
  128. "TO": true,
  129. "CURRENT_USER": true,
  130. "NONCLUSTERED": true,
  131. "TOP": true,
  132. "CURSOR": true,
  133. "NOT": true,
  134. "TRAN": true,
  135. "DATABASE": true,
  136. "NULL": true,
  137. "TRANSACTION": true,
  138. "DBCC": true,
  139. "NULLIF": true,
  140. "TRIGGER": true,
  141. "DEALLOCATE": true,
  142. "OF": true,
  143. "TRUNCATE": true,
  144. "DECLARE": true,
  145. "OFF": true,
  146. "TRY_CONVERT": true,
  147. "DEFAULT": true,
  148. "OFFSETS": true,
  149. "TSEQUAL": true,
  150. "DELETE": true,
  151. "ON": true,
  152. "UNION": true,
  153. "DENY": true,
  154. "OPEN": true,
  155. "UNIQUE": true,
  156. "DESC": true,
  157. "OPENDATASOURCE": true,
  158. "UNPIVOT": true,
  159. "DISK": true,
  160. "OPENQUERY": true,
  161. "UPDATE": true,
  162. "DISTINCT": true,
  163. "OPENROWSET": true,
  164. "UPDATETEXT": true,
  165. "DISTRIBUTED": true,
  166. "OPENXML": true,
  167. "USE": true,
  168. "DOUBLE": true,
  169. "OPTION": true,
  170. "USER": true,
  171. "DROP": true,
  172. "OR": true,
  173. "VALUES": true,
  174. "DUMP": true,
  175. "ORDER": true,
  176. "VARYING": true,
  177. "ELSE": true,
  178. "OUTER": true,
  179. "VIEW": true,
  180. "END": true,
  181. "OVER": true,
  182. "WAITFOR": true,
  183. "ERRLVL": true,
  184. "PERCENT": true,
  185. "WHEN": true,
  186. "ESCAPE": true,
  187. "PIVOT": true,
  188. "WHERE": true,
  189. "EXCEPT": true,
  190. "PLAN": true,
  191. "WHILE": true,
  192. "EXEC": true,
  193. "PRECISION": true,
  194. "WITH": true,
  195. "EXECUTE": true,
  196. "PRIMARY": true,
  197. "WITHIN": true,
  198. "EXISTS": true,
  199. "PRINT": true,
  200. "WRITETEXT": true,
  201. "EXIT": true,
  202. "PROC": true,
  203. }
  204. mssqlQuoter = schemas.Quoter{
  205. Prefix: '[',
  206. Suffix: ']',
  207. IsReserved: schemas.AlwaysReserve,
  208. }
  209. )
  210. type mssql struct {
  211. Base
  212. defaultVarchar string
  213. defaultChar string
  214. }
  215. func (db *mssql) Init(uri *URI) error {
  216. db.quoter = mssqlQuoter
  217. db.defaultChar = "CHAR"
  218. db.defaultVarchar = "VARCHAR"
  219. return db.Base.Init(db, uri)
  220. }
  221. func (db *mssql) SetParams(params map[string]string) {
  222. defaultVarchar, ok := params["DEFAULT_VARCHAR"]
  223. if ok {
  224. var t = strings.ToUpper(defaultVarchar)
  225. switch t {
  226. case "NVARCHAR", "VARCHAR":
  227. db.defaultVarchar = t
  228. default:
  229. db.defaultVarchar = "VARCHAR"
  230. }
  231. } else {
  232. db.defaultVarchar = "VARCHAR"
  233. }
  234. defaultChar, ok := params["DEFAULT_CHAR"]
  235. if ok {
  236. var t = strings.ToUpper(defaultChar)
  237. switch t {
  238. case "NCHAR", "CHAR":
  239. db.defaultChar = t
  240. default:
  241. db.defaultChar = "CHAR"
  242. }
  243. } else {
  244. db.defaultChar = "CHAR"
  245. }
  246. }
  247. func (db *mssql) Version(ctx context.Context, queryer core.Queryer) (*schemas.Version, error) {
  248. rows, err := queryer.QueryContext(ctx,
  249. "SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel') AS ProductLevel, SERVERPROPERTY ('edition') AS ProductEdition")
  250. if err != nil {
  251. return nil, err
  252. }
  253. defer rows.Close()
  254. var version, level, edition string
  255. if !rows.Next() {
  256. if rows.Err() != nil {
  257. return nil, rows.Err()
  258. }
  259. return nil, errors.New("unknow version")
  260. }
  261. if err := rows.Scan(&version, &level, &edition); err != nil {
  262. return nil, err
  263. }
  264. // MSSQL: Microsoft SQL Server 2017 (RTM-CU13) (KB4466404) - 14.0.3048.4 (X64) Nov 30 2018 12:57:58 Copyright (C) 2017 Microsoft Corporation Developer Edition (64-bit) on Linux (Ubuntu 16.04.5 LTS)
  265. return &schemas.Version{
  266. Number: version,
  267. Level: level,
  268. Edition: edition,
  269. }, nil
  270. }
  271. func (db *mssql) SQLType(c *schemas.Column) string {
  272. var res string
  273. switch t := c.SQLType.Name; t {
  274. case schemas.Bool, schemas.Boolean:
  275. res = schemas.Bit
  276. if strings.EqualFold(c.Default, "true") {
  277. c.Default = "1"
  278. } else if strings.EqualFold(c.Default, "false") {
  279. c.Default = "0"
  280. }
  281. return res
  282. case schemas.Serial:
  283. c.IsAutoIncrement = true
  284. c.IsPrimaryKey = true
  285. c.Nullable = false
  286. res = schemas.Int
  287. case schemas.BigSerial:
  288. c.IsAutoIncrement = true
  289. c.IsPrimaryKey = true
  290. c.Nullable = false
  291. res = schemas.BigInt
  292. case schemas.Bytea, schemas.Binary:
  293. res = schemas.VarBinary
  294. if c.Length == 0 {
  295. c.Length = 50
  296. }
  297. case schemas.Blob, schemas.TinyBlob, schemas.MediumBlob, schemas.LongBlob:
  298. res = schemas.VarBinary
  299. if c.Length == 0 {
  300. res += "(MAX)"
  301. }
  302. case schemas.TimeStamp, schemas.DateTime:
  303. if c.Length > 3 {
  304. res = "DATETIME2"
  305. } else {
  306. return schemas.DateTime
  307. }
  308. case schemas.TimeStampz:
  309. res = "DATETIMEOFFSET"
  310. c.Length = 7
  311. case schemas.MediumInt, schemas.TinyInt, schemas.SmallInt, schemas.UnsignedMediumInt, schemas.UnsignedTinyInt, schemas.UnsignedSmallInt:
  312. res = schemas.Int
  313. case schemas.Text, schemas.MediumText, schemas.TinyText, schemas.LongText, schemas.Json:
  314. res = db.defaultVarchar + "(MAX)"
  315. case schemas.Double:
  316. res = schemas.Real
  317. case schemas.Uuid:
  318. res = schemas.Varchar
  319. c.Length = 40
  320. case schemas.TinyInt:
  321. res = schemas.TinyInt
  322. c.Length = 0
  323. case schemas.BigInt, schemas.UnsignedBigInt, schemas.UnsignedInt:
  324. res = schemas.BigInt
  325. c.Length = 0
  326. case schemas.NVarchar:
  327. res = t
  328. if c.Length == -1 {
  329. res += "(MAX)"
  330. }
  331. case schemas.Varchar:
  332. res = db.defaultVarchar
  333. if c.Length == -1 {
  334. res += "(MAX)"
  335. }
  336. case schemas.Char:
  337. res = db.defaultChar
  338. if c.Length == -1 {
  339. res += "(MAX)"
  340. }
  341. case schemas.NChar:
  342. res = t
  343. if c.Length == -1 {
  344. res += "(MAX)"
  345. }
  346. default:
  347. res = t
  348. }
  349. if res == schemas.Int || res == schemas.Bit {
  350. return res
  351. }
  352. hasLen1 := (c.Length > 0)
  353. hasLen2 := (c.Length2 > 0)
  354. if hasLen2 {
  355. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  356. } else if hasLen1 {
  357. res += "(" + strconv.Itoa(c.Length) + ")"
  358. }
  359. return res
  360. }
  361. func (db *mssql) ColumnTypeKind(t string) int {
  362. switch strings.ToUpper(t) {
  363. case "DATE", "DATETIME", "DATETIME2", "TIME":
  364. return schemas.TIME_TYPE
  365. case "VARCHAR", "TEXT", "CHAR", "NVARCHAR", "NCHAR", "NTEXT":
  366. return schemas.TEXT_TYPE
  367. case "FLOAT", "REAL", "BIGINT", "DATETIMEOFFSET", "TINYINT", "SMALLINT", "INT":
  368. return schemas.NUMERIC_TYPE
  369. default:
  370. return schemas.UNKNOW_TYPE
  371. }
  372. }
  373. func (db *mssql) IsReserved(name string) bool {
  374. _, ok := mssqlReservedWords[strings.ToUpper(name)]
  375. return ok
  376. }
  377. func (db *mssql) SetQuotePolicy(quotePolicy QuotePolicy) {
  378. switch quotePolicy {
  379. case QuotePolicyNone:
  380. var q = mssqlQuoter
  381. q.IsReserved = schemas.AlwaysNoReserve
  382. db.quoter = q
  383. case QuotePolicyReserved:
  384. var q = mssqlQuoter
  385. q.IsReserved = db.IsReserved
  386. db.quoter = q
  387. case QuotePolicyAlways:
  388. fallthrough
  389. default:
  390. db.quoter = mssqlQuoter
  391. }
  392. }
  393. func (db *mssql) AutoIncrStr() string {
  394. return "IDENTITY"
  395. }
  396. func (db *mssql) DropTableSQL(tableName string) (string, bool) {
  397. return fmt.Sprintf("IF EXISTS (SELECT * FROM sysobjects WHERE id = "+
  398. "object_id(N'%s') and OBJECTPROPERTY(id, N'IsUserTable') = 1) "+
  399. "DROP TABLE \"%s\"", tableName, tableName), true
  400. }
  401. func (db *mssql) ModifyColumnSQL(tableName string, col *schemas.Column) string {
  402. s, _ := ColumnString(db.dialect, col, false)
  403. return fmt.Sprintf("ALTER TABLE %s ALTER COLUMN %s", tableName, s)
  404. }
  405. func (db *mssql) IndexCheckSQL(tableName, idxName string) (string, []interface{}) {
  406. args := []interface{}{idxName}
  407. sql := "select name from sysindexes where id=object_id('" + tableName + "') and name=?"
  408. return sql, args
  409. }
  410. func (db *mssql) IsColumnExist(queryer core.Queryer, ctx context.Context, tableName, colName string) (bool, error) {
  411. query := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
  412. return db.HasRecords(queryer, ctx, query, tableName, colName)
  413. }
  414. func (db *mssql) IsTableExist(queryer core.Queryer, ctx context.Context, tableName string) (bool, error) {
  415. sql := "select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsUserTable') = 1"
  416. return db.HasRecords(queryer, ctx, sql)
  417. }
  418. func (db *mssql) GetColumns(queryer core.Queryer, ctx context.Context, tableName string) ([]string, map[string]*schemas.Column, error) {
  419. args := []interface{}{}
  420. s := `select a.name as name, b.name as ctype,a.max_length,a.precision,a.scale,a.is_nullable as nullable,
  421. "default_is_null" = (CASE WHEN c.text is null THEN 1 ELSE 0 END),
  422. replace(replace(isnull(c.text,''),'(',''),')','') as vdefault,
  423. ISNULL(p.is_primary_key, 0), a.is_identity as is_identity
  424. from sys.columns a
  425. left join sys.types b on a.user_type_id=b.user_type_id
  426. left join sys.syscomments c on a.default_object_id=c.id
  427. LEFT OUTER JOIN (SELECT i.object_id, ic.column_id, i.is_primary_key
  428. FROM sys.indexes i
  429. LEFT JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
  430. WHERE i.is_primary_key = 1
  431. ) as p on p.object_id = a.object_id AND p.column_id = a.column_id
  432. where a.object_id=object_id('` + tableName + `')`
  433. rows, err := queryer.QueryContext(ctx, s, args...)
  434. if err != nil {
  435. return nil, nil, err
  436. }
  437. defer rows.Close()
  438. cols := make(map[string]*schemas.Column)
  439. colSeq := make([]string, 0)
  440. for rows.Next() {
  441. var name, ctype, vdefault string
  442. var maxLen, precision, scale int
  443. var nullable, isPK, defaultIsNull, isIncrement bool
  444. err = rows.Scan(&name, &ctype, &maxLen, &precision, &scale, &nullable, &defaultIsNull, &vdefault, &isPK, &isIncrement)
  445. if err != nil {
  446. return nil, nil, err
  447. }
  448. col := new(schemas.Column)
  449. col.Indexes = make(map[string]int)
  450. col.Name = strings.Trim(name, "` ")
  451. col.Nullable = nullable
  452. col.DefaultIsEmpty = defaultIsNull
  453. if !defaultIsNull {
  454. col.Default = vdefault
  455. }
  456. col.IsPrimaryKey = isPK
  457. col.IsAutoIncrement = isIncrement
  458. ct := strings.ToUpper(ctype)
  459. if ct == "DECIMAL" {
  460. col.Length = precision
  461. col.Length2 = scale
  462. } else {
  463. col.Length = maxLen
  464. }
  465. switch ct {
  466. case "DATETIMEOFFSET":
  467. col.SQLType = schemas.SQLType{Name: schemas.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
  468. case "NVARCHAR":
  469. col.SQLType = schemas.SQLType{Name: schemas.NVarchar, DefaultLength: 0, DefaultLength2: 0}
  470. if col.Length > 0 {
  471. col.Length /= 2
  472. col.Length2 /= 2
  473. }
  474. case "DATETIME2":
  475. col.SQLType = schemas.SQLType{Name: schemas.DateTime, DefaultLength: 7, DefaultLength2: 0}
  476. col.Length = scale
  477. case "DATETIME":
  478. col.SQLType = schemas.SQLType{Name: schemas.DateTime, DefaultLength: 3, DefaultLength2: 0}
  479. col.Length = scale
  480. case "IMAGE":
  481. col.SQLType = schemas.SQLType{Name: schemas.VarBinary, DefaultLength: 0, DefaultLength2: 0}
  482. case "NCHAR":
  483. if col.Length > 0 {
  484. col.Length /= 2
  485. col.Length2 /= 2
  486. }
  487. fallthrough
  488. default:
  489. if _, ok := schemas.SqlTypes[ct]; ok {
  490. col.SQLType = schemas.SQLType{Name: ct, DefaultLength: 0, DefaultLength2: 0}
  491. } else {
  492. return nil, nil, fmt.Errorf("Unknown colType %v for %v - %v", ct, tableName, col.Name)
  493. }
  494. }
  495. cols[col.Name] = col
  496. colSeq = append(colSeq, col.Name)
  497. }
  498. if rows.Err() != nil {
  499. return nil, nil, rows.Err()
  500. }
  501. return colSeq, cols, nil
  502. }
  503. func (db *mssql) GetTables(queryer core.Queryer, ctx context.Context) ([]*schemas.Table, error) {
  504. args := []interface{}{}
  505. s := `select name from sysobjects where xtype ='U'`
  506. rows, err := queryer.QueryContext(ctx, s, args...)
  507. if err != nil {
  508. return nil, err
  509. }
  510. defer rows.Close()
  511. tables := make([]*schemas.Table, 0)
  512. for rows.Next() {
  513. table := schemas.NewEmptyTable()
  514. var name string
  515. err = rows.Scan(&name)
  516. if err != nil {
  517. return nil, err
  518. }
  519. table.Name = strings.Trim(name, "` ")
  520. tables = append(tables, table)
  521. }
  522. if rows.Err() != nil {
  523. return nil, rows.Err()
  524. }
  525. return tables, nil
  526. }
  527. func (db *mssql) GetIndexes(queryer core.Queryer, ctx context.Context, tableName string) (map[string]*schemas.Index, error) {
  528. args := []interface{}{tableName}
  529. s := `SELECT
  530. IXS.NAME AS [INDEX_NAME],
  531. C.NAME AS [COLUMN_NAME],
  532. IXS.is_unique AS [IS_UNIQUE]
  533. FROM SYS.INDEXES IXS
  534. INNER JOIN SYS.INDEX_COLUMNS IXCS
  535. ON IXS.OBJECT_ID=IXCS.OBJECT_ID AND IXS.INDEX_ID = IXCS.INDEX_ID
  536. INNER JOIN SYS.COLUMNS C ON IXS.OBJECT_ID=C.OBJECT_ID
  537. AND IXCS.COLUMN_ID=C.COLUMN_ID
  538. WHERE IXS.TYPE_DESC='NONCLUSTERED' and OBJECT_NAME(IXS.OBJECT_ID) =?
  539. `
  540. rows, err := queryer.QueryContext(ctx, s, args...)
  541. if err != nil {
  542. return nil, err
  543. }
  544. defer rows.Close()
  545. indexes := make(map[string]*schemas.Index)
  546. for rows.Next() {
  547. var indexType int
  548. var indexName, colName, isUnique string
  549. err = rows.Scan(&indexName, &colName, &isUnique)
  550. if err != nil {
  551. return nil, err
  552. }
  553. i, err := strconv.ParseBool(isUnique)
  554. if err != nil {
  555. return nil, err
  556. }
  557. if i {
  558. indexType = schemas.UniqueType
  559. } else {
  560. indexType = schemas.IndexType
  561. }
  562. colName = strings.Trim(colName, "` ")
  563. var isRegular bool
  564. if (strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName)) && len(indexName) > (5+len(tableName)) {
  565. indexName = indexName[5+len(tableName):]
  566. isRegular = true
  567. }
  568. var index *schemas.Index
  569. var ok bool
  570. if index, ok = indexes[indexName]; !ok {
  571. index = new(schemas.Index)
  572. index.Type = indexType
  573. index.Name = indexName
  574. index.IsRegular = isRegular
  575. indexes[indexName] = index
  576. }
  577. index.AddColumn(colName)
  578. }
  579. if rows.Err() != nil {
  580. return nil, rows.Err()
  581. }
  582. return indexes, nil
  583. }
  584. func (db *mssql) CreateTableSQL(table *schemas.Table, tableName string) ([]string, bool) {
  585. if tableName == "" {
  586. tableName = table.Name
  587. }
  588. quoter := db.dialect.Quoter()
  589. var b strings.Builder
  590. b.WriteString("IF NOT EXISTS (SELECT [name] FROM sys.tables WHERE [name] = '")
  591. quoter.QuoteTo(&b, tableName)
  592. b.WriteString("' ) CREATE TABLE ")
  593. quoter.QuoteTo(&b, tableName)
  594. b.WriteString(" (")
  595. for i, colName := range table.ColumnsSeq() {
  596. col := table.GetColumn(colName)
  597. s, _ := ColumnString(db.dialect, col, col.IsPrimaryKey && len(table.PrimaryKeys) == 1)
  598. b.WriteString(s)
  599. if i != len(table.ColumnsSeq())-1 {
  600. b.WriteString(", ")
  601. }
  602. }
  603. if len(table.PrimaryKeys) > 1 {
  604. b.WriteString(", PRIMARY KEY (")
  605. b.WriteString(quoter.Join(table.PrimaryKeys, ","))
  606. b.WriteString(")")
  607. }
  608. b.WriteString(")")
  609. return []string{b.String()}, true
  610. }
  611. func (db *mssql) ForUpdateSQL(query string) string {
  612. return query
  613. }
  614. func (db *mssql) Filters() []Filter {
  615. return []Filter{}
  616. }
  617. type odbcDriver struct {
  618. baseDriver
  619. }
  620. func (p *odbcDriver) Features() *DriverFeatures {
  621. return &DriverFeatures{
  622. SupportReturnInsertedID: false,
  623. }
  624. }
  625. func (p *odbcDriver) Parse(driverName, dataSourceName string) (*URI, error) {
  626. var dbName string
  627. if strings.HasPrefix(dataSourceName, "sqlserver://") {
  628. u, err := url.Parse(dataSourceName)
  629. if err != nil {
  630. return nil, err
  631. }
  632. dbName = u.Query().Get("database")
  633. } else {
  634. kv := strings.Split(dataSourceName, ";")
  635. for _, c := range kv {
  636. vv := strings.Split(strings.TrimSpace(c), "=")
  637. if len(vv) == 2 {
  638. if strings.ToLower(vv[0]) == "database" {
  639. dbName = vv[1]
  640. }
  641. }
  642. }
  643. }
  644. if dbName == "" {
  645. return nil, errors.New("no db name provided")
  646. }
  647. return &URI{DBName: dbName, DBType: schemas.MSSQL}, nil
  648. }
  649. func (p *odbcDriver) GenScanResult(colType string) (interface{}, error) {
  650. switch colType {
  651. case "VARCHAR", "TEXT", "CHAR", "NVARCHAR", "NCHAR", "NTEXT":
  652. fallthrough
  653. case "DATE", "DATETIME", "DATETIME2", "TIME":
  654. var s sql.NullString
  655. return &s, nil
  656. case "FLOAT", "REAL":
  657. var s sql.NullFloat64
  658. return &s, nil
  659. case "BIGINT", "DATETIMEOFFSET":
  660. var s sql.NullInt64
  661. return &s, nil
  662. case "TINYINT", "SMALLINT", "INT":
  663. var s sql.NullInt32
  664. return &s, nil
  665. default:
  666. var r sql.RawBytes
  667. return &r, nil
  668. }
  669. }