Skip to content

SQLiteDatabaseClient schema methods #283

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 47 additions & 5 deletions src/sqlite.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,16 @@ export class SQLiteDatabaseClient {
text(rows.map(row => row.detail).join("\n"))
]);
}
async describe(object) {
const rows = await (object === undefined
? this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`)
: this.query(`SELECT * FROM pragma_table_info(?)`, [object]));
if (!rows.length) throw new Error("Not found");
async describeTables() {
return this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`);
}
async describeColumns({table} = {}) {
const rows = await this.query(`SELECT name, type, notnull FROM pragma_table_info(?) ORDER BY cid`, [table]);
if (!rows.length) throw new Error(`table not found: ${table}`);
return rows.map(({name, type, notnull}) => ({name, type: sqliteType(type), databaseType: type, nullable: !notnull}));
}
async describe(table) {
const rows = await (table === undefined ? this.describeTables() : this.describeColumns({table}));
const {columns} = rows;
return element("table", {value: rows}, [
element("thead", [element("tr", columns.map(c => element("th", [text(c)])))]),
Expand All @@ -46,10 +51,47 @@ export class SQLiteDatabaseClient {
return [strings.join("?"), params];
}
}

Object.defineProperty(SQLiteDatabaseClient.prototype, "dialect", {
value: "sqlite"
});

// https://www.sqlite.org/datatype3.html
function sqliteType(type) {
switch (type) {
case "NULL":
return "null";
case "INT":
case "INTEGER":
case "TINYINT":
case "SMALLINT":
case "MEDIUMINT":
case "BIGINT":
case "UNSIGNED BIG INT":
case "INT2":
case "INT8":
return "integer";
case "TEXT":
case "CLOB":
return "string";
case "REAL":
case "DOUBLE":
case "DOUBLE PRECISION":
case "FLOAT":
case "NUMERIC":
return "number";
case "BLOB":
return "buffer";
case "DATE":
case "DATETIME":
return "string"; // TODO convert strings to Date instances in sql.js
default:
return /^(?:(?:(?:VARYING|NATIVE) )?CHARACTER|(?:N|VAR|NVAR)CHAR)\(/.test(type) ? "string"
: /^(?:DECIMAL|NUMERIC)\(/.test(type) ? "number"
: "other";
}
}

function load(source) {
return typeof source === "string" ? fetch(source).then(load)
: source instanceof Response || source instanceof Blob ? source.arrayBuffer().then(load)
Expand Down