diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 4388adce8..5d69e121a 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -471,7 +471,7 @@ public final class TableDefinition { } let indexStatements = try columns - .compactMap { $0.indexDefinition(in: name) } + .compactMap { $0.indexDefinition(in: name, ifNotExists: ifNotExists) } .map { try $0.sql(db) } statements.append(contentsOf: indexStatements) return statements.joined(separator: "; ") @@ -570,7 +570,7 @@ public final class TableAlteration { let statement = chunks.joined(separator: " ") statements.append(statement) - if let indexDefinition = column.indexDefinition(in: name) { + if let indexDefinition = column.indexDefinition(in: name, ifNotExists: false) { try statements.append(indexDefinition.sql(db)) } case let .rename(oldName, newName): @@ -934,7 +934,7 @@ public final class ColumnDefinition { return chunks.joined(separator: " ") } - fileprivate func indexDefinition(in table: String) -> IndexDefinition? { + fileprivate func indexDefinition(in table: String, ifNotExists: Bool) -> IndexDefinition? { switch index { case .none: return nil case .unique: return nil @@ -944,7 +944,7 @@ public final class ColumnDefinition { table: table, columns: [name], unique: false, - ifNotExists: false, + ifNotExists: ifNotExists, condition: nil) } } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 8ffc2b079..dc789db30 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -140,6 +140,21 @@ class TableDefinitionTests: GRDBTestCase { } } + // Regression test for https://github.com/groue/GRDB.swift/issues/838 + func testColumnIndexedInheritsIfNotExistsFlag() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + sqlQueries.removeAll() + try db.create(table: "test", ifNotExists: true) { t in + t.column("a", .integer).indexed() + t.column("b", .integer).indexed() + } + assertEqualSQL(sqlQueries[0], "CREATE TABLE IF NOT EXISTS \"test\" (\"a\" INTEGER, \"b\" INTEGER)") + assertEqualSQL(sqlQueries[1], "CREATE INDEX IF NOT EXISTS \"test_on_a\" ON \"test\"(\"a\")") + assertEqualSQL(sqlQueries[2], "CREATE INDEX IF NOT EXISTS \"test_on_b\" ON \"test\"(\"b\")") + } + } + func testColumnUnique() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in