Initial MSSQL support

This commit is contained in:
Sergey Kurt 2017-03-13 12:55:26 +03:00
parent e8723a2797
commit e00ea60679
14 changed files with 639 additions and 1 deletions

362
bdb/drivers/mssql.go Normal file
View file

@ -0,0 +1,362 @@
package drivers
import (
"database/sql"
"fmt"
"net/url"
"strings"
_ "github.com/denisenkom/go-mssqldb"
"github.com/pkg/errors"
"github.com/vattle/sqlboiler/bdb"
)
// MSSQLDriver holds the database connection string and a handle
// to the database connection.
type MSSQLDriver struct {
connStr string
dbConn *sql.DB
}
// NewMSSQLDriver takes the database connection details as parameters and
// returns a pointer to a MSSQLDriver object. Note that it is required to
// call MSSQLDriver.Open() and MSSQLDriver.Close() to open and close
// the database connection once an object has been obtained.
func NewMSSQLDriver(user, pass, dbname, host string, port int, sslmode string) *MSSQLDriver {
driver := MSSQLDriver{
connStr: MSSQLBuildQueryString(user, pass, dbname, host, port, sslmode),
}
return &driver
}
// 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),
// Path: instance, // if connecting to an instance instead of a port
RawQuery: query.Encode(),
}
return u.String()
}
// Open opens the database connection using the connection string
func (m *MSSQLDriver) Open() error {
var err error
m.dbConn, err = sql.Open("mssql", m.connStr)
if err != nil {
return err
}
return nil
}
// Close closes the database connection
func (m *MSSQLDriver) Close() {
m.dbConn.Close()
}
// UseLastInsertID returns false for postgres
func (m *MSSQLDriver) UseLastInsertID() bool {
return true
}
// TableNames connects to the postgres database and
// retrieves all table names from the information_schema where the
// table schema is public.
func (m *MSSQLDriver) TableNames(schema string, whitelist, blacklist []string) ([]string, error) {
var names []string
query := fmt.Sprintf(`select table_name from information_schema.tables where table_schema = ? and table_type = 'BASE TABLE'`)
args := []interface{}{schema}
if len(whitelist) > 0 {
query += fmt.Sprintf(" and table_name in (%s);", strings.Repeat(",?", len(whitelist))[1:])
for _, w := range whitelist {
args = append(args, w)
}
} else if len(blacklist) > 0 {
query += fmt.Sprintf(" and table_name not in (%s);", strings.Repeat(",?", len(blacklist))[1:])
for _, b := range blacklist {
args = append(args, b)
}
}
rows, err := m.dbConn.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
}
// 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) ([]bdb.Column, error) {
var columns []bdb.Column
rows, err := m.dbConn.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
FROM INFORMATION_SCHEMA.columns c
where table_name = ? and table_schema = ?;
`, tableName, schema)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var colName, colType, colFullType string
var nullable, unique bool
var defaultValue *string
if err := rows.Scan(&colName, &colFullType, &colType, &defaultValue, &nullable, &unique); err != nil {
return nil, errors.Wrapf(err, "unable to scan for table %s", tableName)
}
column := bdb.Column{
Name: colName,
FullDBType: colFullType, // example: tinyint(1) instead of tinyint
DBType: colType,
Nullable: nullable,
Unique: unique,
}
if defaultValue != nil && *defaultValue != "NULL" {
column.Default = *defaultValue
}
columns = append(columns, column)
}
return columns, nil
}
// PrimaryKeyInfo looks up the primary key for a table.
func (m *MSSQLDriver) PrimaryKeyInfo(schema, tableName string) (*bdb.PrimaryKey, error) {
pkey := &bdb.PrimaryKey{}
var err error
query := `
select tc.constraint_name
from information_schema.table_constraints as tc
where tc.table_name = ? and tc.constraint_type = 'PRIMARY KEY' and tc.table_schema = ?;`
row := m.dbConn.QueryRow(query, tableName, schema)
if err = row.Scan(&pkey.Name); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
queryColumns := `
select kcu.column_name
from information_schema.key_column_usage as kcu
where table_name = ? and constraint_name = ? and table_schema = ?;`
var rows *sql.Rows
if rows, err = m.dbConn.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) ([]bdb.ForeignKey, error) {
var fkeys []bdb.ForeignKey
query := `
SELECT
ccu.constraint_name AS SourceConstraint
,ccu.table_name AS SourceTable
,ccu.column_name AS SourceColumn
,kcu.table_name AS TargetTable
,kcu.column_name AS TargetColumn
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 = ?
`
var rows *sql.Rows
var err error
if rows, err = m.dbConn.Query(query, schema, schema, tableName); err != nil {
return nil, err
}
for rows.Next() {
var fkey bdb.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 bdb.Column) bdb.Column {
if c.Nullable {
switch c.DBType {
case "tinyint":
// map tinyint(1) to bool if TinyintAsBool is true
if TinyintAsBool && c.FullDBType == "tinyint(1)" {
c.Type = "null.Bool"
} else {
c.Type = "null.Int8"
}
case "smallint":
c.Type = "null.Int16"
case "mediumint":
c.Type = "null.Int32"
case "int", "integer":
c.Type = "null.Int"
case "bigint":
c.Type = "null.Int64"
case "float":
c.Type = "null.Float32"
case "double", "double precision", "real":
c.Type = "null.Float64"
case "boolean", "bool":
c.Type = "null.Bool"
case "date", "datetime", "timestamp", "time":
c.Type = "null.Time"
case "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob":
c.Type = "null.Bytes"
case "json":
c.Type = "types.JSON"
default:
c.Type = "null.String"
}
} else {
switch c.DBType {
case "tinyint":
// map tinyint(1) to bool if TinyintAsBool is true
if TinyintAsBool && c.FullDBType == "tinyint(1)" {
c.Type = "bool"
} else {
c.Type = "int8"
}
case "smallint":
c.Type = "int16"
case "mediumint":
c.Type = "int32"
case "int", "integer":
c.Type = "int"
case "bigint":
c.Type = "int64"
case "float":
c.Type = "float32"
case "double", "double precision", "real":
c.Type = "float64"
case "boolean", "bool":
c.Type = "bool"
case "date", "datetime", "timestamp", "time":
c.Type = "time.Time"
case "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob":
c.Type = "[]byte"
case "json":
c.Type = "types.JSON"
default:
c.Type = "string"
}
}
return c
}
// RightQuote is the quoting character for the right side of the identifier
func (m *MSSQLDriver) RightQuote() byte {
return '`'
}
// LeftQuote is the quoting character for the left side of the identifier
func (m *MSSQLDriver) LeftQuote() byte {
return '`'
}
// IndexPlaceholders returns false to indicate MSSQL doesnt support indexed placeholders
func (m *MSSQLDriver) IndexPlaceholders() bool {
return false
}

