SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat: add more support to sqlschema (#10602)
Pandeye5eb62e45bcc
diff --git a/ee/sqlschema/postgressqlschema/provider.go b/ee/sqlschema/postgressqlschema/provider.goindex e314998e67..83bab7ca55 100644--- a/ee/sqlschema/postgressqlschema/provider.go+++ b/ee/sqlschema/postgressqlschema/provider.go@@ -4,6 +4,7 @@ import ("context""database/sql"+ "github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory""github.com/SigNoz/signoz/pkg/sqlschema""github.com/SigNoz/signoz/pkg/sqlstore"@@ -32,9 +33,9 @@ func New(ctx context.Context, providerSettings factory.ProviderSettings, configfmter: fmter,settings: settings,operator: sqlschema.NewOperator(fmter, sqlschema.OperatorSupport{- DropConstraint: true,- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: true,+ SCreateAndDropConstraint: true,+ SAlterTableAddAndDropColumnIfNotExistsAndExists: true,+ SAlterTableAlterColumnSetAndDrop: true,}),}, nil}@@ -72,8 +73,9 @@ WHEREif err != nil {return nil, nil, err}+if len(columns) == 0 {- return nil, nil, sql.ErrNoRows+ return nil, nil, provider.sqlstore.WrapNotFoundErrf(sql.ErrNoRows, errors.CodeNotFound, "table (%s) not found", tableName)}sqlschemaColumns := make([]*sqlschema.Column, 0)@@ -220,7 +222,8 @@ SELECTci.relname AS index_name,i.indisunique AS unique,i.indisprimary AS primary,- a.attname AS column_name+ a.attname AS column_name,+ array_position(i.indkey, a.attnum) AS column_positionFROMpg_index iLEFT JOIN pg_class ct ON ct.oid = i.indrelid@@ -231,9 +234,10 @@ WHEREa.attnum = ANY(i.indkey)AND con.oid IS NULLAND ct.relkind = 'r'- AND ct.relname = ?`, string(name))+ AND ct.relname = ?+ORDER BY index_name, column_position`, string(name))if err != nil {- return nil, err+ return nil, provider.sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "no indices for table (%s) found", name)}defer func() {@@ -250,9 +254,11 @@ WHEREunique boolprimary boolcolumnName string+ // starts from 0 and is unused in this function, this is to ensure that the column names are in the correct order+ columnPosition int)- if err := rows.Scan(&tableName, &indexName, &unique, &primary, &columnName); err != nil {+ if err := rows.Scan(&tableName, &indexName, &unique, &primary, &columnName, &columnPosition); err != nil {return nil, err}@@ -269,8 +275,12 @@ WHERE}indices := make([]sqlschema.Index, 0)- for _, index := range uniqueIndicesMap {- indices = append(indices, index)+ for indexName, index := range uniqueIndicesMap {+ if index.Name() == indexName {+ indices = append(indices, index)+ } else {+ indices = append(indices, index.Named(indexName))+ }}return indices, nildiff --git a/pkg/sqlschema/column.go b/pkg/sqlschema/column.goindex abcda6b198..2730bdf71a 100644--- a/pkg/sqlschema/column.go+++ b/pkg/sqlschema/column.go@@ -41,6 +41,13 @@ type Column struct {Default string}+func (column *Column) Equals(other *Column) bool {+ return column.Name == other.Name &&+ column.DataType == other.DataType &&+ column.Nullable == other.Nullable &&+ column.Default == other.Default+}+func (column *Column) ToDefinitionSQL(fmter SQLFormatter) []byte {sql := []byte{}@@ -129,3 +136,53 @@ func (column *Column) ToSetNotNullSQL(fmter SQLFormatter, tableName TableName) [return sql}++func (column *Column) ToDropNotNullSQL(fmter SQLFormatter, tableName TableName) []byte {+ sql := []byte{}++ sql = append(sql, "ALTER TABLE "...)+ sql = fmter.AppendIdent(sql, string(tableName))+ sql = append(sql, " ALTER COLUMN "...)+ sql = fmter.AppendIdent(sql, string(column.Name))+ sql = append(sql, " DROP NOT NULL"...)++ return sql+}++func (column *Column) ToSetDefaultSQL(fmter SQLFormatter, tableName TableName) []byte {+ sql := []byte{}++ sql = append(sql, "ALTER TABLE "...)+ sql = fmter.AppendIdent(sql, string(tableName))+ sql = append(sql, " ALTER COLUMN "...)+ sql = fmter.AppendIdent(sql, string(column.Name))+ sql = append(sql, " SET DEFAULT "...)+ sql = append(sql, column.Default...)++ return sql+}++func (column *Column) ToDropDefaultSQL(fmter SQLFormatter, tableName TableName) []byte {+ sql := []byte{}++ sql = append(sql, "ALTER TABLE "...)+ sql = fmter.AppendIdent(sql, string(tableName))+ sql = append(sql, " ALTER COLUMN "...)+ sql = fmter.AppendIdent(sql, string(column.Name))+ sql = append(sql, " DROP DEFAULT"...)++ return sql+}++func (column *Column) ToSetDataTypeSQL(fmter SQLFormatter, tableName TableName) []byte {+ sql := []byte{}++ sql = append(sql, "ALTER TABLE "...)+ sql = fmter.AppendIdent(sql, string(tableName))+ sql = append(sql, " ALTER COLUMN "...)+ sql = fmter.AppendIdent(sql, string(column.Name))+ sql = append(sql, " SET DATA TYPE "...)+ sql = append(sql, fmter.SQLDataTypeOf(column.DataType)...)++ return sql+}diff --git a/pkg/sqlschema/constraint.go b/pkg/sqlschema/constraint.goindex 3b0b52c290..56b26aa144 100644--- a/pkg/sqlschema/constraint.go+++ b/pkg/sqlschema/constraint.go@@ -49,6 +49,9 @@ type Constraint interface {// The SQL representation of the constraint.ToDropSQL(fmter SQLFormatter, tableName TableName) []byte++ // The SQL representation of the constraint.+ ToCreateSQL(fmter SQLFormatter, tableName TableName) []byte}type PrimaryKeyConstraint struct {@@ -139,6 +142,27 @@ func (constraint *PrimaryKeyConstraint) ToDropSQL(fmter SQLFormatter, tableNamereturn sql}+func (constraint *PrimaryKeyConstraint) ToCreateSQL(fmter SQLFormatter, tableName TableName) []byte {+ sql := []byte{}++ sql = append(sql, "ALTER TABLE "...)+ sql = fmter.AppendIdent(sql, string(tableName))+ sql = append(sql, " ADD CONSTRAINT "...)+ sql = fmter.AppendIdent(sql, constraint.Name(tableName))+ sql = append(sql, " PRIMARY KEY ("...)++ for i, column := range constraint.ColumnNames {+ if i > 0 {+ sql = append(sql, ", "...)+ }+ sql = fmter.AppendIdent(sql, string(column))+ }++ sql = append(sql, ")"...)++ return sql+}+type ForeignKeyConstraint struct {ReferencingColumnName ColumnNameReferencedTableName TableName@@ -220,6 +244,24 @@ func (constraint *ForeignKeyConstraint) ToDropSQL(fmter SQLFormatter, tableNamereturn sql}+func (constraint *ForeignKeyConstraint) ToCreateSQL(fmter SQLFormatter, tableName TableName) []byte {+ sql := []byte{}++ sql = append(sql, "ALTER TABLE "...)+ sql = fmter.AppendIdent(sql, string(tableName))+ sql = append(sql, " ADD CONSTRAINT "...)+ sql = fmter.AppendIdent(sql, constraint.Name(tableName))+ sql = append(sql, " FOREIGN KEY ("...)+ sql = fmter.AppendIdent(sql, string(constraint.ReferencingColumnName))+ sql = append(sql, ") REFERENCES "...)+ sql = fmter.AppendIdent(sql, string(constraint.ReferencedTableName))+ sql = append(sql, " ("...)+ sql = fmter.AppendIdent(sql, string(constraint.ReferencedColumnName))+ sql = append(sql, ")"...)++ return sql+}+// Do not use this constraint type. Instead create an index with the `UniqueIndex` type.// The main difference between a Unique Index and a Unique Constraint is mostly semantic, with a constraint focusing more on data integrity, while an index focuses on performance.// We choose to create unique indices because of sqlite. Dropping a unique index is directly supported whilst dropping a unique constraint requires a recreation of the table with the constraint removed.@@ -323,3 +365,7 @@ func (constraint *UniqueConstraint) ToDropSQL(fmter SQLFormatter, tableName Tablreturn sql}++func (constraint *UniqueConstraint) ToCreateSQL(fmter SQLFormatter, tableName TableName) []byte {+ return []byte{}+}diff --git a/pkg/sqlschema/index.go b/pkg/sqlschema/index.goindex 1988b1fd5e..2c846c1724 100644--- a/pkg/sqlschema/index.go+++ b/pkg/sqlschema/index.go@@ -1,6 +1,7 @@package sqlschemaimport (+ "slices""strings""github.com/SigNoz/signoz/pkg/valuer"@@ -27,12 +28,18 @@ type Index interface {// Add name to the index. This is typically used to override the autogenerated name because the database might have a different name.Named(name string) Index+ // Returns true if the index is named. A named index is not autogenerated+ IsNamed() bool+// The type of the index.Type() IndexType// The columns that the index is applied to.Columns() []ColumnName+ // Equals returns true if the index is equal to the other index.+ Equals(other Index) bool+// The SQL representation of the index.ToCreateSQL(fmter SQLFormatter) []byte@@ -76,6 +83,10 @@ func (index *UniqueIndex) Named(name string) Index {}}+func (index *UniqueIndex) IsNamed() bool {+ return index.name != ""+}+func (*UniqueIndex) Type() IndexType {return IndexTypeUnique}@@ -84,6 +95,14 @@ func (index *UniqueIndex) Columns() []ColumnName {return index.ColumnNames}+func (index *UniqueIndex) Equals(other Index) bool {+ if other.Type() != IndexTypeUnique {+ return false+ }++ return index.Name() == other.Name() && slices.Equal(index.Columns(), other.Columns())+}+func (index *UniqueIndex) ToCreateSQL(fmter SQLFormatter) []byte {sql := []byte{}diff --git a/pkg/sqlschema/operator.go b/pkg/sqlschema/operator.goindex 8cdc994a81..3915080013 100644--- a/pkg/sqlschema/operator.go+++ b/pkg/sqlschema/operator.go@@ -1,11 +1,21 @@package sqlschema+import (+ "reflect"+ "slices"+)+var _ SQLOperator = (*Operator)(nil)type OperatorSupport struct {- DropConstraint bool- ColumnIfNotExistsExists bool- AlterColumnSetNotNull bool+ // Support for creating and dropping constraints.+ SCreateAndDropConstraint bool++ // Support for `IF EXISTS` and `IF NOT EXISTS` in `ALTER TABLE ADD COLUMN` and `ALTER TABLE DROP COLUMN`.+ SAlterTableAddAndDropColumnIfNotExistsAndExists bool++ // Support for altering columns such as `ALTER TABLE ALTER COLUMN SET NOT NULL`.+ SAlterTableAlterColumnSetAndDrop bool}type Operator struct {@@ -25,9 +35,115 @@ func (operator *Operator) CreateTable(table *Table) [][]byte {}func (operator *Operator) RenameTable(table *Table, newName TableName) [][]byte {- sqls := [][]byte{table.ToRenameSQL(operator.fmter, newName)}+ sql := table.ToRenameSQL(operator.fmter, newName)table.Name = newName- return sqls++ return [][]byte{sql}+}++func (operator *Operator) AlterTable(oldTable *Table, oldTableUniqueConstraints []*UniqueConstraint, newTable *Table) [][]byte {+ // The following has to be done in order:+ // - Drop constraints+ // - Drop columns (some columns might be part of constraints therefore this depends on Step 1)+ // - Add columns, then modify columns+ // - Rename table+ // - Add constraints (some constraints might be part of columns therefore this depends on Step 3, constraint names also depend on table name which is changed in Step 4)+ // - Create unique indices from unique constraints for the new table++ sql := [][]byte{}++ // Drop primary key constraint if it is in the old table but not in the new table.+ if oldTable.PrimaryKeyConstraint != nil && newTable.PrimaryKeyConstraint == nil {+ sql = append(sql, operator.DropConstraint(oldTable, oldTableUniqueConstraints, oldTable.PrimaryKeyConstraint)...)+ }++ // Drop primary key constraint if it is in the old table and the new table but they are different.+ if oldTable.PrimaryKeyConstraint != nil && newTable.PrimaryKeyConstraint != nil && !oldTable.PrimaryKeyConstraint.Equals(newTable.PrimaryKeyConstraint) {+ sql = append(sql, operator.DropConstraint(oldTable, oldTableUniqueConstraints, oldTable.PrimaryKeyConstraint)...)+ }++ // Drop foreign key constraints that are in the old table but not in the new table.+ for _, fkConstraint := range oldTable.ForeignKeyConstraints {+ if index := operator.findForeignKeyConstraint(newTable, fkConstraint); index == -1 {+ sql = append(sql, operator.DropConstraint(oldTable, oldTableUniqueConstraints, fkConstraint)...)+ }+ }++ // Drop all unique constraints.+ for _, uniqueConstraint := range oldTableUniqueConstraints {+ sql = append(sql, operator.DropConstraint(oldTable, oldTableUniqueConstraints, uniqueConstraint)...)+ }++ // Reduce number of drops for engines with no SCreateAndDropConstraint.+ if !operator.support.SCreateAndDropConstraint && len(sql) > 0 {+ // Do not send the unique constraints to recreate table. We will change them to indexes at the end.+ sql = operator.RecreateTable(oldTable, nil)+ }++ // Drop columns that are in the old table but not in the new table.+ for _, column := range oldTable.Columns {+ if index := operator.findColumnByName(newTable, column.Name); index == -1 {+ sql = append(sql, operator.DropColumn(oldTable, column)...)+ }+ }++ // Add columns that are in the new table but not in the old table.+ for _, column := range newTable.Columns {+ if index := operator.findColumnByName(oldTable, column.Name); index == -1 {+ sql = append(sql, operator.AddColumn(oldTable, oldTableUniqueConstraints, column, nil)...)+ }+ }++ // Modify columns that are in the new table and in the old table+ alterColumnSQLs := [][]byte{}+ for _, column := range newTable.Columns {+ alterColumnSQLs = append(alterColumnSQLs, operator.AlterColumn(oldTable, oldTableUniqueConstraints, column)...)+ }++ // Reduce number of drops for engines with no SAlterTableAlterColumnSetAndDrop.+ if !operator.support.SAlterTableAlterColumnSetAndDrop && len(alterColumnSQLs) > 0 {+ // Do not send the unique constraints to recreate table. We will change them to indexes at the end.+ sql = append(sql, operator.RecreateTable(oldTable, nil)...)+ }++ if operator.support.SAlterTableAlterColumnSetAndDrop && len(alterColumnSQLs) > 0 {+ sql = append(sql, alterColumnSQLs...)+ }++ // Check if the name has changed+ if oldTable.Name != newTable.Name {+ sql = append(sql, operator.RenameTable(oldTable, newTable.Name)...)+ }++ // If the old table does not have a primary key constraint and the new table does, we need to create it.+ if oldTable.PrimaryKeyConstraint == nil {+ if newTable.PrimaryKeyConstraint != nil {+ sql = append(sql, operator.CreateConstraint(oldTable, oldTableUniqueConstraints, newTable.PrimaryKeyConstraint)...)+ }+ }++ if oldTable.PrimaryKeyConstraint != nil {+ if !oldTable.PrimaryKeyConstraint.Equals(newTable.PrimaryKeyConstraint) {+ sql = append(sql, operator.CreateConstraint(oldTable, oldTableUniqueConstraints, newTable.PrimaryKeyConstraint)...)+ }+ }++ // Create foreign key constraints that are in the new table but not in the old table.+ for _, fkConstraint := range newTable.ForeignKeyConstraints {+ if index := operator.findForeignKeyConstraint(oldTable, fkConstraint); index == -1 {+ sql = append(sql, operator.CreateConstraint(oldTable, oldTableUniqueConstraints, fkConstraint)...)+ }+ }++ // Create indices for the new table.+ for _, uniqueConstraint := range oldTableUniqueConstraints {+ sql = append(sql, uniqueConstraint.ToIndex(oldTable.Name).ToCreateSQL(operator.fmter))+ }++ // Remove duplicate SQLs.+ return slices.CompactFunc(sql, func(a, b []byte) bool {+ return string(a) == string(b)+ })}func (operator *Operator) RecreateTable(table *Table, uniqueConstraints []*UniqueConstraint) [][]byte {@@ -64,16 +180,23 @@ func (operator *Operator) AddColumn(table *Table, uniqueConstraints []*UniqueContable.Columns = append(table.Columns, column)sqls := [][]byte{- column.ToAddSQL(operator.fmter, table.Name, operator.support.ColumnIfNotExistsExists),+ column.ToAddSQL(operator.fmter, table.Name, operator.support.SAlterTableAddAndDropColumnIfNotExistsAndExists),}- if !column.Nullable {- if val == nil {- val = column.DataType.z- }+ // If the value is not nil, always try to update the column.+ if val != nil {sqls = append(sqls, column.ToUpdateSQL(operator.fmter, table.Name, val))+ }- if operator.support.AlterColumnSetNotNull {+ // If the column is not nullable and does not have a default value and no value is provided, we need to set something.+ // So we set it to the zero value of the column's data type.+ if !column.Nullable && column.Default == "" && val == nil {+ sqls = append(sqls, column.ToUpdateSQL(operator.fmter, table.Name, column.DataType.z))+ }++ // If the column is not nullable, we need to set it to not null.+ if !column.Nullable {+ if operator.support.SAlterTableAlterColumnSetAndDrop {sqls = append(sqls, column.ToSetNotNullSQL(operator.fmter, table.Name))} else {sqls = append(sqls, operator.RecreateTable(table, uniqueConstraints)...)@@ -83,6 +206,62 @@ func (operator *Operator) AddColumn(table *Table, uniqueConstraints []*UniqueConreturn sqls}+func (operator *Operator) AlterColumn(table *Table, uniqueConstraints []*UniqueConstraint, column *Column) [][]byte {+ index := operator.findColumnByName(table, column.Name)+ // If the column does not exist, we do not need to alter it.+ if index == -1 {+ return [][]byte{}+ }++ oldColumn := table.Columns[index]+ // If the column is the same, we do not need to alter it.+ if oldColumn.Equals(column) {+ return [][]byte{}+ }++ sqls := [][]byte{}+ var recreateTable bool++ if oldColumn.DataType != column.DataType {+ if operator.support.SAlterTableAlterColumnSetAndDrop {+ sqls = append(sqls, column.ToSetDataTypeSQL(operator.fmter, table.Name))+ } else {+ recreateTable = true+ }+ }++ if oldColumn.Nullable != column.Nullable {+ if operator.support.SAlterTableAlterColumnSetAndDrop {+ if column.Nullable {+ sqls = append(sqls, column.ToDropNotNullSQL(operator.fmter, table.Name))+ } else {+ sqls = append(sqls, column.ToSetNotNullSQL(operator.fmter, table.Name))+ }+ } else {+ recreateTable = true+ }+ }++ if oldColumn.Default != column.Default {+ if operator.support.SAlterTableAlterColumnSetAndDrop {+ if column.Default != "" {+ sqls = append(sqls, column.ToSetDefaultSQL(operator.fmter, table.Name))+ } else {+ sqls = append(sqls, column.ToDropDefaultSQL(operator.fmter, table.Name))+ }+ } else {+ recreateTable = true+ }+ }++ table.Columns[index] = column+ if recreateTable {+ sqls = append(sqls, operator.RecreateTable(table, uniqueConstraints)...)+ }++ return sqls+}+func (operator *Operator) DropColumn(table *Table, column *Column) [][]byte {index := operator.findColumnByName(table, column.Name)// If the column does not exist, we do not need to drop it.@@ -92,7 +271,48 @@ func (operator *Operator) DropColumn(table *Table, column *Column) [][]byte {table.Columns = append(table.Columns[:index], table.Columns[index+1:]...)- return [][]byte{column.ToDropSQL(operator.fmter, table.Name, operator.support.ColumnIfNotExistsExists)}+ return [][]byte{column.ToDropSQL(operator.fmter, table.Name, operator.support.SAlterTableAddAndDropColumnIfNotExistsAndExists)}+}++func (operator *Operator) CreateConstraint(table *Table, uniqueConstraints []*UniqueConstraint, constraint Constraint) [][]byte {+ if constraint == nil {+ return [][]byte{}+ }++ if reflect.ValueOf(constraint).IsNil() {+ return [][]byte{}+ }++ if constraint.Type() == ConstraintTypeForeignKey {+ // Constraint already exists as foreign key constraint.+ if table.ForeignKeyConstraints != nil {+ for _, fkConstraint := range table.ForeignKeyConstraints {+ if constraint.Equals(fkConstraint) {+ return [][]byte{}+ }+ }+ }++ table.ForeignKeyConstraints = append(table.ForeignKeyConstraints, constraint.(*ForeignKeyConstraint))+ }++ sqls := [][]byte{}+ if constraint.Type() == ConstraintTypePrimaryKey {+ if operator.support.SCreateAndDropConstraint {+ if table.PrimaryKeyConstraint != nil {+ // TODO(grandwizard28): this is a hack to drop the primary key constraint.+ // We need to find a better way to do this.+ sqls = append(sqls, table.PrimaryKeyConstraint.ToDropSQL(operator.fmter, table.Name))+ }+ }+ table.PrimaryKeyConstraint = constraint.(*PrimaryKeyConstraint)+ }++ if operator.support.SCreateAndDropConstraint {+ return append(sqls, constraint.ToCreateSQL(operator.fmter, table.Name))+ }++ return operator.RecreateTable(table, uniqueConstraints)}func (operator *Operator) DropConstraint(table *Table, uniqueConstraints []*UniqueConstraint, constraint Constraint) [][]byte {@@ -105,20 +325,48 @@ func (operator *Operator) DropConstraint(table *Table, uniqueConstraints []*Uniqreturn [][]byte{}}- if operator.support.DropConstraint {+ if operator.support.SCreateAndDropConstraint {return [][]byte{uniqueConstraints[uniqueConstraintIndex].ToDropSQL(operator.fmter, table.Name)}}- return operator.RecreateTable(table, append(uniqueConstraints[:uniqueConstraintIndex], uniqueConstraints[uniqueConstraintIndex+1:]...))+ var copyOfUniqueConstraints []*UniqueConstraint+ copyOfUniqueConstraints = append(copyOfUniqueConstraints, uniqueConstraints[:uniqueConstraintIndex]...)+ copyOfUniqueConstraints = append(copyOfUniqueConstraints, uniqueConstraints[uniqueConstraintIndex+1:]...)++ return operator.RecreateTable(table, copyOfUniqueConstraints)}- if operator.support.DropConstraint {+ if operator.support.SCreateAndDropConstraint {return [][]byte{toDropConstraint.ToDropSQL(operator.fmter, table.Name)}}return operator.RecreateTable(table, uniqueConstraints)}+func (operator *Operator) DiffIndices(oldIndices []Index, newIndices []Index) [][]byte {+ sqls := [][]byte{}++ for i, oldIndex := range oldIndices {+ if index := operator.findIndex(newIndices, oldIndex); index == -1 {+ sqls = append(sqls, oldIndex.ToDropSQL(operator.fmter))+ continue+ }++ if oldIndex.IsNamed() {+ sqls = append(sqls, oldIndex.ToDropSQL(operator.fmter))+ sqls = append(sqls, newIndices[i].ToCreateSQL(operator.fmter))+ }+ }++ for _, newIndex := range newIndices {+ if index := operator.findIndex(oldIndices, newIndex); index == -1 {+ sqls = append(sqls, newIndex.ToCreateSQL(operator.fmter))+ }+ }++ return sqls+}+func (*Operator) findColumnByName(table *Table, columnName ColumnName) int {for i, column := range table.Columns {if column.Name == columnName {@@ -142,3 +390,27 @@ func (*Operator) findUniqueConstraint(uniqueConstraints []*UniqueConstraint, conreturn -1}++func (*Operator) findForeignKeyConstraint(table *Table, constraint Constraint) int {+ if constraint.Type() != ConstraintTypeForeignKey {+ return -1+ }++ for i, fkConstraint := range table.ForeignKeyConstraints {+ if fkConstraint.Equals(constraint) {+ return i+ }+ }++ return -1+}++func (*Operator) findIndex(indices []Index, index Index) int {+ for i, inputIndex := range indices {+ if index.Equals(inputIndex) {+ return i+ }+ }++ return -1+}diff --git a/pkg/sqlschema/operator_test.go b/pkg/sqlschema/operator_test.goindex 6ea932ff98..f67b27226b 100644--- a/pkg/sqlschema/operator_test.go+++ b/pkg/sqlschema/operator_test.go@@ -2,6 +2,7 @@ package sqlschemaimport ("testing"+ "time""github.com/stretchr/testify/assert""github.com/uptrace/bun/schema"@@ -54,9 +55,8 @@ func TestOperatorAddColumn(t *testing.T) {column *Columnval anyuniqueConstraints []*UniqueConstraint- support OperatorSupport- expectedSQLs [][]byteexpectedTable *Table+ expected map[OperatorSupport][][]byte}{{name: "NullableNoDefault_DoesNotExist",@@ -68,19 +68,21 @@ func TestOperatorAddColumn(t *testing.T) {},column: &Column{Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},val: nil,- support: OperatorSupport{- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: true,- },- expectedSQLs: [][]byte{- []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "name" TEXT`),- },expectedTable: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},{Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},},+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "name" TEXT`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "name" TEXT`),+ },},},{@@ -94,21 +96,21 @@ func TestOperatorAddColumn(t *testing.T) {},column: &Column{Name: "name", DataType: DataTypeBigInt, Nullable: true, Default: ""},val: nil,- support: OperatorSupport{- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: true,- },- expectedSQLs: [][]byte{},expectedTable: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},{Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},},+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {},+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {},},},{- name: "NotNullableNoDefaultNoVal_DoesNotExist",+ name: "TextNotNullableNoDefaultNoVal_DoesNotExist",table: &Table{Name: "users",Columns: []*Column{@@ -117,25 +119,32 @@ func TestOperatorAddColumn(t *testing.T) {},column: &Column{Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},val: nil,- support: OperatorSupport{- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: true,- },- expectedSQLs: [][]byte{- []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "name" TEXT`),- []byte(`UPDATE "users" SET "name" = ''`),- []byte(`ALTER TABLE "users" ALTER COLUMN "name" SET NOT NULL`),- },expectedTable: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},{Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},},+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "name" TEXT`),+ []byte(`UPDATE "users" SET "name" = ''`),+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id", "name") SELECT "id", "name" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "name" TEXT`),+ []byte(`UPDATE "users" SET "name" = ''`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "name" SET NOT NULL`),+ },},},{- name: "NotNullableNoDefault_DoesNotExist",+ name: "IntegerNotNullableNoDefaultNoVal_DoesNotExist",table: &Table{Name: "users",Columns: []*Column{@@ -143,81 +152,154 @@ func TestOperatorAddColumn(t *testing.T) {},},column: &Column{Name: "num", DataType: DataTypeInteger, Nullable: false, Default: ""},- val: int64(100),- support: OperatorSupport{- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: true,- },- expectedSQLs: [][]byte{- []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "num" INTEGER`),- []byte(`UPDATE "users" SET "num" = 100`),- []byte(`ALTER TABLE "users" ALTER COLUMN "num" SET NOT NULL`),- },+ val: nil,expectedTable: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},{Name: "num", DataType: DataTypeInteger, Nullable: false, Default: ""},},+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "num" INTEGER`),+ []byte(`UPDATE "users" SET "num" = 0`),+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "num" INTEGER NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id", "num") SELECT "id", "num" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "num" INTEGER`),+ []byte(`UPDATE "users" SET "num" = 0`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "num" SET NOT NULL`),+ },},},{- name: "NotNullableNoDefault_DoesNotExist_AlterColumnSetNotNullFalse",+ name: "IntegerNotNullableNoDefaultVal_DoesNotExist",table: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},- {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},},},column: &Column{Name: "num", DataType: DataTypeInteger, Nullable: false, Default: ""},val: int64(100),- uniqueConstraints: []*UniqueConstraint{- {ColumnNames: []ColumnName{"name"}},+ expectedTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "num", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},},- support: OperatorSupport{- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: false,+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "num" INTEGER`),+ []byte(`UPDATE "users" SET "num" = 100`),+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "num" INTEGER NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id", "num") SELECT "id", "num" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "num" INTEGER`),+ []byte(`UPDATE "users" SET "num" = 100`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "num" SET NOT NULL`),+ },},- expectedSQLs: [][]byte{- []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "num" INTEGER`),- []byte(`UPDATE "users" SET "num" = 100`),- []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT NOT NULL, "num" INTEGER NOT NULL)`),- []byte(`INSERT INTO "users__temp" ("id", "name", "num") SELECT "id", "name", "num" FROM "users"`),- []byte(`DROP TABLE IF EXISTS "users"`),- []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),- []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_name" ON "users" ("name")`),+ },+ {+ name: "BooleanNotNullableNoDefaultValNoVal_DoesNotExist",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },},+ column: &Column{Name: "is_admin", DataType: DataTypeBoolean, Nullable: false, Default: ""},+ val: nil,expectedTable: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},- {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},- {Name: "num", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "is_admin", DataType: DataTypeBoolean, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "is_admin" BOOLEAN`),+ // Set to the zero value+ []byte(`UPDATE "users" SET "is_admin" = FALSE`),+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "is_admin" BOOLEAN NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id", "is_admin") SELECT "id", "is_admin" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "is_admin" BOOLEAN`),+ // Set to the zero value+ []byte(`UPDATE "users" SET "is_admin" = FALSE`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "is_admin" SET NOT NULL`),},},},{- name: "MismatchingDataType_DoesExist_AlterColumnSetNotNullFalse",+ name: "BooleanNullableDefaultVal_DoesNotExist",table: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},- {Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},},},- column: &Column{Name: "name", DataType: DataTypeBigInt, Nullable: false, Default: ""},+ column: &Column{Name: "is_admin", DataType: DataTypeBoolean, Nullable: true, Default: "TRUE"},val: nil,- support: OperatorSupport{- ColumnIfNotExistsExists: true,- AlterColumnSetNotNull: false,+ expectedTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "is_admin", DataType: DataTypeBoolean, Nullable: true, Default: "TRUE"},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},},- expectedSQLs: [][]byte{},+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "is_admin" BOOLEAN DEFAULT TRUE`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "is_admin" BOOLEAN DEFAULT TRUE`),+ },+ },+ },+ {+ name: "TimestampNullableDefaultValAndVal_DoesNotExist",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ },+ column: &Column{Name: "created_at", DataType: DataTypeTimestamp, Nullable: true, Default: "CURRENT_TIMESTAMP"},+ val: time.Time{},expectedTable: &Table{Name: "users",Columns: []*Column{{Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},- {Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},+ {Name: "created_at", DataType: DataTypeTimestamp, Nullable: true, Default: "CURRENT_TIMESTAMP"},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "created_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP`),+ []byte(`UPDATE "users" SET "created_at" = '0001-01-01 00:00:00+00:00'`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "created_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP`),+ []byte(`UPDATE "users" SET "created_at" = '0001-01-01 00:00:00+00:00'`),},},},@@ -226,11 +308,15 @@ func TestOperatorAddColumn(t *testing.T) {for _, testCase := range testCases {t.Run(testCase.name, func(t *testing.T) {fmter := NewFormatter(schema.NewNopFormatter().Dialect())- operator := NewOperator(fmter, testCase.support)- actuals := operator.AddColumn(testCase.table, testCase.uniqueConstraints, testCase.column, testCase.val)- assert.Equal(t, testCase.expectedSQLs, actuals)- assert.Equal(t, testCase.expectedTable, testCase.table)+ for support, expectedSQLs := range testCase.expected {+ operator := NewOperator(fmter, support)+ clonedTable := testCase.table.Clone()++ actuals := operator.AddColumn(clonedTable, testCase.uniqueConstraints, testCase.column, testCase.val)+ assert.Equal(t, expectedSQLs, actuals)+ assert.Equal(t, testCase.expectedTable, clonedTable)+ }})}}@@ -246,7 +332,7 @@ func TestOperatorDropConstraint(t *testing.T) {expectedTable *Table}{{- name: "PrimaryKeyConstraint_DoesExist_DropConstraintTrue",+ name: "PrimaryKeyConstraint_DoesExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -260,7 +346,7 @@ func TestOperatorDropConstraint(t *testing.T) {ColumnNames: []ColumnName{"id"},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{[]byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "pk_users"`),@@ -273,7 +359,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "PrimaryKeyConstraint_DoesNotExist_DropConstraintTrue",+ name: "PrimaryKeyConstraint_DoesNotExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -284,7 +370,7 @@ func TestOperatorDropConstraint(t *testing.T) {ColumnNames: []ColumnName{"id"},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{},expectedTable: &Table{@@ -295,7 +381,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "PrimaryKeyConstraintDifferentName_DoesExist_DropConstraintTrue",+ name: "PrimaryKeyConstraintDifferentName_DoesExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -310,7 +396,7 @@ func TestOperatorDropConstraint(t *testing.T) {ColumnNames: []ColumnName{"id"},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{[]byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "pk_users_different_name"`),@@ -323,7 +409,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "PrimaryKeyConstraint_DoesExist_DropConstraintFalse",+ name: "PrimaryKeyConstraint_DoesExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -337,7 +423,7 @@ func TestOperatorDropConstraint(t *testing.T) {ColumnNames: []ColumnName{"id"},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{[]byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL)`),@@ -353,7 +439,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "PrimaryKeyConstraint_DoesNotExist_DropConstraintFalse",+ name: "PrimaryKeyConstraint_DoesNotExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -364,7 +450,7 @@ func TestOperatorDropConstraint(t *testing.T) {ColumnNames: []ColumnName{"id"},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{},expectedTable: &Table{@@ -375,7 +461,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "UniqueConstraint_DoesExist_DropConstraintTrue",+ name: "UniqueConstraint_DoesExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -390,7 +476,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"name"}},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{[]byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "uq_users_name"`),@@ -404,7 +490,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "UniqueConstraint_DoesNotExist_DropConstraintTrue",+ name: "UniqueConstraint_DoesNotExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -419,7 +505,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{},expectedTable: &Table{@@ -431,7 +517,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "UniqueConstraint_DoesExist_DropConstraintFalse",+ name: "UniqueConstraint_DoesExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -446,7 +532,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"name"}},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{[]byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT NOT NULL)`),@@ -463,7 +549,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "UniqueConstraint_DoesNotExist_DropConstraintFalse",+ name: "UniqueConstraint_DoesNotExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -478,7 +564,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{},expectedTable: &Table{@@ -490,7 +576,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "ForeignKeyConstraint_DoesExist_DropConstraintTrue",+ name: "ForeignKeyConstraint_DoesExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -506,7 +592,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{[]byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "fk_users_org_id"`),@@ -521,7 +607,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "ForeignKeyConstraintDifferentName_DoesExist_DropConstraintTrue",+ name: "ForeignKeyConstraintDifferentName_DoesExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -537,7 +623,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{[]byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "my_fk"`),@@ -552,7 +638,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "ForeignKeyConstraint_DoesNotExist_DropConstraintTrue",+ name: "ForeignKeyConstraint_DoesNotExist_SCreateAndDropConstraintTrue",table: &Table{Name: "users",Columns: []*Column{@@ -569,7 +655,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: true,+ SCreateAndDropConstraint: true,},expectedSQLs: [][]byte{},expectedTable: &Table{@@ -584,7 +670,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "ForeignKeyConstraint_DoesExist_DropConstraintFalse",+ name: "ForeignKeyConstraint_DoesExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -600,7 +686,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{[]byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "org_id" INTEGER NOT NULL)`),@@ -620,7 +706,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "ForeignKeyConstraintDifferentName_DoesExist_DropConstraintFalse",+ name: "ForeignKeyConstraintDifferentName_DoesExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -636,7 +722,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{[]byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "org_id" INTEGER NOT NULL)`),@@ -656,7 +742,7 @@ func TestOperatorDropConstraint(t *testing.T) {},},{- name: "ForeignKeyConstraint_DoesNotExist_DropConstraintFalse",+ name: "ForeignKeyConstraint_DoesNotExist_SCreateAndDropConstraintFalse",table: &Table{Name: "users",Columns: []*Column{@@ -673,7 +759,7 @@ func TestOperatorDropConstraint(t *testing.T) {{ColumnNames: []ColumnName{"id"}},},support: OperatorSupport{- DropConstraint: false,+ SCreateAndDropConstraint: false,},expectedSQLs: [][]byte{},expectedTable: &Table{@@ -700,3 +786,363 @@ func TestOperatorDropConstraint(t *testing.T) {})}}++func TestOperatorAlterTable(t *testing.T) {+ testCases := []struct {+ name string+ table *Table+ uniqueConstraints []*UniqueConstraint+ newTable *Table+ expected map[OperatorSupport][][]byte+ }{+ {+ name: "NoOperation",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ },+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {},+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {},+ },+ },+ {+ name: "RenameTable",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ },+ newTable: &Table{+ Name: "users_new",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" RENAME TO "users_new"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" RENAME TO "users_new"`),+ },+ },+ },+ {+ name: "AddColumn_NullableNoDefault_SAlterTableAddAndDropColumnIfNotExistsAndExistsTrue",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ },+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ {Name: "age", DataType: DataTypeInteger, Nullable: true, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`ALTER TABLE "users" ADD COLUMN "age" INTEGER`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "age" INTEGER`),+ },+ },+ },+ {+ name: "CreatePrimaryKeyConstraint",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{+ ColumnNames: []ColumnName{"id"},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"))`),+ []byte(`INSERT INTO "users__temp" ("id") SELECT "id" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" ADD CONSTRAINT "pk_users" PRIMARY KEY ("id")`),+ },+ },+ },+ {+ name: "DropPrimaryKeyConstraint_AlterColumnNullable",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{ColumnNames: []ColumnName{"id"}},+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ // first drop to remove the primary key constraint+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT)`),+ []byte(`INSERT INTO "users__temp" ("id", "name") SELECT "id", "name" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ // second drop to make the column nullable+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id", "name") SELECT "id", "name" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "pk_users"`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "name" SET NOT NULL`),+ },+ },+ },+ {+ name: "DropForeignKeyConstraint_DropColumn",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "org_id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{+ {ReferencingColumnName: "org_id", ReferencedTableName: "orgs", ReferencedColumnName: "id"},+ },+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ // first drop to remove the foreign key constraint+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "org_id" INTEGER NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id", "org_id") SELECT "id", "org_id" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ // second drop to remove the column+ []byte(`ALTER TABLE "users" DROP COLUMN "org_id"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ // first drop to remove the foreign key constraint+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "fk_users_org_id"`),+ // second drop to remove the column+ []byte(`ALTER TABLE "users" DROP COLUMN IF EXISTS "org_id"`),+ },+ },+ },+ {+ name: "DropMultipleConstraints",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ {Name: "age", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "org_id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "team_id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{ColumnNames: []ColumnName{"id"}},+ ForeignKeyConstraints: []*ForeignKeyConstraint{+ {ReferencingColumnName: "org_id", ReferencedTableName: "orgs", ReferencedColumnName: "id"},+ {ReferencingColumnName: "team_id", ReferencedTableName: "teams", ReferencedColumnName: "id"},+ },+ },+ uniqueConstraints: []*UniqueConstraint{+ {ColumnNames: []ColumnName{"name", "age"}},+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ {Name: "age", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "org_id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "team_id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ ForeignKeyConstraints: []*ForeignKeyConstraint{+ {ReferencingColumnName: "team_id", ReferencedTableName: "teams", ReferencedColumnName: "id"},+ },+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT NOT NULL, "age" INTEGER NOT NULL, "org_id" INTEGER NOT NULL, "team_id" INTEGER NOT NULL, CONSTRAINT "fk_users_team_id" FOREIGN KEY ("team_id") REFERENCES "teams" ("id"))`),+ []byte(`INSERT INTO "users__temp" ("id", "name", "age", "org_id", "team_id") SELECT "id", "name", "age", "org_id", "team_id" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_name_age" ON "users" ("name", "age")`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "pk_users"`),+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "fk_users_org_id"`),+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "uq_users_name_age"`),+ []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_name_age" ON "users" ("name", "age")`),+ },+ },+ },+ {+ name: "DropUniqueConstraints_AlterMultipleColumns",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: true, Default: ""},+ {Name: "age", DataType: DataTypeInteger, Nullable: true, Default: ""},+ {Name: "email", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{ColumnNames: []ColumnName{"id"}},+ ForeignKeyConstraints: []*ForeignKeyConstraint{+ {ReferencingColumnName: "org_id", ReferencedTableName: "orgs", ReferencedColumnName: "id"},+ },+ },+ uniqueConstraints: []*UniqueConstraint{+ {ColumnNames: []ColumnName{"email"}},+ {name: "my_name_constraint", ColumnNames: []ColumnName{"name"}},+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeInteger, Nullable: false, Default: ""},+ {Name: "name", DataType: DataTypeText, Nullable: false, Default: ""},+ {Name: "age", DataType: DataTypeInteger, Nullable: false, Default: "0"},+ {Name: "email", DataType: DataTypeInteger, Nullable: false, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{ColumnNames: []ColumnName{"id"}},+ ForeignKeyConstraints: []*ForeignKeyConstraint{+ {ReferencingColumnName: "org_id", ReferencedTableName: "orgs", ReferencedColumnName: "id"},+ },+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ // first drop to remove unique constraint+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT, "age" INTEGER, "email" INTEGER NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"), CONSTRAINT "fk_users_org_id" FOREIGN KEY ("org_id") REFERENCES "orgs" ("id"))`),+ []byte(`INSERT INTO "users__temp" ("id", "name", "age", "email") SELECT "id", "name", "age", "email" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ // second drop to change all columns+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" INTEGER NOT NULL, "name" TEXT NOT NULL, "age" INTEGER NOT NULL DEFAULT 0, "email" INTEGER NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"), CONSTRAINT "fk_users_org_id" FOREIGN KEY ("org_id") REFERENCES "orgs" ("id"))`),+ []byte(`INSERT INTO "users__temp" ("id", "name", "age", "email") SELECT "id", "name", "age", "email" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ // create unique index for the constraint+ []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_email" ON "users" ("email")`),+ []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_name" ON "users" ("name")`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "uq_users_email"`),+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "my_name_constraint"`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "name" SET NOT NULL`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "age" SET NOT NULL`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "age" SET DEFAULT 0`),+ []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_email" ON "users" ("email")`),+ []byte(`CREATE UNIQUE INDEX IF NOT EXISTS "uq_users_name" ON "users" ("name")`),+ },+ },+ },+ {+ name: "ChangePrimaryKeyConstraint",+ table: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "id", DataType: DataTypeText, Nullable: false, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{ColumnNames: []ColumnName{"id"}},+ },+ newTable: &Table{+ Name: "users",+ Columns: []*Column{+ {Name: "uuid", DataType: DataTypeText, Nullable: false, Default: ""},+ },+ PrimaryKeyConstraint: &PrimaryKeyConstraint{ColumnNames: []ColumnName{"uuid"}},+ ForeignKeyConstraints: []*ForeignKeyConstraint{},+ },+ expected: map[OperatorSupport][][]byte{+ {SCreateAndDropConstraint: false, SAlterTableAddAndDropColumnIfNotExistsAndExists: false, SAlterTableAlterColumnSetAndDrop: false}: {+ // first drop to remove the primary key constraint+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("id" TEXT NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("id") SELECT "id" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ // drop the column+ []byte(`ALTER TABLE "users" DROP COLUMN "id"`),+ // add the column+ []byte(`ALTER TABLE "users" ADD COLUMN "uuid" TEXT`),+ []byte(`UPDATE "users" SET "uuid" = ''`),+ // second drop to make it non-nullable+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("uuid" TEXT NOT NULL)`),+ []byte(`INSERT INTO "users__temp" ("uuid") SELECT "uuid" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ // third drop to add the primary key constraint+ []byte(`CREATE TABLE IF NOT EXISTS "users__temp" ("uuid" TEXT NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("uuid"))`),+ []byte(`INSERT INTO "users__temp" ("uuid") SELECT "uuid" FROM "users"`),+ []byte(`DROP TABLE IF EXISTS "users"`),+ []byte(`ALTER TABLE "users__temp" RENAME TO "users"`),+ },+ {SCreateAndDropConstraint: true, SAlterTableAddAndDropColumnIfNotExistsAndExists: true, SAlterTableAlterColumnSetAndDrop: true}: {+ []byte(`ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "pk_users"`),+ []byte(`ALTER TABLE "users" DROP COLUMN IF EXISTS "id"`),+ []byte(`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "uuid" TEXT`),+ []byte(`UPDATE "users" SET "uuid" = ''`),+ []byte(`ALTER TABLE "users" ALTER COLUMN "uuid" SET NOT NULL`),+ []byte(`ALTER TABLE "users" ADD CONSTRAINT "pk_users" PRIMARY KEY ("uuid")`),+ },+ },+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ fmter := NewFormatter(schema.NewNopFormatter().Dialect())+ for support, sqls := range testCase.expected {+ operator := NewOperator(fmter, support)+ clonedTable := testCase.table.Clone()++ actuals := operator.AlterTable(clonedTable, testCase.uniqueConstraints, testCase.newTable)+ assert.Equal(t, sqls, actuals)+ assert.EqualValues(t, testCase.newTable, clonedTable)+ }+ })+ }+}diff --git a/pkg/sqlschema/sqlitesqlschema/provider.go b/pkg/sqlschema/sqlitesqlschema/provider.goindex 354df7a035..0ef3510f01 100644--- a/pkg/sqlschema/sqlitesqlschema/provider.go+++ b/pkg/sqlschema/sqlitesqlschema/provider.go@@ -33,9 +33,9 @@ func New(ctx context.Context, providerSettings factory.ProviderSettings, configsettings: settings,sqlstore: sqlstore,operator: sqlschema.NewOperator(fmter, sqlschema.OperatorSupport{- DropConstraint: false,- ColumnIfNotExistsExists: false,- AlterColumnSetNotNull: false,+ SCreateAndDropConstraint: false,+ SAlterTableAddAndDropColumnIfNotExistsAndExists: false,+ SAlterTableAlterColumnSetAndDrop: false,}),}, nil}@@ -56,7 +56,7 @@ func (provider *provider) GetTable(ctx context.Context, tableName sqlschema.TablBunDB().NewRaw("SELECT sql FROM sqlite_master WHERE type IN (?) AND tbl_name = ? AND sql IS NOT NULL", bun.In([]string{"table"}), string(tableName)).Scan(ctx, &sql); err != nil {- return nil, nil, err+ return nil, nil, provider.sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "table (%s) not found", tableName)}table, uniqueConstraints, err := parseCreateTable(sql, provider.fmter)@@ -73,7 +73,7 @@ func (provider *provider) GetIndices(ctx context.Context, tableName sqlschema.TaBunDB().QueryContext(ctx, "SELECT * FROM PRAGMA_index_list(?)", string(tableName))if err != nil {- return nil, err+ return nil, provider.sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "no indices for table (%s) found", tableName)}defer func() {@@ -115,10 +115,16 @@ func (provider *provider) GetIndices(ctx context.Context, tableName sqlschema.Ta}if unique {- indices = append(indices, (&sqlschema.UniqueIndex{+ index := &sqlschema.UniqueIndex{TableName: tableName,ColumnNames: columns,- }).Named(name).(*sqlschema.UniqueIndex))+ }++ if index.Name() == name {+ indices = append(indices, index)+ } else {+ indices = append(indices, index.Named(name))+ }}}diff --git a/pkg/sqlschema/sqlschema.go b/pkg/sqlschema/sqlschema.goindex 1fdeab35c8..e1b886b02c 100644--- a/pkg/sqlschema/sqlschema.go+++ b/pkg/sqlschema/sqlschema.go@@ -34,7 +34,10 @@ type SQLOperator interface {// Returns a list of SQL statements to rename a table.RenameTable(*Table, TableName) [][]byte- // Returns a list of SQL statements to recreate a table.+ // Returns a list of SQL statements to alter the input table to the new table. It converts all unique constraints to unique indices and drops the unique constraints.+ AlterTable(*Table, []*UniqueConstraint, *Table) [][]byte++ // Returns a list of SQL statements to recreate a table. In recreating the table, it converts all unqiue constraints to indices and copies data from the old table.RecreateTable(*Table, []*UniqueConstraint) [][]byte// Returns a list of SQL statements to create an index.@@ -47,11 +50,21 @@ type SQLOperator interface {// If the column is not nullable, the column is added with the input value, then the column is made non-nullable.AddColumn(*Table, []*UniqueConstraint, *Column, any) [][]byte+ // Returns a list of SQL statements to alter a column.+ AlterColumn(*Table, []*UniqueConstraint, *Column) [][]byte+// Returns a list of SQL statements to drop a column from a table.DropColumn(*Table, *Column) [][]byte+ // Returns a list of SQL statements to create a constraint on a table.+ CreateConstraint(*Table, []*UniqueConstraint, Constraint) [][]byte+// Returns a list of SQL statements to drop a constraint from a table.DropConstraint(*Table, []*UniqueConstraint, Constraint) [][]byte++ // Returns a list of SQL statements to get the difference between the input indices and the output indices. If the input indices are named,+ // they are dropped and recreated with autogenerated names.+ DiffIndices([]Index, []Index) [][]byte}type SQLFormatter interface {