-
Notifications
You must be signed in to change notification settings - Fork 535
/
mssql.go
653 lines (573 loc) · 17.7 KB
/
mssql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package driver
import (
"database/sql"
"embed"
"encoding/base64"
"fmt"
"io/fs"
"net/url"
"strings"
// Side effect import go-mssqldb
"github.com/friendsofgo/errors"
_ "github.com/microsoft/go-mssqldb"
"github.com/volatiletech/strmangle"
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/volatiletech/sqlboiler/v4/importers"
)
//go:embed override
var templates embed.FS
func init() {
drivers.RegisterFromInit("mssql", &MSSQLDriver{})
}
// Assemble is more useful for calling into the library so you don't
// have to instantiate an empty type.
func Assemble(config drivers.Config) (dbinfo *drivers.DBInfo, err error) {
driver := MSSQLDriver{}
return driver.Assemble(config)
}
// MSSQLDriver holds the database connection string and a handle
// to the database connection.
type MSSQLDriver struct {
connStr string
conn *sql.DB
configForeignKeys []drivers.ForeignKey
}
// Templates that should be added/overridden
func (MSSQLDriver) Templates() (map[string]string, error) {
tpls := make(map[string]string)
fs.WalkDir(templates, "override", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
b, err := fs.ReadFile(templates, path)
if err != nil {
return err
}
tpls[strings.Replace(path, "override/", "", 1)] = base64.StdEncoding.EncodeToString(b)
return nil
})
return tpls, nil
}
// Assemble all the information we need to provide back to the driver
func (m *MSSQLDriver) Assemble(config drivers.Config) (dbinfo *drivers.DBInfo, err error) {
defer func() {
if r := recover(); r != nil && err == nil {
dbinfo = nil
err = r.(error)
}
}()
user := config.MustString(drivers.ConfigUser)
pass, _ := config.String(drivers.ConfigPass)
dbname := config.MustString(drivers.ConfigDBName)
host := config.MustString(drivers.ConfigHost)
port := config.DefaultInt(drivers.ConfigPort, 1433)
sslmode := config.DefaultString(drivers.ConfigSSLMode, "true")
schema := config.DefaultString(drivers.ConfigSchema, "dbo")
whitelist, _ := config.StringSlice(drivers.ConfigWhitelist)
blacklist, _ := config.StringSlice(drivers.ConfigBlacklist)
concurrency := config.DefaultInt(drivers.ConfigConcurrency, drivers.DefaultConcurrency)
m.connStr = MSSQLBuildQueryString(user, pass, dbname, host, port, sslmode)
m.configForeignKeys = config.MustForeignKeys(drivers.ConfigForeignKeys)
m.conn, err = sql.Open("mssql", m.connStr)
if err != nil {
return nil, errors.Wrap(err, "sqlboiler-mssql failed to connect to database")
}
defer func() {
if e := m.conn.Close(); e != nil {
dbinfo = nil
err = e
}
}()
dbinfo = &drivers.DBInfo{
Schema: schema,
Dialect: drivers.Dialect{
LQ: '[',
RQ: ']',
UseIndexPlaceholders: true,
UseSchema: true,
UseDefaultKeyword: true,
UseTopClause: true,
UseOutputClause: true,
UseCaseWhenExistsClause: true,
},
}
dbinfo.Tables, err = drivers.TablesConcurrently(m, schema, whitelist, blacklist, concurrency)
if err != nil {
return nil, err
}
return dbinfo, err
}
// MSSQLBuildQueryString builds a query string for MSSQL.
func MSSQLBuildQueryString(user, pass, dbname, host string, port int, sslmode string) string {
query := url.Values{}
query.Add("database", dbname)
query.Add("encrypt", sslmode)
u := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword(user, pass),
Host: fmt.Sprintf("%s:%d", host, port),
RawQuery: query.Encode(),
}
// If the host is an "sqlserver instance" then we set the Path not the Host
// so the url package doesn't escape the /
if strings.Contains(host, "/") {
u.Path = host
u.Host = ""
}
return u.String()
}
// TableNames connects to the postgres database and
// retrieves all table names from the information_schema where the
// table schema is schema. It uses a whitelist and blacklist.
func (m *MSSQLDriver) TableNames(schema string, whitelist, blacklist []string) ([]string, error) {
var names []string
query := `
SELECT table_name
FROM information_schema.tables
WHERE table_schema = ? AND table_type = 'BASE TABLE'`
args := []interface{}{schema}
if len(whitelist) > 0 {
tables := drivers.TablesFromList(whitelist)
if len(tables) > 0 {
query += fmt.Sprintf(" AND table_name IN (%s)", strings.Repeat(",?", len(tables))[1:])
for _, w := range tables {
args = append(args, w)
}
}
} else if len(blacklist) > 0 {
tables := drivers.TablesFromList(blacklist)
if len(tables) > 0 {
query += fmt.Sprintf(" AND table_name not IN (%s)", strings.Repeat(",?", len(tables))[1:])
for _, b := range tables {
args = append(args, b)
}
}
}
query += ` ORDER BY table_name;`
rows, err := m.conn.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
names = append(names, name)
}
return names, nil
}
// ViewNames connects to the postgres database and
// retrieves all view names from the information_schema where the
// view schema is schema. It uses a whitelist and blacklist.
func (m *MSSQLDriver) ViewNames(schema string, whitelist, blacklist []string) ([]string, error) {
var names []string
query := `select table_name from information_schema.views where table_schema = ?`
args := []interface{}{schema}
if len(whitelist) > 0 {
tables := drivers.TablesFromList(whitelist)
if len(tables) > 0 {
query += fmt.Sprintf(" and table_name in (%s)", strings.Repeat(",?", len(tables))[1:])
for _, w := range tables {
args = append(args, w)
}
}
} else if len(blacklist) > 0 {
tables := drivers.TablesFromList(blacklist)
if len(tables) > 0 {
query += fmt.Sprintf(" and table_name not in (%s)", strings.Repeat(",?", len(tables))[1:])
for _, b := range tables {
args = append(args, b)
}
}
}
query += ` order by table_name;`
rows, err := m.conn.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
names = append(names, name)
}
return names, nil
}
// ViewCapabilities return what actions are allowed for a view.
func (m *MSSQLDriver) ViewCapabilities(schema, name string) (drivers.ViewCapabilities, error) {
// This depends on the specific query and is not possible to ensure
// from just the schema
capabilities := drivers.ViewCapabilities{
CanInsert: false,
CanUpsert: false,
}
return capabilities, nil
}
func (m *MSSQLDriver) ViewColumns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {
return m.Columns(schema, tableName, whitelist, blacklist)
}
// Columns takes a table name and attempts to retrieve the table information
// from the database information_schema.columns. It retrieves the column names
// and column types and returns those as a []Column after TranslateColumnType()
// converts the SQL types to Go types, for example: "varchar" to "string"
func (m *MSSQLDriver) Columns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {
var columns []drivers.Column
args := []interface{}{schema, tableName}
query := `
SELECT column_name,
CASE
WHEN character_maximum_length IS NULL THEN data_type
ELSE data_type + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
END AS full_type,
data_type,
column_default,
CASE
WHEN is_nullable = 'YES' THEN 1
ELSE 0
END AS is_nullable,
CASE
WHEN EXISTS (SELECT c.column_name
FROM information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_name = kcu.table_name
AND tc.table_schema = kcu.table_schema
WHERE c.column_name = kcu.column_name
AND tc.table_name = c.table_name
AND (tc.constraint_type = 'PRIMARY KEY' OR tc.constraint_type = 'UNIQUE')
AND (SELECT COUNT(*)
FROM information_schema.key_column_usage
WHERE table_schema = kcu.table_schema
AND table_name = tc.table_name
AND constraint_name = tc.constraint_name) = 1) THEN 1
ELSE 0
END AS is_unique,
COLUMNPROPERTY(object_id($1 + '.' + $2), c.column_name, 'IsIdentity') as is_identity,
COLUMNPROPERTY(object_id($1 + '.' + $2), c.column_name, 'IsComputed') as is_computed
FROM information_schema.columns c
WHERE table_schema = $1 AND table_name = $2`
if len(whitelist) > 0 {
cols := drivers.ColumnsFromList(whitelist, tableName)
if len(cols) > 0 {
query += fmt.Sprintf(" and c.column_name in (%s)", strmangle.Placeholders(true, len(cols), 3, 1))
for _, w := range cols {
args = append(args, w)
}
}
} else if len(blacklist) > 0 {
cols := drivers.ColumnsFromList(blacklist, tableName)
if len(cols) > 0 {
query += fmt.Sprintf(" and c.column_name not in (%s)", strmangle.Placeholders(true, len(cols), 3, 1))
for _, w := range cols {
args = append(args, w)
}
}
}
query += ` ORDER BY ordinal_position;`
rows, err := m.conn.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var colName, colType, colFullType string
var nullable, unique, identity, computed bool
var defaultValue *string
if err := rows.Scan(&colName, &colFullType, &colType, &defaultValue, &nullable, &unique, &identity, &computed); err != nil {
return nil, errors.Wrapf(err, "unable to scan for table %s", tableName)
}
computed = computed || strings.EqualFold(colType, "timestamp") || strings.EqualFold(colType, "rowversion")
column := drivers.Column{
Name: colName,
FullDBType: colFullType,
DBType: colType,
Nullable: nullable,
Unique: unique,
AutoGenerated: computed || identity,
}
if defaultValue != nil {
column.Default = *defaultValue
}
// A generated column technically has a default value
if column.Default == "" && column.AutoGenerated {
column.Default = "AUTO_GENERATED"
}
columns = append(columns, column)
}
return columns, nil
}
// PrimaryKeyInfo looks up the primary key for a table.
func (m *MSSQLDriver) PrimaryKeyInfo(schema, tableName string) (*drivers.PrimaryKey, error) {
pkey := &drivers.PrimaryKey{}
var err error
query := `
SELECT constraint_name
FROM information_schema.table_constraints
WHERE table_name = ? AND constraint_type = 'PRIMARY KEY' AND table_schema = ?;`
row := m.conn.QueryRow(query, tableName, schema)
if err = row.Scan(&pkey.Name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
queryColumns := `
SELECT column_name
FROM information_schema.key_column_usage
WHERE table_name = ? AND constraint_name = ? AND table_schema = ?
ORDER BY ordinal_position;`
var rows *sql.Rows
if rows, err = m.conn.Query(queryColumns, tableName, pkey.Name, schema); err != nil {
return nil, err
}
defer rows.Close()
var columns []string
for rows.Next() {
var column string
err = rows.Scan(&column)
if err != nil {
return nil, err
}
columns = append(columns, column)
}
if err = rows.Err(); err != nil {
return nil, err
}
pkey.Columns = columns
return pkey, nil
}
// ForeignKeyInfo retrieves the foreign keys for a given table name.
func (m *MSSQLDriver) ForeignKeyInfo(schema, tableName string) ([]drivers.ForeignKey, error) {
dbForeignKeys, err := m.foreignKeyInfoFromDB(schema, tableName)
if err != nil {
return nil, errors.Wrap(err, "read foreign keys info from db")
}
return drivers.CombineConfigAndDBForeignKeys(m.configForeignKeys, tableName, dbForeignKeys), nil
}
func (m *MSSQLDriver) foreignKeyInfoFromDB(schema, tableName string) ([]drivers.ForeignKey, error) {
var fkeys []drivers.ForeignKey
query := `
SELECT ccu.constraint_name ,
ccu.table_name AS local_table ,
ccu.column_name AS local_column ,
kcu.table_name AS foreign_table ,
kcu.column_name AS foreign_column
FROM information_schema.constraint_column_usage ccu
INNER JOIN information_schema.referential_constraints rc ON ccu.constraint_name = rc.constraint_name
INNER JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = rc.unique_constraint_name
WHERE ccu.table_schema = ?
AND ccu.constraint_schema = ?
AND ccu.table_name = ?
ORDER BY ccu.constraint_name, local_table, local_column, foreign_table, foreign_column
`
var rows *sql.Rows
var err error
if rows, err = m.conn.Query(query, schema, schema, tableName); err != nil {
return nil, err
}
for rows.Next() {
var fkey drivers.ForeignKey
var sourceTable string
fkey.Table = tableName
err = rows.Scan(&fkey.Name, &sourceTable, &fkey.Column, &fkey.ForeignTable, &fkey.ForeignColumn)
if err != nil {
return nil, err
}
fkeys = append(fkeys, fkey)
}
if err = rows.Err(); err != nil {
return nil, err
}
return fkeys, nil
}
// TranslateColumnType converts postgres database types to Go types, for example
// "varchar" to "string" and "bigint" to "int64". It returns this parsed data
// as a Column object.
func (m *MSSQLDriver) TranslateColumnType(c drivers.Column) drivers.Column {
if c.Nullable {
switch c.DBType {
case "tinyint":
c.Type = "null.Int8"
case "smallint":
c.Type = "null.Int16"
case "mediumint":
c.Type = "null.Int32"
case "int":
c.Type = "null.Int"
case "bigint":
c.Type = "null.Int64"
case "real":
c.Type = "null.Float32"
case "float":
c.Type = "null.Float64"
case "boolean", "bool", "bit":
c.Type = "null.Bool"
case "date", "datetime", "datetime2", "datetimeoffset", "smalldatetime", "time":
c.Type = "null.Time"
case "binary", "varbinary":
c.Type = "null.Bytes"
case "timestamp", "rowversion":
c.Type = "null.Bytes"
case "xml":
c.Type = "null.String"
case "uniqueidentifier":
c.Type = "mssql.UniqueIdentifier"
c.DBType = "uuid"
case "numeric", "decimal", "dec":
c.Type = "types.NullDecimal"
default:
c.Type = "null.String"
}
} else {
switch c.DBType {
case "tinyint":
c.Type = "int8"
case "smallint":
c.Type = "int16"
case "mediumint":
c.Type = "int32"
case "int":
c.Type = "int"
case "bigint":
c.Type = "int64"
case "real":
c.Type = "float32"
case "float":
c.Type = "float64"
case "boolean", "bool", "bit":
c.Type = "bool"
case "date", "datetime", "datetime2", "datetimeoffset", "smalldatetime", "time":
c.Type = "time.Time"
case "binary", "varbinary":
c.Type = "[]byte"
case "timestamp", "rowversion":
c.Type = "[]byte"
case "xml":
c.Type = "string"
case "uniqueidentifier":
c.Type = "mssql.UniqueIdentifier"
c.DBType = "uuid"
case "numeric", "decimal", "dec":
c.Type = "types.Decimal"
default:
c.Type = "string"
}
}
return c
}
// Imports returns important imports for the driver
func (MSSQLDriver) Imports() (col importers.Collection, err error) {
col.All = importers.Set{
Standard: importers.List{
`"strconv"`,
},
}
col.Singleton = importers.Map{
"mssql_upsert": {
Standard: importers.List{
`"fmt"`,
`"strings"`,
},
ThirdParty: importers.List{
`"github.com/volatiletech/strmangle"`,
`"github.com/volatiletech/sqlboiler/v4/drivers"`,
},
},
}
col.TestSingleton = importers.Map{
"mssql_suites_test": {
Standard: importers.List{
`"testing"`,
},
},
"mssql_main_test": {
Standard: importers.List{
`"bytes"`,
`"database/sql"`,
`"fmt"`,
`"os"`,
`"os/exec"`,
`"regexp"`,
`"strings"`,
},
ThirdParty: importers.List{
`"github.com/kat-co/vala"`,
`"github.com/friendsofgo/errors"`,
`"github.com/spf13/viper"`,
`"github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-mssql/driver"`,
`"github.com/volatiletech/randomize"`,
`_ "github.com/microsoft/go-mssqldb"`,
},
},
}
col.BasedOnType = importers.Map{
"null.Float32": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Float64": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int8": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int16": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int32": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Int64": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint8": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint16": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint32": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Uint64": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.String": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Bool": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Time": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Bytes": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"time.Time": {
Standard: importers.List{`"time"`},
},
"types.Decimal": {
Standard: importers.List{`"github.com/volatiletech/sqlboiler/v4/types"`},
},
"types.NullDecimal": {
Standard: importers.List{`"github.com/volatiletech/sqlboiler/v4/types"`},
},
"mssql.UniqueIdentifier": {
Standard: importers.List{`"github.com/microsoft/go-mssqldb"`},
},
}
return col, err
}