View file

@ -305,6 +305,15 @@ func (s *State) initDriver(driverName string) error {
s.Config.MySQL.Port,
s.Config.MySQL.SSLMode,
)
case "mssql":
s.Driver = drivers.NewMSSQLDriver(
s.Config.MSSQL.User,
s.Config.MSSQL.Pass,
s.Config.MSSQL.DBName,
s.Config.MSSQL.Host,
s.Config.MSSQL.Port,
s.Config.MSSQL.SSLMode,
)
case "mock":
s.Driver = &drivers.MockDriver{}
}

View file

@ -19,6 +19,7 @@ type Config struct {
Postgres PostgresConfig
MySQL MySQLConfig
MSSQL MSSQLConfig
}
// PostgresConfig configures a postgres database
@ -40,3 +41,13 @@ type MySQLConfig struct {
DBName string
SSLMode string
}
// MSSQLConfig configures a mysql database
type MSSQLConfig struct {
User string
Pass string
Host string
Port int
DBName string
SSLMode string
}

View file

@ -285,6 +285,25 @@ func newImporter() importer {
`_ "github.com/go-sql-driver/mysql"`,
},
},
"mssql": {
standard: importList{
`"bytes"`,
`"database/sql"`,
`"fmt"`,
`"io"`,
`"io/ioutil"`,
`"os"`,
`"os/exec"`,
`"strings"`,
},
thirdParty: importList{
`"github.com/pkg/errors"`,
`"github.com/spf13/viper"`,
`"github.com/vattle/sqlboiler/bdb/drivers"`,
`"github.com/vattle/sqlboiler/randomize"`,
`_ "github.com/denisenkom/go-mssqldb"`,
},
},
}
// basedOnType imports are only included in the template output if the

