Skip to content

Commit c8599fb

Browse files
committed
SQLiteDatabaseClient schema
1 parent c574ed9 commit c8599fb

File tree

1 file changed

+47
-4
lines changed

1 file changed

+47
-4
lines changed

src/sqlite.js

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,16 @@ export class SQLiteDatabaseClient {
2828
text(rows.map(row => row.detail).join("\n"))
2929
]);
3030
}
31-
async describe(object) {
32-
const rows = await (object === undefined
33-
? this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`)
34-
: this.query(`SELECT * FROM pragma_table_info(?)`, [object]));
31+
async describeTables() {
32+
return this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`);
33+
}
34+
async describeColumns({table} = {}) {
35+
const rows = await this.query(`SELECT name, type, notnull FROM pragma_table_info(?) ORDER BY cid`, [table]);
36+
if (!rows.length) throw new Error(`table not found: ${table}`);
37+
return rows.map(({name, type, notnull}) => ({name, type: sqliteType(type), databaseType: type, nullable: !notnull}));
38+
}
39+
async describe(table) {
40+
const rows = await (table === undefined ? this.describeTables() : this.describeColumns({table}));
3541
if (!rows.length) throw new Error("Not found");
3642
const {columns} = rows;
3743
return element("table", {value: rows}, [
@@ -46,10 +52,47 @@ export class SQLiteDatabaseClient {
4652
return [strings.join("?"), params];
4753
}
4854
}
55+
4956
Object.defineProperty(SQLiteDatabaseClient.prototype, "dialect", {
5057
value: "sqlite"
5158
});
5259

60+
// https://www.sqlite.org/datatype3.html
61+
function sqliteType(type) {
62+
switch (type) {
63+
case "NULL":
64+
return "null";
65+
case "INT":
66+
case "INTEGER":
67+
case "TINYINT":
68+
case "SMALLINT":
69+
case "MEDIUMINT":
70+
case "BIGINT":
71+
case "UNSIGNED BIG INT":
72+
case "INT2":
73+
case "INT8":
74+
return "integer";
75+
case "TEXT":
76+
case "CLOB":
77+
return "string";
78+
case "REAL":
79+
case "DOUBLE":
80+
case "DOUBLE PRECISION":
81+
case "FLOAT":
82+
case "NUMERIC":
83+
return "number";
84+
case "BLOB":
85+
return "buffer";
86+
case "DATE":
87+
case "DATETIME":
88+
return "string"; // TODO convert strings to Date instances in sql.js
89+
default:
90+
return /^(?:(?:(?:VARYING|NATIVE) )?CHARACTER|(?:N|VAR|NVAR)CHAR)\(/.test(type) ? "string"
91+
: /^(?:DECIMAL|NUMERIC)\(/.test(type) ? "number"
92+
: "other";
93+
}
94+
}
95+
5396
function load(source) {
5497
return typeof source === "string" ? fetch(source).then(load)
5598
: source instanceof Response || source instanceof Blob ? source.arrayBuffer().then(load)

0 commit comments

Comments
 (0)