Skip to content

Commit d34f63a

Browse files
authored
Merge pull request #1217 from stefansaasen/bugfix/composite-primary-keys
SchemaReader: return the correct column definition for a composite primary key
2 parents f1bee07 + 7997c85 commit d34f63a

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

Sources/SQLite/Schema/SchemaReader.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public class SchemaReader {
2525
.map { (row: Row) -> ColumnDefinition in
2626
ColumnDefinition(
2727
name: row[TableInfoTable.nameColumn],
28-
primaryKey: row[TableInfoTable.primaryKeyColumn] == 1 ?
28+
primaryKey: (row[TableInfoTable.primaryKeyColumn] ?? 0) > 0 ?
2929
try parsePrimaryKey(column: row[TableInfoTable.nameColumn]) : nil,
3030
type: ColumnDefinition.Affinity(row[TableInfoTable.typeColumn]),
3131
nullable: row[TableInfoTable.notNullColumn] == 0,

Tests/SQLiteTests/Schema/SchemaReaderTests.swift

+37
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,43 @@ class SchemaReaderTests: SQLiteTestCase {
9090
)
9191
}
9292

93+
func test_columnDefinitions_composite_primary_keys() throws {
94+
try db.run("""
95+
CREATE TABLE t (
96+
col1 INTEGER,
97+
col2 INTEGER,
98+
col3 INTEGER,
99+
PRIMARY KEY (col1, col2)
100+
);
101+
""")
102+
103+
XCTAssertEqual(
104+
try schemaReader.columnDefinitions(table: "t"), [
105+
ColumnDefinition(
106+
name: "col1",
107+
primaryKey: .init(autoIncrement: false),
108+
type: .INTEGER,
109+
nullable: true,
110+
defaultValue: .NULL,
111+
references: nil),
112+
ColumnDefinition(
113+
name: "col2",
114+
primaryKey: .init(autoIncrement: false),
115+
type: .INTEGER,
116+
nullable: true,
117+
defaultValue: .NULL,
118+
references: nil),
119+
ColumnDefinition(
120+
name: "col3",
121+
primaryKey: nil,
122+
type: .INTEGER,
123+
nullable: true,
124+
defaultValue: .NULL,
125+
references: nil)
126+
]
127+
)
128+
}
129+
93130
func test_indexDefinitions_no_index() throws {
94131
let indexes = try schemaReader.indexDefinitions(table: "users")
95132
XCTAssertTrue(indexes.isEmpty)

0 commit comments

Comments
 (0)