36
main.go
View file

@ -255,6 +255,42 @@ func preRun(cmd *cobra.Command, args []string) error {
}
}
if driverName == "mssql" {
cmdConfig.MSSQL = boilingcore.MSSQLConfig{
User: viper.GetString("mssql.user"),
Pass: viper.GetString("mssql.pass"),
Host: viper.GetString("mssql.host"),
Port: viper.GetInt("mssql.port"),
DBName: viper.GetString("mssql.dbname"),
SSLMode: viper.GetString("mssql.sslmode"),
}
// BUG: https://github.com/spf13/viper/issues/71
// Despite setting defaults, nested values don't get defaults
// Set them manually
if cmdConfig.MSSQL.SSLMode == "" {
cmdConfig.MSSQL.SSLMode = "true"
viper.Set("mssql.sslmode", cmdConfig.MSSQL.SSLMode)
}
if cmdConfig.MSSQL.Port == 0 {
cmdConfig.MSSQL.Port = 3306
viper.Set("mssql.port", cmdConfig.MSSQL.Port)
}
err = vala.BeginValidation().Validate(
vala.StringNotEmpty(cmdConfig.MSSQL.User, "mssql.user"),
vala.StringNotEmpty(cmdConfig.MSSQL.Host, "mssql.host"),
vala.Not(vala.Equals(cmdConfig.MSSQL.Port, 0, "mssql.port")),
vala.StringNotEmpty(cmdConfig.MSSQL.DBName, "mssql.dbname"),
vala.StringNotEmpty(cmdConfig.MSSQL.SSLMode, "mssql.sslmode"),
).Check()
if err != nil {
return commandFailure(err.Error())
}
}
cmdState, err = boilingcore.New(cmdConfig)
return err
}

View file

