-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathsqlite.js
158 lines (150 loc) · 4.61 KB
/
sqlite.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
// https://github.com/sql-js/sql.js/issues/284
const SQLite = await (async () => {
const exports = {};
const response = await fetch(import.meta.resolve("npm:sql.js/dist/sql-wasm.js"));
new Function("exports", await response.text())(exports);
return exports.Module({locateFile: (name) => import.meta.resolve("npm:sql.js/dist/") + name});
})();
export default SQLite;
export class SQLiteDatabaseClient {
constructor(db) {
Object.defineProperties(this, {
_db: {value: db}
});
}
static async open(source) {
return new SQLiteDatabaseClient(new SQLite.Database(await load(await source)));
}
async query(query, params) {
return await exec(this._db, query, params);
}
async queryRow(query, params) {
return (await this.query(query, params))[0] || null;
}
async explain(query, params) {
const rows = await this.query(`EXPLAIN QUERY PLAN ${query}`, params);
return element("pre", {className: "observablehq--inspect"}, [text(rows.map((row) => row.detail).join("\n"))]);
}
async describeTables({schema} = {}) {
return this.query(
`SELECT NULLIF(schema, 'main') AS schema, name FROM pragma_table_list() WHERE type = 'table'${
schema == null ? "" : " AND schema = ?"
} AND name NOT LIKE 'sqlite_%' ORDER BY schema, name`,
schema == null ? [] : [schema]
);
}
async describeColumns({schema, table} = {}) {
if (table == null) throw new Error("missing table");
const rows = await this.query(
`SELECT name, type, "notnull" FROM pragma_table_info(?${schema == null ? "" : ", ?"}) ORDER BY cid`,
schema == null ? [table] : [table, schema]
);
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(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");
const {columns} = rows;
return element("table", {value: rows}, [
element("thead", [
element(
"tr",
columns.map((c) => element("th", [text(c)]))
)
]),
element(
"tbody",
rows.map((r) =>
element(
"tr",
columns.map((c) => element("td", [text(r[c])]))
)
)
)
]);
}
async sql() {
return this.query(...this.queryTag.apply(this, arguments));
}
queryTag(strings, ...params) {
return [strings.join("?"), params];
}
export() {
return this._db.export(this._db);
}
}
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 && typeof source.arrayBuffer === "function" // Response, Blob, FileAttachment
? source.arrayBuffer().then(load)
: source instanceof ArrayBuffer
? new Uint8Array(source)
: source;
}
async function exec(db, query, params) {
const [result] = await db.exec(query, params);
if (!result) return [];
const {columns, values} = result;
const rows = values.map((row) => Object.fromEntries(row.map((value, i) => [columns[i], value])));
rows.columns = columns;
return rows;
}
function element(name, props, children) {
if (arguments.length === 2) (children = props), (props = undefined);
const element = document.createElement(name);
if (props !== undefined) for (const p in props) element[p] = props[p];
if (children !== undefined) for (const c of children) element.appendChild(c);
return element;
}
function text(value) {
return document.createTextNode(value);
}