2020-08-06 20:58:47 +03:00
|
|
|
// Package sqlserver implements the sq driver for SQL Server.
|
|
|
|
package sqlserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/record"
|
|
|
|
|
2023-04-07 11:00:49 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/driver/dialect"
|
|
|
|
|
2023-04-02 22:49:45 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lga"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lgm"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg"
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2023-04-02 22:49:45 +03:00
|
|
|
"golang.org/x/exp/slog"
|
|
|
|
|
2023-04-07 11:00:49 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/ast/render"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/errz"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/kind"
|
2020-08-23 22:00:13 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlmodel"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlz"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/stringz"
|
2020-08-06 20:58:47 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/driver"
|
|
|
|
"github.com/neilotoole/sq/libsq/source"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// Type is the SQL Server source driver type.
|
2023-04-22 06:36:32 +03:00
|
|
|
Type = source.DriverType("sqlserver")
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
// dbDrvr is the backing SQL Server driver impl name.
|
|
|
|
dbDrvr = "sqlserver"
|
|
|
|
)
|
|
|
|
|
2020-08-20 23:19:16 +03:00
|
|
|
var _ driver.Provider = (*Provider)(nil)
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// Provider is the SQL Server implementation of driver.Provider.
|
|
|
|
type Provider struct {
|
2023-04-30 17:18:56 +03:00
|
|
|
Log *slog.Logger
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// DriverFor implements driver.Provider.
|
2023-04-22 06:36:32 +03:00
|
|
|
func (p *Provider) DriverFor(typ source.DriverType) (driver.Driver, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
if typ != Type {
|
2023-04-08 21:09:27 +03:00
|
|
|
return nil, errz.Errorf("unsupported driver type {%s}}", typ)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-04-30 17:18:56 +03:00
|
|
|
return &driveri{log: p.Log}, nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
var _ driver.SQLDriver = (*driveri)(nil)
|
2020-08-20 23:19:16 +03:00
|
|
|
|
2020-08-13 06:40:03 +03:00
|
|
|
// driveri is the SQL Server implementation of driver.Driver.
|
|
|
|
type driveri struct {
|
2023-04-30 17:18:56 +03:00
|
|
|
log *slog.Logger
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-06-13 19:06:18 +03:00
|
|
|
// ConnParams implements driver.SQLDriver.
|
|
|
|
func (d *driveri) ConnParams() map[string][]string {
|
|
|
|
// https://github.com/microsoft/go-mssqldb#connection-parameters-and-dsn.
|
|
|
|
return map[string][]string{
|
|
|
|
"ApplicationIntent": {"ReadOnly"},
|
|
|
|
"ServerSPN": nil,
|
|
|
|
"TrustServerCertificate": {"false", "true"},
|
|
|
|
"Workstation ID": nil,
|
|
|
|
"app name": {"sq"},
|
|
|
|
"certificate": nil,
|
|
|
|
"connection timeout": {"0"},
|
|
|
|
"database": nil,
|
|
|
|
"dial timeout": {"0"},
|
|
|
|
"encrypt": {"disable", "false", "true"},
|
|
|
|
"failoverpartner": nil,
|
|
|
|
"failoverport": {"1433"},
|
|
|
|
"hostNameInCertificate": nil,
|
|
|
|
"keepAlive": {"0", "30"},
|
|
|
|
"log": {"0", "1", "2", "4", "8", "16", "32", "64", "128", "255"},
|
|
|
|
"packet size": {"512", "4096", "16383", "32767"},
|
|
|
|
"protocol": nil,
|
|
|
|
"tlsmin": {"1.0", "1.1", "1.2", "1.3"},
|
|
|
|
"user id": nil,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
// ErrWrapFunc implements driver.SQLDriver.
|
|
|
|
func (d *driveri) ErrWrapFunc() func(error) error {
|
|
|
|
return errw
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// DriverMetadata implements driver.SQLDriver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) DriverMetadata() driver.Metadata {
|
2020-08-06 20:58:47 +03:00
|
|
|
return driver.Metadata{
|
|
|
|
Type: Type,
|
2022-12-25 07:04:18 +03:00
|
|
|
Description: "Microsoft SQL Server / Azure SQL Edge",
|
2022-12-23 21:09:06 +03:00
|
|
|
Doc: "https://github.com/microsoft/go-mssqldb",
|
2020-08-06 20:58:47 +03:00
|
|
|
IsSQL: true,
|
2023-06-13 19:06:18 +03:00
|
|
|
DefaultPort: 1433,
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Dialect implements driver.SQLDriver.
|
2023-04-07 11:00:49 +03:00
|
|
|
func (d *driveri) Dialect() dialect.Dialect {
|
|
|
|
return dialect.Dialect{
|
2020-08-12 21:24:01 +03:00
|
|
|
Type: Type,
|
|
|
|
Placeholders: placeholders,
|
2023-04-07 11:00:49 +03:00
|
|
|
IdentQuote: '"',
|
|
|
|
Enquote: stringz.DoubleQuote,
|
2020-08-12 21:24:01 +03:00
|
|
|
MaxBatchValues: 1000,
|
2023-04-07 11:00:49 +03:00
|
|
|
Ops: dialect.DefaultOps(),
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
func placeholders(numCols, numRows int) string {
|
|
|
|
rows := make([]string, numRows)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
n := 1
|
2020-08-06 20:58:47 +03:00
|
|
|
var sb strings.Builder
|
2020-08-12 21:24:01 +03:00
|
|
|
for i := 0; i < numRows; i++ {
|
|
|
|
sb.Reset()
|
|
|
|
sb.WriteRune('(')
|
|
|
|
for j := 1; j <= numCols; j++ {
|
|
|
|
sb.WriteString("@p")
|
|
|
|
sb.WriteString(strconv.Itoa(n))
|
|
|
|
n++
|
|
|
|
if j < numCols {
|
|
|
|
sb.WriteString(driver.Comma)
|
|
|
|
}
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2020-08-12 21:24:01 +03:00
|
|
|
sb.WriteRune(')')
|
|
|
|
rows[i] = sb.String()
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2020-08-12 21:24:01 +03:00
|
|
|
|
|
|
|
return strings.Join(rows, driver.Comma)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-04-07 11:00:49 +03:00
|
|
|
// Renderer implements driver.SQLDriver.
|
|
|
|
func (d *driveri) Renderer() *render.Renderer {
|
|
|
|
r := render.NewDefaultRenderer()
|
|
|
|
|
2023-04-08 21:09:27 +03:00
|
|
|
// Custom functions for SQLServer-specific stuff.
|
2023-04-07 11:00:49 +03:00
|
|
|
r.Range = renderRange
|
|
|
|
r.PreRender = preRender
|
|
|
|
|
|
|
|
return r
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-04-08 21:09:27 +03:00
|
|
|
// Open implements driver.DatabaseOpener.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) Open(ctx context.Context, src *source.Source) (driver.Database, error) {
|
2023-05-03 15:36:10 +03:00
|
|
|
lg.FromContext(ctx).Debug(lgm.OpenSrc, lga.Src, src)
|
2023-04-30 17:18:56 +03:00
|
|
|
|
|
|
|
db, err := d.doOpen(ctx, src)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-04-30 17:18:56 +03:00
|
|
|
return nil, err
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
if err = driver.OpeningPing(ctx, src, db); err != nil {
|
|
|
|
return nil, err
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return &database{log: d.log, db: db, src: src, drvr: d}, nil
|
|
|
|
}
|
|
|
|
|
2023-04-30 17:18:56 +03:00
|
|
|
func (d *driveri) doOpen(ctx context.Context, src *source.Source) (*sql.DB, error) {
|
|
|
|
db, err := sql.Open(dbDrvr, src.Location)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2023-04-30 17:18:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
driver.ConfigureDB(ctx, db, src.Options)
|
|
|
|
return db, nil
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// ValidateSource implements driver.Driver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) ValidateSource(src *source.Source) (*source.Source, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
if src.Type != Type {
|
2023-04-22 06:36:32 +03:00
|
|
|
return nil, errz.Errorf("expected driver type %q but got %q", Type, src.Type)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
return src, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ping implements driver.Driver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) Ping(ctx context.Context, src *source.Source) error {
|
2023-04-30 17:18:56 +03:00
|
|
|
db, err := d.doOpen(ctx, src)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return err
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2023-04-02 22:49:45 +03:00
|
|
|
defer lg.WarnIfCloseError(d.log, lgm.CloseDB, db)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
err = db.PingContext(ctx)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "ping %s", src.Handle)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-05-19 17:24:18 +03:00
|
|
|
// DBProperties implements driver.SQLDriver.
|
|
|
|
func (d *driveri) DBProperties(ctx context.Context, db sqlz.DB) (map[string]any, error) {
|
|
|
|
return getDBProperties(ctx, db)
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// Truncate implements driver.Driver. Due to a quirk of SQL Server, the
|
|
|
|
// operation is implemented in two statements. First "DELETE FROM tbl" to
|
|
|
|
// delete all rows. Then, if reset is true, the table sequence counter
|
|
|
|
// is reset via RESEED.
|
2022-12-18 05:43:53 +03:00
|
|
|
//
|
|
|
|
//nolint:lll
|
2023-05-19 17:24:18 +03:00
|
|
|
func (d *driveri) Truncate(ctx context.Context, src *source.Source, tbl string, reset bool,
|
|
|
|
) (affected int64, err error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// https://docs.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql?view=sql-server-ver15
|
|
|
|
|
|
|
|
// When there are foreign key constraints on mssql tables,
|
|
|
|
// it's not possible to TRUNCATE the table. An alternative is
|
|
|
|
// to delete all rows and reseed the identity column.
|
|
|
|
//
|
|
|
|
// DELETE FROM "table1"; DBCC CHECKIDENT ('table1', RESEED, 1);
|
|
|
|
//
|
|
|
|
// See: https://stackoverflow.com/questions/253849/cannot-truncate-table-because-it-is-being-referenced-by-a-foreign-key-constraint
|
|
|
|
|
2023-04-30 17:18:56 +03:00
|
|
|
db, err := d.doOpen(ctx, src)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2023-04-02 22:49:45 +03:00
|
|
|
defer lg.WarnIfFuncError(d.log, lgm.CloseDB, db.Close)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2021-02-22 10:37:00 +03:00
|
|
|
affected, err = sqlz.ExecAffected(ctx, db, fmt.Sprintf("DELETE FROM %q", tbl))
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return affected, errz.Wrapf(errw(err), "truncate: failed to delete from %q", tbl)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if reset {
|
|
|
|
_, err = db.ExecContext(ctx, fmt.Sprintf("DBCC CHECKIDENT ('%s', RESEED, 1)", tbl))
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return affected, errz.Wrapf(errw(err), "truncate: deleted %d rows from %q but RESEED failed", affected, tbl)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return affected, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// TableColumnTypes implements driver.SQLDriver.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) TableColumnTypes(ctx context.Context, db sqlz.DB, tblName string,
|
2022-12-18 11:35:59 +03:00
|
|
|
colNames []string,
|
|
|
|
) ([]*sql.ColumnType, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// SQLServer has this unusual incantation for its LIMIT equivalent:
|
|
|
|
//
|
|
|
|
// SELECT username, email, address_id FROM person
|
|
|
|
// ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;
|
|
|
|
const queryTpl = "SELECT %s FROM %s ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY"
|
|
|
|
|
|
|
|
dialect := d.Dialect()
|
2023-04-07 11:00:49 +03:00
|
|
|
quote := string(dialect.IdentQuote)
|
2020-08-06 20:58:47 +03:00
|
|
|
tblNameQuoted := stringz.Surround(tblName, quote)
|
|
|
|
|
2022-12-18 11:35:59 +03:00
|
|
|
colsClause := "*"
|
2020-08-06 20:58:47 +03:00
|
|
|
if len(colNames) > 0 {
|
|
|
|
colNamesQuoted := stringz.SurroundSlice(colNames, quote)
|
|
|
|
colsClause = strings.Join(colNamesQuoted, driver.Comma)
|
|
|
|
}
|
|
|
|
|
|
|
|
query := fmt.Sprintf(queryTpl, colsClause, tblNameQuoted)
|
|
|
|
rows, err := db.QueryContext(ctx, query)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
colTypes, err := rows.ColumnTypes()
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfFuncError(d.log, lgm.CloseDBRows, rows.Close)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Err()
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfFuncError(d.log, lgm.CloseDBRows, rows.Close)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Close()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return colTypes, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RecordMeta implements driver.SQLDriver.
|
2023-05-22 18:08:14 +03:00
|
|
|
func (d *driveri) RecordMeta(colTypes []*sql.ColumnType) (record.Meta, driver.NewRecordFunc, error) {
|
|
|
|
recMeta := make([]*record.FieldMeta, len(colTypes))
|
2020-08-06 20:58:47 +03:00
|
|
|
for i, colType := range colTypes {
|
|
|
|
kind := kindFromDBTypeName(d.log, colType.Name(), colType.DatabaseTypeName())
|
2023-05-22 18:08:14 +03:00
|
|
|
colTypeData := record.NewColumnTypeData(colType, kind)
|
2020-08-06 20:58:47 +03:00
|
|
|
setScanType(colTypeData, kind)
|
2023-05-22 18:08:14 +03:00
|
|
|
recMeta[i] = record.NewFieldMeta(colTypeData)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
mungeFn := func(vals []any) (record.Record, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
// sqlserver doesn't need to do any special munging, so we
|
|
|
|
// just use the default munging.
|
|
|
|
rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil)
|
|
|
|
if len(skipped) > 0 {
|
|
|
|
return nil, errz.Errorf("expected zero skipped cols but have %d", skipped)
|
|
|
|
}
|
|
|
|
return rec, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return recMeta, mungeFn, nil
|
|
|
|
}
|
|
|
|
|
2021-01-04 05:56:22 +03:00
|
|
|
// TableExists implements driver.SQLDriver.
|
|
|
|
func (d *driveri) TableExists(ctx context.Context, db sqlz.DB, tbl string) (bool, error) {
|
2023-03-22 09:17:34 +03:00
|
|
|
const query = `SELECT COUNT(*) FROM information_schema.tables
|
|
|
|
WHERE table_schema = 'dbo' AND table_name = @p1`
|
2021-01-04 05:56:22 +03:00
|
|
|
|
|
|
|
var count int64
|
|
|
|
err := db.QueryRowContext(ctx, query, tbl).Scan(&count)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return false, errw(err)
|
2021-01-04 05:56:22 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return count == 1, nil
|
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
// CurrentSchema implements driver.SQLDriver.
|
|
|
|
func (d *driveri) CurrentSchema(ctx context.Context, db sqlz.DB) (string, error) {
|
|
|
|
var name string
|
|
|
|
if err := db.QueryRowContext(ctx, `SELECT SCHEMA_NAME()`).Scan(&name); err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return "", errw(err)
|
2023-03-22 09:17:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return name, nil
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// CreateTable implements driver.SQLDriver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) CreateTable(ctx context.Context, db sqlz.DB, tblDef *sqlmodel.TableDef) error {
|
2020-08-06 20:58:47 +03:00
|
|
|
stmt := buildCreateTableStmt(tblDef)
|
|
|
|
|
|
|
|
_, err := db.ExecContext(ctx, stmt)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2020-08-21 06:08:59 +03:00
|
|
|
// AlterTableAddColumn implements driver.SQLDriver.
|
2023-03-22 09:17:34 +03:00
|
|
|
func (d *driveri) AlterTableAddColumn(ctx context.Context, db sqlz.DB, tbl, col string, knd kind.Kind) error {
|
|
|
|
q := fmt.Sprintf("ALTER TABLE %q ADD %q ", tbl, col) + dbTypeNameFromKind(knd)
|
2020-08-21 06:08:59 +03:00
|
|
|
|
|
|
|
_, err := db.ExecContext(ctx, q)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "alter table: failed to add column %q to table %q", col, tbl)
|
2023-03-22 09:17:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// AlterTableRename implements driver.SQLDriver.
|
|
|
|
func (d *driveri) AlterTableRename(ctx context.Context, db sqlz.DB, tbl, newName string) error {
|
|
|
|
schema, err := d.CurrentSchema(ctx, db)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
q := fmt.Sprintf(`exec sp_rename '[%s].[%s]', '%s'`, schema, tbl, newName)
|
|
|
|
_, err = db.ExecContext(ctx, q)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "alter table: failed to rename table %q to %q", tbl, newName)
|
2023-03-22 09:17:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// AlterTableRenameColumn implements driver.SQLDriver.
|
|
|
|
func (d *driveri) AlterTableRenameColumn(ctx context.Context, db sqlz.DB, tbl, col, newName string) error {
|
|
|
|
schema, err := d.CurrentSchema(ctx, db)
|
2020-08-21 06:08:59 +03:00
|
|
|
if err != nil {
|
2023-03-22 09:17:34 +03:00
|
|
|
return err
|
2020-08-21 06:08:59 +03:00
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
q := fmt.Sprintf(`exec sp_rename '[%s].[%s].[%s]', '%s'`, schema, tbl, col, newName)
|
|
|
|
_, err = db.ExecContext(ctx, q)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "alter table: failed to rename column {%s.%s.%s} to {%s}", schema, tbl, col, newName)
|
2020-08-21 06:08:59 +03:00
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// CopyTable implements driver.SQLDriver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) CopyTable(ctx context.Context, db sqlz.DB, fromTable, toTable string, copyData bool) (int64, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
var stmt string
|
|
|
|
|
|
|
|
if copyData {
|
|
|
|
stmt = fmt.Sprintf("SELECT * INTO %q FROM %q", toTable, fromTable)
|
|
|
|
} else {
|
|
|
|
stmt = fmt.Sprintf("SELECT TOP(0) * INTO %q FROM %q", toTable, fromTable)
|
|
|
|
}
|
|
|
|
|
2021-02-22 10:37:00 +03:00
|
|
|
affected, err := sqlz.ExecAffected(ctx, db, stmt)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return affected, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// DropTable implements driver.SQLDriver.
|
2020-08-13 06:40:03 +03:00
|
|
|
func (d *driveri) DropTable(ctx context.Context, db sqlz.DB, tbl string, ifExists bool) error {
|
2020-08-06 20:58:47 +03:00
|
|
|
var stmt string
|
|
|
|
|
|
|
|
if ifExists {
|
|
|
|
stmt = fmt.Sprintf("IF OBJECT_ID('dbo.%s', 'U') IS NOT NULL DROP TABLE dbo.%q", tbl, tbl)
|
|
|
|
} else {
|
|
|
|
stmt = fmt.Sprintf("DROP TABLE dbo.%q", tbl)
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := db.ExecContext(ctx, stmt)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// PrepareInsertStmt implements driver.SQLDriver.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) PrepareInsertStmt(ctx context.Context, db sqlz.DB, destTbl string, destColNames []string,
|
2022-12-18 11:35:59 +03:00
|
|
|
numRows int,
|
|
|
|
) (*driver.StmtExecer, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
destColsMeta, err := d.getTableColsMeta(ctx, db, destTbl, destColNames)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:24:01 +03:00
|
|
|
stmt, err := driver.PrepareInsertStmt(ctx, d, db, destTbl, destColsMeta.Names(), numRows)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-12-18 05:43:53 +03:00
|
|
|
execer := driver.NewStmtExecer(stmt, driver.DefaultInsertMungeFunc(destTbl, destColsMeta),
|
|
|
|
newStmtExecFunc(stmt, db, destTbl), destColsMeta)
|
2020-08-06 20:58:47 +03:00
|
|
|
return execer, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrepareUpdateStmt implements driver.SQLDriver.
|
2022-12-18 05:43:53 +03:00
|
|
|
func (d *driveri) PrepareUpdateStmt(ctx context.Context, db sqlz.DB, destTbl string, destColNames []string,
|
2022-12-18 11:35:59 +03:00
|
|
|
where string,
|
|
|
|
) (*driver.StmtExecer, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
destColsMeta, err := d.getTableColsMeta(ctx, db, destTbl, destColNames)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
query, err := buildUpdateStmt(destTbl, destColNames, where)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
stmt, err := db.PrepareContext(ctx, query)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-12-18 05:43:53 +03:00
|
|
|
execer := driver.NewStmtExecer(stmt, driver.DefaultInsertMungeFunc(destTbl, destColsMeta),
|
|
|
|
newStmtExecFunc(stmt, db, destTbl), destColsMeta)
|
2020-08-06 20:58:47 +03:00
|
|
|
return execer, nil
|
|
|
|
}
|
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
func (d *driveri) getTableColsMeta(ctx context.Context, db sqlz.DB,
|
|
|
|
tblName string, colNames []string,
|
|
|
|
) (record.Meta, error) {
|
2020-08-16 00:06:40 +03:00
|
|
|
// SQLServer has this unusual incantation for its LIMIT equivalent:
|
|
|
|
//
|
|
|
|
// SELECT username, email, address_id FROM person
|
|
|
|
// ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;
|
|
|
|
const queryTpl = "SELECT %s FROM %s ORDER BY (SELECT 0) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY"
|
|
|
|
|
|
|
|
dialect := d.Dialect()
|
2023-04-07 11:00:49 +03:00
|
|
|
quote := string(dialect.IdentQuote)
|
2020-08-16 00:06:40 +03:00
|
|
|
tblNameQuoted := stringz.Surround(tblName, quote)
|
|
|
|
colNamesQuoted := stringz.SurroundSlice(colNames, quote)
|
|
|
|
colsJoined := strings.Join(colNamesQuoted, driver.Comma)
|
|
|
|
|
|
|
|
query := fmt.Sprintf(queryTpl, colsJoined, tblNameQuoted)
|
|
|
|
rows, err := db.QueryContext(ctx, query)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
colTypes, err := rows.ColumnTypes()
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfFuncError(d.log, lgm.CloseDBRows, rows.Close)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if rows.Err() != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(rows.Err())
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
destCols, _, err := d.RecordMeta(colTypes)
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfFuncError(d.log, lgm.CloseDBRows, rows.Close)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Close()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return destCols, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// database implements driver.Database.
|
|
|
|
type database struct {
|
2023-04-02 22:49:45 +03:00
|
|
|
log *slog.Logger
|
2020-08-16 00:06:40 +03:00
|
|
|
drvr *driveri
|
|
|
|
db *sql.DB
|
|
|
|
src *source.Source
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ driver.Database = (*database)(nil)
|
|
|
|
|
|
|
|
// DB implements driver.Database.
|
|
|
|
func (d *database) DB() *sql.DB {
|
|
|
|
return d.db
|
|
|
|
}
|
|
|
|
|
|
|
|
// SQLDriver implements driver.Database.
|
|
|
|
func (d *database) SQLDriver() driver.SQLDriver {
|
|
|
|
return d.drvr
|
|
|
|
}
|
|
|
|
|
|
|
|
// Source implements driver.Database.
|
|
|
|
func (d *database) Source() *source.Source {
|
|
|
|
return d.src
|
|
|
|
}
|
|
|
|
|
|
|
|
// TableMetadata implements driver.Database.
|
|
|
|
func (d *database) TableMetadata(ctx context.Context, tblName string) (*source.TableMetadata, error) {
|
|
|
|
const query = `SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_TYPE
|
|
|
|
FROM INFORMATION_SCHEMA.TABLES
|
|
|
|
WHERE TABLE_NAME = @p1`
|
|
|
|
|
|
|
|
var catalog, schema, tblType string
|
|
|
|
err := d.db.QueryRowContext(ctx, query, tblName).Scan(&catalog, &schema, &tblType)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
2023-04-26 18:16:42 +03:00
|
|
|
// TODO: getTableMetadata can cause deadlock in the DB. Needs further investigation.
|
|
|
|
// But a quick hack would be to use retry on a deadlock error.
|
2023-04-02 22:49:45 +03:00
|
|
|
return getTableMetadata(ctx, d.db, catalog, schema, tblName, tblType)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// SourceMetadata implements driver.Database.
|
2023-06-22 08:48:58 +03:00
|
|
|
func (d *database) SourceMetadata(ctx context.Context, noSchema bool) (*source.Metadata, error) {
|
|
|
|
return getSourceMetadata(ctx, d.src, d.db, noSchema)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close implements driver.Database.
|
|
|
|
func (d *database) Close() error {
|
2023-05-03 15:36:10 +03:00
|
|
|
d.log.Debug(lgm.CloseDB, lga.Handle, d.src.Handle)
|
2020-08-16 00:06:40 +03:00
|
|
|
|
2023-05-22 18:08:14 +03:00
|
|
|
return errw(d.db.Close())
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
// newStmtExecFunc returns a StmtExecFunc that has logic to deal with
|
|
|
|
// the "identity insert" error. If the error is encountered, setIdentityInsert
|
|
|
|
// is called and stmt is executed again.
|
|
|
|
func newStmtExecFunc(stmt *sql.Stmt, db sqlz.DB, tbl string) driver.StmtExecFunc {
|
2022-12-17 02:34:33 +03:00
|
|
|
return func(ctx context.Context, args ...any) (int64, error) {
|
2020-08-06 20:58:47 +03:00
|
|
|
res, err := stmt.ExecContext(ctx, args...)
|
|
|
|
if err == nil {
|
|
|
|
var affected int64
|
|
|
|
affected, err = res.RowsAffected()
|
2023-05-22 18:08:14 +03:00
|
|
|
return affected, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if !hasErrCode(err, errCodeIdentityInsert) {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
idErr := setIdentityInsert(ctx, db, tbl, true)
|
|
|
|
if idErr != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errz.Combine(errw(err), idErr)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
res, err = stmt.ExecContext(ctx, args...)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return 0, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
affected, err := res.RowsAffected()
|
2023-05-22 18:08:14 +03:00
|
|
|
return affected, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// setIdentityInsert enables (or disables) "identity insert" for tbl on db.
|
|
|
|
// SQLServer is fussy about inserting values to the identity col. This
|
|
|
|
// error can be returned from the driver:
|
|
|
|
//
|
2022-12-17 01:54:09 +03:00
|
|
|
// mssql: Cannot insert explicit value for identity column in table 'payment' when IDENTITY_INSERT is set to OFF
|
2020-08-06 20:58:47 +03:00
|
|
|
//
|
|
|
|
// The solution is "SET IDENTITY_INSERT tbl ON".
|
|
|
|
//
|
|
|
|
// See: https://docs.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql?view=sql-server-ver15
|
|
|
|
func setIdentityInsert(ctx context.Context, db sqlz.DB, tbl string, on bool) error {
|
2022-12-18 11:35:59 +03:00
|
|
|
mode := "ON"
|
2020-08-06 20:58:47 +03:00
|
|
|
if !on {
|
|
|
|
mode = "OFF"
|
|
|
|
}
|
|
|
|
|
|
|
|
query := fmt.Sprintf("SET IDENTITY_INSERT %q %s", tbl, mode)
|
|
|
|
_, err := db.ExecContext(ctx, query)
|
2023-05-22 18:08:14 +03:00
|
|
|
return errz.Wrapf(errw(err), "failed to SET IDENTITY INSERT %s %s", tbl, mode)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|