[feat] 新增 表结构操作
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
package sqlserver
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.fsdpf.net/go/db/v2"
|
||||
"git.fsdpf.net/go/db/v2/dialect/sqlserver"
|
||||
"git.fsdpf.net/go/db/v2/internal/sb"
|
||||
"git.fsdpf.net/go/db/v2/schema"
|
||||
"git.fsdpf.net/go/db/v2/sqlgen"
|
||||
)
|
||||
|
||||
type SQLServer struct {
|
||||
db *db.Database
|
||||
esg sqlgen.ExpressionSQLGenerator
|
||||
}
|
||||
|
||||
var sqlServerDefaultModifiers = []string{
|
||||
"Nullable", "Default", "Increment", "Comment",
|
||||
}
|
||||
|
||||
func (this SQLServer) GetColumnListing(table string) ([]string, error) {
|
||||
cols := []string{}
|
||||
err := this.db.From(db.S("INFORMATION_SCHEMA").Table("COLUMNS")).Where(
|
||||
db.C("TABLE_NAME").Eq(table),
|
||||
db.C("TABLE_SCHEMA").Eq(db.L("SCHEMA_NAME()")),
|
||||
).Pluck(&cols, "COLUMN_NAME")
|
||||
return cols, err
|
||||
}
|
||||
|
||||
func (this SQLServer) TableExists(table string) (bool, error) {
|
||||
result, err := this.db.From(db.S("INFORMATION_SCHEMA").Table("TABLES")).Where(db.Ex{
|
||||
"TABLE_NAME": table,
|
||||
"TABLE_TYPE": "BASE TABLE",
|
||||
"TABLE_SCHEMA": db.L("SCHEMA_NAME()"),
|
||||
}).Count()
|
||||
return result > 0, err
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileCreate(bp *schema.Blueprint) []string {
|
||||
temporary := db.L("CREATE")
|
||||
if bp.IsTemporary() {
|
||||
temporary = db.L("CREATE")
|
||||
}
|
||||
columns := strings.Join(this.getAddedColumns(bp), ",\n")
|
||||
sql := this.GenerateSQL("? TABLE ? (\n?\n)", temporary, db.T(bp.GetTable()), db.L(columns))
|
||||
return []string{sql}
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileAdd(bp *schema.Blueprint) []string {
|
||||
columns := strings.Join(schema.PrefixArray("ADD", this.getAddedColumns(bp)), ",\n")
|
||||
sql := this.GenerateSQL("ALTER TABLE ?\n?", db.T(bp.GetTable()), db.L(columns))
|
||||
return []string{sql}
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileChange(bp *schema.Blueprint) []string {
|
||||
columns := strings.Join(schema.PrefixArray("ALTER COLUMN", this.getChangedColumns(bp)), ",\n")
|
||||
sql := this.GenerateSQL("ALTER TABLE ?\n?", db.T(bp.GetTable()), db.L(columns))
|
||||
return []string{sql}
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileDropColumn(bp *schema.Blueprint) []string {
|
||||
columns := []string{}
|
||||
for _, item := range bp.GetCommands() {
|
||||
if item.Type != "dropColumn" {
|
||||
continue
|
||||
}
|
||||
for _, col := range item.Columns {
|
||||
columns = append(columns, this.GenerateSQL("DROP COLUMN ?", db.C(col)))
|
||||
}
|
||||
}
|
||||
sql := this.GenerateSQL("ALTER TABLE ?\n?", db.T(bp.GetTable()), db.L(strings.Join(columns, ",\n")))
|
||||
return []string{sql}
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileDrop(bp *schema.Blueprint) []string {
|
||||
return []string{this.GenerateSQL("DROP TABLE ?", db.T(bp.GetTable()))}
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileDropIfExists(bp *schema.Blueprint) []string {
|
||||
return []string{this.GenerateSQL("DROP TABLE IF EXISTS ?", db.T(bp.GetTable()))}
|
||||
}
|
||||
|
||||
func (this SQLServer) CompileRename(bp *schema.Blueprint) []string {
|
||||
toName := ""
|
||||
commands := bp.GetCommands()
|
||||
if len(commands) == 0 {
|
||||
panic("new table undefined")
|
||||
}
|
||||
toName = bp.GetCommands()[0].To
|
||||
if toName == "" {
|
||||
panic("new table undefined")
|
||||
}
|
||||
return []string{this.GenerateSQL("EXEC sp_rename ?, ?", db.T(bp.GetTable()), db.T(toName))}
|
||||
}
|
||||
|
||||
func (this SQLServer) addModifiers(sql string, bp *schema.Blueprint, column *schema.ColumnDefinition) string {
|
||||
for _, modifier := range sqlServerDefaultModifiers {
|
||||
sql += this.GetColumnModifier(modifier, bp, column)
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
func (this SQLServer) GetColumnType(column *schema.ColumnDefinition) string {
|
||||
switch column.Type {
|
||||
case "char":
|
||||
return this.GenerateSQL("CHAR(?)", column.Length)
|
||||
case "string":
|
||||
return this.GenerateSQL("NVARCHAR(?)", column.Length)
|
||||
case "text":
|
||||
return "NVARCHAR(MAX)"
|
||||
case "integer":
|
||||
return "INT"
|
||||
case "bigInteger":
|
||||
return "BIGINT"
|
||||
case "smallInteger":
|
||||
return "SMALLINT"
|
||||
case "decimal":
|
||||
return this.GenerateSQL("DECIMAL(?,?)", column.Total, column.Places)
|
||||
case "boolean":
|
||||
return "BIT"
|
||||
case "enum":
|
||||
return this.GenerateSQL("NVARCHAR(?)", column.Length) // SQL Server doesn't have native enum
|
||||
case "json":
|
||||
return "NVARCHAR(MAX)" // SQL Server 2016+ has JSON support
|
||||
case "binary":
|
||||
return "VARBINARY(MAX)"
|
||||
case "datetime":
|
||||
return "DATETIME2"
|
||||
case "timestamp":
|
||||
return "DATETIME2"
|
||||
case "date":
|
||||
return "DATE"
|
||||
case "time":
|
||||
return "TIME"
|
||||
case "year":
|
||||
return "SMALLINT"
|
||||
case "uuid":
|
||||
return "UNIQUEIDENTIFIER"
|
||||
}
|
||||
panic("Unsupported data type: " + column.Type)
|
||||
}
|
||||
|
||||
func (this SQLServer) GetColumnModifier(modifier string, bp *schema.Blueprint, column *schema.ColumnDefinition) string {
|
||||
switch modifier {
|
||||
case "Nullable":
|
||||
if column.IsNullable() {
|
||||
return " NULL"
|
||||
}
|
||||
return " NOT NULL"
|
||||
case "Default":
|
||||
v := column.GetDefault()
|
||||
if v == nil {
|
||||
if column.IsUseCurrent() {
|
||||
return " DEFAULT GETDATE()"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return this.GenerateSQL(" DEFAULT ?", v)
|
||||
case "Increment":
|
||||
if column.IsAutoIncrement() {
|
||||
return " IDENTITY(1,1) PRIMARY KEY"
|
||||
}
|
||||
case "Comment":
|
||||
// SQL Server handles comments via extended properties
|
||||
return ""
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (this SQLServer) getAddedColumns(bp *schema.Blueprint) (columns []string) {
|
||||
for _, column := range bp.GetAddedColumns() {
|
||||
sql := this.GenerateSQL("? ?", db.C(column.Name), db.L(this.GetColumnType(column)))
|
||||
columns = append(columns, this.addModifiers(sql, bp, column))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (this SQLServer) getChangedColumns(bp *schema.Blueprint) (columns []string) {
|
||||
for _, column := range bp.GetChangedColumns() {
|
||||
sql := this.GenerateSQL("? ?", db.C(column.Name), db.L(this.GetColumnType(column)))
|
||||
columns = append(columns, this.addModifiers(sql, bp, column))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (this SQLServer) GenerateSQL(sql string, args ...any) string {
|
||||
sb := sb.NewSQLBuilder(false)
|
||||
this.esg.Generate(sb, db.L(sql, args...))
|
||||
result, _, _ := sb.ToSQL()
|
||||
return result
|
||||
}
|
||||
|
||||
func init() {
|
||||
schema.RegisterDialect("sqlserver", func(db *db.Database) schema.Schema {
|
||||
return &SQLServer{
|
||||
db: db,
|
||||
esg: sqlgen.NewExpressionSQLGenerator("sqlserver", sqlserver.DialectOptions()),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package sqlserver_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.fsdpf.net/go/db/v2/engine"
|
||||
"git.fsdpf.net/go/db/v2/schema"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
)
|
||||
|
||||
type sqlServerTest struct {
|
||||
suite.Suite
|
||||
schema schema.Schema
|
||||
}
|
||||
|
||||
var (
|
||||
tableName = "entry"
|
||||
|
||||
dropTable = "IF OBJECT_ID('entry', 'U') IS NOT NULL DROP TABLE entry;"
|
||||
|
||||
createTable = "CREATE TABLE entry (" +
|
||||
"id INT NOT NULL IDENTITY(1,1) PRIMARY KEY," +
|
||||
"int INT NOT NULL UNIQUE," +
|
||||
"float REAL NOT NULL," +
|
||||
"string NVARCHAR(255) NOT NULL," +
|
||||
"time DATETIME2 NOT NULL," +
|
||||
"bool BIT NOT NULL," +
|
||||
"bytes VARBINARY(MAX) NOT NULL" +
|
||||
");"
|
||||
)
|
||||
|
||||
func TestSQLServerSuite(t *testing.T) {
|
||||
suite.Run(t, new(sqlServerTest))
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) SetupSuite() {
|
||||
db := engine.Open(map[string]engine.DBConfig{
|
||||
"test-sqlserver": engine.NewDBConfig("sqlserver",
|
||||
engine.WithHost(os.Getenv("SQLSERVER_HOST")),
|
||||
engine.WithPort(os.Getenv("SQLSERVER_PORT")),
|
||||
engine.WithDatabase(os.Getenv("SQLSERVER_DB")),
|
||||
engine.WithUsername(os.Getenv("SQLSERVER_USER")),
|
||||
engine.WithPassword(os.Getenv("SQLSERVER_PASSWD")),
|
||||
),
|
||||
}).Connection("test-sqlserver")
|
||||
|
||||
t.schema = schema.GetSchemaDialect(db)
|
||||
|
||||
db.Exec(dropTable)
|
||||
db.Exec(createTable)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestGetColumnListing() {
|
||||
result, err := t.schema.GetColumnListing(tableName)
|
||||
t.Require().NoError(err)
|
||||
t.Require().ElementsMatch([]string{"id", "int", "float", "string", "time", "bool", "bytes"}, result)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestTableExists() {
|
||||
result, err := t.schema.TableExists(tableName)
|
||||
t.Require().NoError(err)
|
||||
t.Require().Equal(result, true)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileCreate() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
bp.Create()
|
||||
|
||||
bp.BigIncrements("id").AutoIncrement().Comment("ID")
|
||||
bp.Boolean("enabled").Default("1").Comment("是否有效")
|
||||
bp.Char("created_user", 36).Default("00000000-0000-0000-0000-000000000000").Comment("创建者")
|
||||
bp.Char("owned_user", 36).Default("00000000-0000-0000-0000-000000000000").Comment("拥有者")
|
||||
bp.Timestamp("created_at").UseCurrent().Comment("创建时间")
|
||||
bp.Timestamp("updated_at").UseCurrent().Comment("更新时间")
|
||||
bp.DateTime("deleted_at").Nullable().Comment("删除时间")
|
||||
|
||||
sql := t.schema.CompileCreate(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"CREATE TABLE [users] (\n" +
|
||||
"[id] BIGINT NOT NULL IDENTITY(1,1) PRIMARY KEY COMMENT 'ID',\n" +
|
||||
"[enabled] BIT NOT NULL DEFAULT 1 COMMENT '是否有效',\n" +
|
||||
"[created_user] CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000' COMMENT '创建者',\n" +
|
||||
"[owned_user] CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000' COMMENT '拥有者',\n" +
|
||||
"[created_at] DATETIME2 NOT NULL DEFAULT GETDATE() COMMENT '创建时间',\n" +
|
||||
"[updated_at] DATETIME2 NOT NULL DEFAULT GETDATE() COMMENT '更新时间',\n" +
|
||||
"[deleted_at] DATETIME2 NULL COMMENT '删除时间'\n" +
|
||||
")",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileAdd() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.String("name", 50).Comment("用户名")
|
||||
bp.SmallInteger("age").Default("18").Comment("年龄")
|
||||
bp.String("sex", 1).Default("0").Comment("性别")
|
||||
|
||||
sql := t.schema.CompileAdd(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"ALTER TABLE [users]\n" +
|
||||
"ADD [name] NVARCHAR(50) NOT NULL COMMENT '用户名',\n" +
|
||||
"ADD [age] SMALLINT NOT NULL DEFAULT 18 COMMENT '年龄',\n" +
|
||||
"ADD [sex] NVARCHAR(1) NOT NULL DEFAULT '0' COMMENT '性别'",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileChange() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.String("name", 50).Change("username")
|
||||
bp.SmallInteger("age").Default("19").Comment("年龄").Change()
|
||||
|
||||
sql := t.schema.CompileChange(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"ALTER TABLE [users]\n" +
|
||||
"ALTER COLUMN [name] NVARCHAR(50) NOT NULL,\n" +
|
||||
"ALTER COLUMN [age] SMALLINT NOT NULL DEFAULT 19 COMMENT '年龄'",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileDropColumn() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.DropColumn("age", "sex")
|
||||
|
||||
sql := t.schema.CompileDropColumn(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"ALTER TABLE [users]\n" +
|
||||
"DROP COLUMN [age],\n" +
|
||||
"DROP COLUMN [sex]",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileDrop() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.Drop()
|
||||
|
||||
sql := t.schema.CompileDrop(bp)
|
||||
|
||||
t.Equal([]string{"DROP TABLE [users]"}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileDropIfExists() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.Drop()
|
||||
|
||||
sql := t.schema.CompileDropIfExists(bp)
|
||||
t.Equal([]string{"DROP TABLE IF EXISTS [users]"}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
func (t *sqlServerTest) TestCompileRename() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.Rename("user")
|
||||
|
||||
sql := t.schema.CompileRename(bp)
|
||||
|
||||
t.Equal([]string{"EXEC sp_rename [users], [user]"}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
Reference in New Issue
Block a user