diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt index df28066b1c..3e3c113dcf 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt @@ -251,30 +251,52 @@ open class SQLServerDialect : VendorDialect(dialectName, SQLServerDataTypeProvid return columnDefault !in nonAcceptableDefaults } - override fun modifyColumn(column: Column<*>, columnDiff: ColumnDiff): List = - super.modifyColumn(column, columnDiff).map { statement -> - if (columnDiff.defaults) { - val transaction = TransactionManager.current() - val tableName = transaction.identity(column.table) - val colName = transaction.identity(column) - - val dropConstraint = "DROP CONSTRAINT IF EXISTS DF_${tableName}_$colName" - - column.dbDefaultValue?.let { - buildString { - append(statement.substringBefore("MODIFY COLUMN") + dropConstraint) + override fun modifyColumn(column: Column<*>, columnDiff: ColumnDiff): List { + val transaction = TransactionManager.current() + val tableName = transaction.identity(column.table) + val colName = transaction.identity(column) + + val alterTablePart = "ALTER TABLE $tableName " + + val statements = mutableListOf() + + statements.add( + buildString { + append(alterTablePart + "ALTER COLUMN $colName ${column.columnType.sqlType()}") + + if (columnDiff.nullability) { + val defaultValue = column.dbDefaultValue + val isPKColumn = column.table.primaryKey?.columns?.contains(column) == true + + if (column.columnType.nullable || + (defaultValue != null && column.defaultValueFun == null && !currentDialect.isAllowedAsColumnDefault(defaultValue))) { + append(" NULL") + } else if (!isPKColumn) { + append(" NOT NULL") + } + } + }) + + if (columnDiff.defaults) { + val dropConstraint = "DROP CONSTRAINT IF EXISTS DF_${tableName}_$colName" + + statements.add( + buildString { + column.dbDefaultValue?.let { + append(alterTablePart + dropConstraint) append("; ") append( - statement.substringBefore("MODIFY COLUMN") + + alterTablePart + "ADD CONSTRAINT DF_${tableName}_$colName DEFAULT ${SQLServerDataTypeProvider.processForDefaultValue(it)} for $colName" ) - } - } ?: (statement.substringBefore("MODIFY COLUMN") + dropConstraint) - } else { - statement.replace("MODIFY COLUMN", "ALTER COLUMN") - } + } ?: append(alterTablePart + dropConstraint) + } + ) } + return statements + } + override fun createDatabase(name: String): String = "CREATE DATABASE ${name.inProperCase()}" override fun dropDatabase(name: String) = "DROP DATABASE ${name.inProperCase()}"