@ -32,8 +32,10 @@ var (
{{$varNameSingular}}InsertCache = make(map[string]insertCache)
{{$varNameSingular}}UpdateCacheMut sync.RWMutex
{{$varNameSingular}}UpdateCache = make(map[string]updateCache)
{{if ne .DriverName "mssql"}}
{{$varNameSingular}}UpsertCacheMut sync.RWMutex
{{$varNameSingular}}UpsertCache = make(map[string]insertCache)
{{end}}
)
var (

View file

@ -4,13 +4,17 @@
var {{$varNameSingular}}BeforeInsertHooks []{{$tableNameSingular}}Hook
var {{$varNameSingular}}BeforeUpdateHooks []{{$tableNameSingular}}Hook
var {{$varNameSingular}}BeforeDeleteHooks []{{$tableNameSingular}}Hook
{{- if ne .DriverName "mssql" -}}
var {{$varNameSingular}}BeforeUpsertHooks []{{$tableNameSingular}}Hook
{{- end}}
var {{$varNameSingular}}AfterInsertHooks []{{$tableNameSingular}}Hook
var {{$varNameSingular}}AfterSelectHooks []{{$tableNameSingular}}Hook
var {{$varNameSingular}}AfterUpdateHooks []{{$tableNameSingular}}Hook
var {{$varNameSingular}}AfterDeleteHooks []{{$tableNameSingular}}Hook
{{- if ne .DriverName "mssql" -}}
var {{$varNameSingular}}AfterUpsertHooks []{{$tableNameSingular}}Hook
{{- end}}
// doBeforeInsertHooks executes all "before insert" hooks.
func (o *{{$tableNameSingular}}) doBeforeInsertHooks(exec boil.Executor) (err error) {
@ -45,6 +49,7 @@ func (o *{{$tableNameSingular}}) doBeforeDeleteHooks(exec boil.Executor) (err er
return nil
}
{{- if ne .DriverName "mssql" -}}
// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *{{$tableNameSingular}}) doBeforeUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeUpsertHooks {
@ -55,6 +60,7 @@ func (o *{{$tableNameSingular}}) doBeforeUpsertHooks(exec boil.Executor) (err er
return nil
}
{{- end}}
// doAfterInsertHooks executes all "after Insert" hooks.
func (o *{{$tableNameSingular}}) doAfterInsertHooks(exec boil.Executor) (err error) {
@ -100,6 +106,7 @@ func (o *{{$tableNameSingular}}) doAfterDeleteHooks(exec boil.Executor) (err err
return nil
}
{{- if ne .DriverName "mssql" -}}
// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *{{$tableNameSingular}}) doAfterUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterUpsertHooks {
@ -110,6 +117,7 @@ func (o *{{$tableNameSingular}}) doAfterUpsertHooks(exec boil.Executor) (err err
return nil
}
{{- end}}
// Add{{$tableNameSingular}}Hook registers your hook function for all future operations.
func Add{{$tableNameSingular}}Hook(hookPoint boil.HookPoint, {{$varNameSingular}}Hook {{$tableNameSingular}}Hook) {
@ -120,8 +128,10 @@ func Add{{$tableNameSingular}}Hook(hookPoint boil.HookPoint, {{$varNameSingular}
{{$varNameSingular}}BeforeUpdateHooks = append({{$varNameSingular}}BeforeUpdateHooks, {{$varNameSingular}}Hook)
case boil.BeforeDeleteHook:
{{$varNameSingular}}BeforeDeleteHooks = append({{$varNameSingular}}BeforeDeleteHooks, {{$varNameSingular}}Hook)
{{if ne .DriverName "mssql" -}}
case boil.BeforeUpsertHook:
{{$varNameSingular}}BeforeUpsertHooks = append({{$varNameSingular}}BeforeUpsertHooks, {{$varNameSingular}}Hook)
{{- end}}
case boil.AfterInsertHook:
{{$varNameSingular}}AfterInsertHooks = append({{$varNameSingular}}AfterInsertHooks, {{$varNameSingular}}Hook)
case boil.AfterSelectHook:
@ -130,8 +140,10 @@ func Add{{$tableNameSingular}}Hook(hookPoint boil.HookPoint, {{$varNameSingular}
{{$varNameSingular}}AfterUpdateHooks = append({{$varNameSingular}}AfterUpdateHooks, {{$varNameSingular}}Hook)
case boil.AfterDeleteHook:
{{$varNameSingular}}AfterDeleteHooks = append({{$varNameSingular}}AfterDeleteHooks, {{$varNameSingular}}Hook)
{{- if ne .DriverName "mssql" -}}
case boil.AfterUpsertHook:
{{$varNameSingular}}AfterUpsertHooks = append({{$varNameSingular}}AfterUpsertHooks, {{$varNameSingular}}Hook)
{{- end}}
}
}
{{- end}}

View file

@ -1,3 +1,4 @@
{{- if ne .DriverName "mssql" -}}
{{- $tableNameSingular := .Table.Name | singular | titleCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}}
{{- $schemaTable := .Table.Name | .SchemaTable}}
@ -207,3 +208,4 @@ CacheNoHooks:
return nil
{{- end}}
}
{{- end}}

View file

@ -38,6 +38,7 @@ func {{$varNameSingular}}AfterDeleteHook(e boil.Executor, o *{{$tableNameSingula
return nil
}
{{if ne .DriverName "mssql" -}}
func {{$varNameSingular}}BeforeUpsertHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{}
return nil
@ -47,6 +48,7 @@ func {{$varNameSingular}}AfterUpsertHook(e boil.Executor, o *{{$tableNameSingula
*o = {{$tableNameSingular}}{}
return nil
}
{{- end}}
func test{{$tableNamePlural}}Hooks(t *testing.T) {
t.Parallel()
@ -124,6 +126,7 @@ func test{{$tableNamePlural}}Hooks(t *testing.T) {
}
{{$varNameSingular}}AfterDeleteHooks = []{{$tableNameSingular}}Hook{}
{{- if ne .DriverName "mssql" -}}
Add{{$tableNameSingular}}Hook(boil.BeforeUpsertHook, {{$varNameSingular}}BeforeUpsertHook)
if err = o.doBeforeUpsertHooks(nil); err != nil {
t.Errorf("Unable to execute doBeforeUpsertHooks: %s", err)
@ -141,5 +144,6 @@ func test{{$tableNamePlural}}Hooks(t *testing.T) {
t.Errorf("Expected AfterUpsertHook function to empty object, but got: %#v", o)
}
{{$varNameSingular}}AfterUpsertHooks = []{{$tableNameSingular}}Hook{}
{{- end}}
}
{{- end}}

View file

@ -0,0 +1,161 @@
type mssqlTester struct {
dbConn *sql.DB
dbName string
host string
user string
pass string
sslmode string
port int
optionFile string
testDBName string
}
func init() {
dbMain = &mssqlTester{}
}
func (m *mssqlTester) setup() error {
var err error
m.dbName = viper.GetString("mssql.dbname")
m.host = viper.GetString("mssql.host")
m.user = viper.GetString("mssql.user")
m.pass = viper.GetString("mssql.pass")
m.port = viper.GetInt("mssql.port")
m.sslmode = viper.GetString("mssql.sslmode")
// Create a randomized db name.
m.testDBName = randomize.StableDBName(m.dbName)
if err = m.makeOptionFile(); err != nil {
return errors.Wrap(err, "couldn't make option file")
}
if err = m.dropTestDB(); err != nil {
return err
}
if err = m.createTestDB(); err != nil {
return err
}
dumpCmd := exec.Command("mssqldump", m.defaultsFile(), "--no-data", m.dbName)
createCmd := exec.Command("mssql", m.defaultsFile(), "--database", m.testDBName)
r, w := io.Pipe()
dumpCmd.Stdout = w
createCmd.Stdin = newFKeyDestroyer(rgxMSSQLkey, r)
if err = dumpCmd.Start(); err != nil {
return errors.Wrap(err, "failed to start mssqldump command")
}
if err = createCmd.Start(); err != nil {
return errors.Wrap(err, "failed to start mssql command")
}
if err = dumpCmd.Wait(); err != nil {
fmt.Println(err)
return errors.Wrap(err, "failed to wait for mssqldump command")
}
w.Close() // After dumpCmd is done, close the write end of the pipe
if err = createCmd.Wait(); err != nil {
fmt.Println(err)
return errors.Wrap(err, "failed to wait for mssql command")
}
return nil
}
func (m *mssqlTester) sslMode(mode string) string {
switch mode {
case "true":
return "true"
case "false":
return "false"
default:
return "disable"
}
}
func (m *mssqlTester) defaultsFile() string {
return fmt.Sprintf("--defaults-file=%s", m.optionFile)
}
func (m *mssqlTester) makeOptionFile() error {
tmp, err := ioutil.TempFile("", "optionfile")
if err != nil {
return errors.Wrap(err, "failed to create option file")
}
fmt.Fprintln(tmp, "[client]")
fmt.Fprintf(tmp, "host=%s\n", m.host)
fmt.Fprintf(tmp, "port=%d\n", m.port)
fmt.Fprintf(tmp, "user=%s\n", m.user)
fmt.Fprintf(tmp, "password=%s\n", m.pass)
fmt.Fprintf(tmp, "ssl-mode=%s\n", m.sslMode(m.sslmode))
fmt.Fprintln(tmp, "[mssqldump]")
fmt.Fprintf(tmp, "host=%s\n", m.host)
fmt.Fprintf(tmp, "port=%d\n", m.port)
fmt.Fprintf(tmp, "user=%s\n", m.user)
fmt.Fprintf(tmp, "password=%s\n", m.pass)
fmt.Fprintf(tmp, "ssl-mode=%s\n", m.sslMode(m.sslmode))
m.optionFile = tmp.Name()
return tmp.Close()
}
func (m *mssqlTester) createTestDB() error {
sql := fmt.Sprintf("create database %s;", m.testDBName)
return m.runCmd(sql, "mssql")
}
func (m *mssqlTester) dropTestDB() error {
sql := fmt.Sprintf("drop database if exists %s;", m.testDBName)
return m.runCmd(sql, "mssql")
}
func (m *mssqlTester) teardown() error {
if m.dbConn != nil {
m.dbConn.Close()
}
if err := m.dropTestDB(); err != nil {
return err
}
return os.Remove(m.optionFile)
}
func (m *mssqlTester) runCmd(stdin, command string, args ...string) error {
args = append([]string{m.defaultsFile()}, args...)
cmd := exec.Command(command, args...)
cmd.Stdin = strings.NewReader(stdin)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
fmt.Println("failed running:", command, args)
fmt.Println(stdout.String())
fmt.Println(stderr.String())
return err
}
return nil
}
func (m *mssqlTester) conn() (*sql.DB, error) {
if m.dbConn != nil {
return m.dbConn, nil
}
var err error
m.dbConn, err = sql.Open("mssql", drivers.MSSQLBuildQueryString(m.user, m.pass, m.testDBName, m.host, m.port, m.sslmode))
if err != nil {
return nil, err
}
return m.dbConn, nil
}

View file

@ -104,6 +104,12 @@ func setConfigDefaults() {
if viper.GetInt("mysql.port") == 0 {
viper.Set("mysql.port", 3306)
}
if viper.GetString("mssql.sslmode") == "" {
viper.Set("mssql.sslmode", "true")
}
if viper.GetInt("mssql.port") == 0 {
viper.Set("mssql.port", 1433)
}
}
func validateConfig(driverName string) error {
@ -127,5 +133,15 @@ func validateConfig(driverName string) error {
).Check()
}
if driverName == "mssql" {
return vala.BeginValidation().Validate(
vala.StringNotEmpty(viper.GetString("mssql.user"), "mssql.user"),
vala.StringNotEmpty(viper.GetString("mssql.host"), "mssql.host"),
vala.Not(vala.Equals(viper.GetInt("mssql.port"), 0, "mssql.port")),
vala.StringNotEmpty(viper.GetString("mssql.dbname"), "mssql.dbname"),
vala.StringNotEmpty(viper.GetString("mssql.sslmode"), "mssql.sslmode"),
).Check()
}
return errors.New("not a valid driver name")
}

View file

@ -9,6 +9,7 @@ func MustTx(transactor boil.Transactor, err error) boil.Transactor {
var rgxPGFkey = regexp.MustCompile(`(?m)^ALTER TABLE ONLY .*\n\s+ADD CONSTRAINT .*? FOREIGN KEY .*?;\n`)
var rgxMySQLkey = regexp.MustCompile(`(?m)((,\n)?\s+CONSTRAINT.*?FOREIGN KEY.*?\n)+`)
var rgxMSSQLkey = regexp.MustCompile(`(?m)^ALTER TABLE .*\n\s+ADD CONSTRAINT .*? FOREIGN KEY .*?;\n`)
func newFKeyDestroyer(regex *regexp.Regexp, reader io.Reader) io.Reader {
return &fKeyDestroyer{

View file

@ -327,7 +327,7 @@ func TestSliceUpdateAll(t *testing.T) {
{{end -}}
{{- end -}}
}
{{- if ne .DriverName "mssql" -}}
func TestUpsert(t *testing.T) {
{{- range $index, $table := .Tables}}
{{- if $table.IsJoinTable -}}
@ -337,3 +337,4 @@ func TestUpsert(t *testing.T) {
{{end -}}
{{- end -}}
}
{{- end -}}

View file

@ -1,3 +1,4 @@
{{- if ne .DriverName "mssql" -}}
{{- $tableNameSingular := .Table.Name | singular | titleCase -}}
{{- $tableNamePlural := .Table.Name | plural | titleCase -}}
{{- $varNamePlural := .Table.Name | plural | camelCase -}}
@ -48,3 +49,4 @@ func test{{$tableNamePlural}}Upsert(t *testing.T) {
t.Error("want one record, got:", count)
}
}
{{- end}}