-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdatabase.ts
54 lines (48 loc) · 1.69 KB
/
database.ts
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
import { sqlTemplate } from "./template";
import type { Connector, Database, SQLDialect } from "./types";
const SQL_SELECT_RE = /^select/i;
const SQL_RETURNING_RE = /[\s]returning[\s]/i;
const DIALECTS_WITH_RET: Set<SQLDialect> = new Set(["postgresql", "sqlite"]);
/**
* Creates and returns a database interface using the specified connector.
* This interface allows you to execute raw SQL queries, prepare SQL statements,
* and execute SQL queries with parameters using tagged template literals.
*
* @param {Connector} connector - The database connector used to execute and prepare SQL statements. See {@link Connector}.
* @returns {Database} The database interface that allows SQL operations. See {@link Database}.
*/
export function createDatabase<TConnector extends Connector = Connector>(
connector: TConnector,
): Database<TConnector> {
return <Database<TConnector>>{
get dialect() {
return connector.dialect;
},
getInstance() {
return connector.getInstance();
},
exec: (sql: string) => {
return Promise.resolve(connector.exec(sql));
},
prepare: (sql: string) => {
return connector.prepare(sql);
},
sql: async (strings, ...values) => {
const [sql, params] = sqlTemplate(strings, ...values);
if (
SQL_SELECT_RE.test(sql) /* select */ ||
// prettier-ignore
(DIALECTS_WITH_RET.has(connector.dialect) && SQL_RETURNING_RE.test(sql)) /* returning */
) {
const rows = await connector.prepare(sql).all(...params);
return {
rows,
success: true,
};
} else {
const res = await connector.prepare(sql).run(...params);
return res;
}
},
};
}