Skip to content

Commit 24436c9

Browse files
committed
fix: handle column aliasing the rowid
1 parent 202faf3 commit 24436c9

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/inferQueryResult.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ export interface ColumnInfo {
1515
}
1616

1717
// https://www.sqlite.org/datatype3.html#determination_of_column_affinity
18+
// https://www.sqlite.org/lang_createtable.html#rowids_and_the_integer_primary_key
19+
// Note that this query doesn't handle the exception to rowid aliasing
1820
const COLUMN_DATA_QUERY = `
1921
SELECT
20-
\`notnull\`,
22+
iif(\`notnull\` = 1, 1, TYPE = 'INTEGER' AND pk = 1 AND (SELECT COUNT(*) FROM pragma_table_info(:tableName) WHERE pk != 0) = 1) AS 'notnull',
2123
CASE
2224
WHEN TYPE LIKE '%INT%' THEN ${ColumnType.Number.toString()}
2325
WHEN (TYPE LIKE '%CHAR%')

tests/inferQueryResult.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,25 @@ it("should prove that a column is only null", () => {
154154
{ name: "id", type: ColumnType.Null },
155155
]);
156156
});
157+
158+
it("should detect when a column is an alias for rowid", () => {
159+
const result = testInferQueryResult(
160+
"CREATE TABLE foo (id integer primary key)",
161+
"SELECT id FROM foo",
162+
);
163+
164+
expect(result).toStrictEqual<typeof result>([
165+
{ name: "id", type: ColumnType.Number },
166+
]);
167+
});
168+
169+
it("should detect when a column is not an alias for rowid", () => {
170+
const result = testInferQueryResult(
171+
"CREATE TABLE foo (id integer, name text, PRIMARY KEY(id, name))",
172+
"SELECT id FROM foo",
173+
);
174+
175+
expect(result).toStrictEqual<typeof result>([
176+
{ name: "id", type: ColumnType.Number | ColumnType.Null },
177+
]);
178+
});

0 commit comments

Comments
 (0)