@kiln-js/db 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/dist/index.d.ts +136 -0
- package/dist/index.js +275 -0
- package/package.json +24 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zxsty
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kiln-js/db
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@kiln-js/db)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
Part of the Kiln framework.
|
|
7
|
+
|
|
8
|
+
Part of [Kiln](https://github.com/kiln-js/kiln), a file-based server-side rendering framework for React and Vite.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
bun add @kiln-js/db
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { v } from "@kiln-js/core";
|
|
20
|
+
import { createDatabaseClient, defineModel, MemoryDatabaseAdapter } from "@kiln-js/db";
|
|
21
|
+
|
|
22
|
+
const User = defineModel("users", {
|
|
23
|
+
email: v.string(),
|
|
24
|
+
name: v.string(),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const db = createDatabaseClient(new MemoryDatabaseAdapter(), {
|
|
28
|
+
slowQueryThresholdMs: 200,
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Adapters
|
|
33
|
+
|
|
34
|
+
`MemoryDatabaseAdapter` is meant for tests and prototypes. Use `createSqlAdapter` with a `SqlExecutor` to connect PostgreSQL, SQLite, or MySQL.
|
|
35
|
+
The client records query telemetry, flags slow queries, and exposes health checks.
|
|
36
|
+
|
|
37
|
+
## Documentation
|
|
38
|
+
|
|
39
|
+
See the [Kiln repository](https://github.com/kiln-js/kiln) for the full API reference and guides.
|
|
40
|
+
|
|
41
|
+
## Development
|
|
42
|
+
|
|
43
|
+
This repository is generated from the Kiln monorepo. Make changes there, then run `scripts/publish-repo.ps1` to publish them here. Report issues in this repository, and send pull requests to the monorepo.
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { Schema, Infer } from "@kiln-js/core";
|
|
2
|
+
export type Dialect = "postgresql" | "sqlite" | "mysql" | "memory";
|
|
3
|
+
export interface QueryResult<TRow = Record<string, unknown>> {
|
|
4
|
+
rows: TRow[];
|
|
5
|
+
rowCount: number;
|
|
6
|
+
durationMs: number;
|
|
7
|
+
sql: string;
|
|
8
|
+
}
|
|
9
|
+
export interface QueryTelemetryEvent {
|
|
10
|
+
sql: string;
|
|
11
|
+
params: unknown[];
|
|
12
|
+
durationMs: number;
|
|
13
|
+
rowCount: number;
|
|
14
|
+
slow: boolean;
|
|
15
|
+
timestamp: number;
|
|
16
|
+
dialect: Dialect;
|
|
17
|
+
}
|
|
18
|
+
export interface HealthCheckResult {
|
|
19
|
+
ok: boolean;
|
|
20
|
+
dialect: Dialect;
|
|
21
|
+
latencyMs: number;
|
|
22
|
+
version?: string;
|
|
23
|
+
error?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface TransactionClient {
|
|
26
|
+
query<TRow = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<QueryResult<TRow>>;
|
|
27
|
+
execute(sql: string, params?: unknown[]): Promise<{
|
|
28
|
+
rowCount: number;
|
|
29
|
+
durationMs: number;
|
|
30
|
+
}>;
|
|
31
|
+
}
|
|
32
|
+
export interface DatabaseAdapter extends TransactionClient {
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly dialect: Dialect;
|
|
35
|
+
transaction<T>(fn: (tx: TransactionClient) => Promise<T>): Promise<T>;
|
|
36
|
+
healthCheck(): Promise<HealthCheckResult>;
|
|
37
|
+
close?(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
export interface MigrationRecord {
|
|
40
|
+
id: string;
|
|
41
|
+
name: string;
|
|
42
|
+
up(tx: TransactionClient): Promise<void>;
|
|
43
|
+
down?(tx: TransactionClient): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
export interface MigrationContract {
|
|
46
|
+
applied(): Promise<string[]>;
|
|
47
|
+
up(migrations: MigrationRecord[]): Promise<string[]>;
|
|
48
|
+
down(migration: MigrationRecord): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
export interface ModelDefinition<TName extends string, TSchema extends Schema> {
|
|
51
|
+
readonly tableName: TName;
|
|
52
|
+
readonly schema: TSchema;
|
|
53
|
+
readonly primaryKey: string;
|
|
54
|
+
}
|
|
55
|
+
export type InferModel<M> = M extends ModelDefinition<string, infer S> ? {
|
|
56
|
+
id: string;
|
|
57
|
+
} & {
|
|
58
|
+
[K in keyof S]: Infer<S[K]>;
|
|
59
|
+
} : never;
|
|
60
|
+
export declare function defineModel<TName extends string, TSchema extends Schema>(tableName: TName, schema: TSchema, primaryKey?: string): ModelDefinition<TName, TSchema>;
|
|
61
|
+
export interface RepositoryContract<TEntity extends {
|
|
62
|
+
id: string;
|
|
63
|
+
}, TCreateInput = Omit<TEntity, "id">> {
|
|
64
|
+
readonly tableName: string;
|
|
65
|
+
findById(id: string): Promise<TEntity | null>;
|
|
66
|
+
findMany(filter?: Partial<TEntity>): Promise<TEntity[]>;
|
|
67
|
+
create(input: TCreateInput & {
|
|
68
|
+
id?: string;
|
|
69
|
+
}): Promise<TEntity>;
|
|
70
|
+
update(id: string, patch: Partial<TCreateInput>): Promise<TEntity | null>;
|
|
71
|
+
delete(id: string): Promise<boolean>;
|
|
72
|
+
count(filter?: Partial<TEntity>): Promise<number>;
|
|
73
|
+
}
|
|
74
|
+
export interface DatabaseClientOptions {
|
|
75
|
+
slowQueryThresholdMs?: number;
|
|
76
|
+
maxTelemetryHistory?: number;
|
|
77
|
+
onQuery?: (event: QueryTelemetryEvent) => void;
|
|
78
|
+
onError?: (error: unknown, sql: string) => void;
|
|
79
|
+
}
|
|
80
|
+
export declare class KilnDatabaseClient implements DatabaseAdapter {
|
|
81
|
+
readonly name: string;
|
|
82
|
+
readonly dialect: Dialect;
|
|
83
|
+
private adapter;
|
|
84
|
+
private slowThresholdMs;
|
|
85
|
+
private maxHistory;
|
|
86
|
+
private onQuery?;
|
|
87
|
+
private onError?;
|
|
88
|
+
private telemetryHistory;
|
|
89
|
+
constructor(adapter: DatabaseAdapter, options?: DatabaseClientOptions);
|
|
90
|
+
query<TRow = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<QueryResult<TRow>>;
|
|
91
|
+
execute(sql: string, params?: unknown[]): Promise<{
|
|
92
|
+
rowCount: number;
|
|
93
|
+
durationMs: number;
|
|
94
|
+
}>;
|
|
95
|
+
transaction<T>(fn: (tx: TransactionClient) => Promise<T>): Promise<T>;
|
|
96
|
+
healthCheck(): Promise<HealthCheckResult>;
|
|
97
|
+
getTelemetry(): QueryTelemetryEvent[];
|
|
98
|
+
clearTelemetry(): void;
|
|
99
|
+
repository<TName extends string, TSchema extends Schema>(model: ModelDefinition<TName, TSchema>): RepositoryContract<InferModel<ModelDefinition<TName, TSchema>>, {
|
|
100
|
+
[K in keyof TSchema]: Infer<TSchema[K]>;
|
|
101
|
+
}>;
|
|
102
|
+
private recordTelemetry;
|
|
103
|
+
}
|
|
104
|
+
export declare function createDatabaseClient(adapter: DatabaseAdapter, options?: DatabaseClientOptions): KilnDatabaseClient;
|
|
105
|
+
/**
|
|
106
|
+
* In-memory DatabaseAdapter implementing full CRUD repositories, SQL query inspection,
|
|
107
|
+
* and atomic transactions with rollback snapshots.
|
|
108
|
+
*/
|
|
109
|
+
export declare class MemoryDatabaseAdapter implements DatabaseAdapter {
|
|
110
|
+
readonly name = "memory-db";
|
|
111
|
+
readonly dialect: Dialect;
|
|
112
|
+
private tables;
|
|
113
|
+
private getTable;
|
|
114
|
+
query<TRow = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<QueryResult<TRow>>;
|
|
115
|
+
execute(sql: string, params?: unknown[]): Promise<{
|
|
116
|
+
rowCount: number;
|
|
117
|
+
durationMs: number;
|
|
118
|
+
}>;
|
|
119
|
+
transaction<T>(fn: (tx: TransactionClient) => Promise<T>): Promise<T>;
|
|
120
|
+
healthCheck(): Promise<HealthCheckResult>;
|
|
121
|
+
createRepository<TName extends string, TSchema extends Schema>(model: ModelDefinition<TName, TSchema>): RepositoryContract<InferModel<ModelDefinition<TName, TSchema>>, {
|
|
122
|
+
[K in keyof TSchema]: Infer<TSchema[K]>;
|
|
123
|
+
}>;
|
|
124
|
+
}
|
|
125
|
+
export interface SqlExecutor {
|
|
126
|
+
dialect?: Dialect;
|
|
127
|
+
name?: string;
|
|
128
|
+
query<TRow = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<{
|
|
129
|
+
rows: TRow[];
|
|
130
|
+
rowCount?: number | null;
|
|
131
|
+
}>;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Wraps a Node-Postgres Pool, Drizzle SQL executor, or any SQL driver into a Kiln DatabaseAdapter.
|
|
135
|
+
*/
|
|
136
|
+
export declare function createSqlAdapter(executor: SqlExecutor): DatabaseAdapter;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// packages/db/src/index.ts
|
|
2
|
+
import { validate } from "@kiln-js/core";
|
|
3
|
+
function defineModel(tableName, schema, primaryKey = "id") {
|
|
4
|
+
return {
|
|
5
|
+
tableName,
|
|
6
|
+
schema,
|
|
7
|
+
primaryKey
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
var KilnDatabaseClient = class {
|
|
11
|
+
name;
|
|
12
|
+
dialect;
|
|
13
|
+
adapter;
|
|
14
|
+
slowThresholdMs;
|
|
15
|
+
maxHistory;
|
|
16
|
+
onQuery;
|
|
17
|
+
onError;
|
|
18
|
+
telemetryHistory = [];
|
|
19
|
+
constructor(adapter, options = {}) {
|
|
20
|
+
this.adapter = adapter;
|
|
21
|
+
this.name = adapter.name;
|
|
22
|
+
this.dialect = adapter.dialect;
|
|
23
|
+
this.slowThresholdMs = options.slowQueryThresholdMs ?? 100;
|
|
24
|
+
this.maxHistory = options.maxTelemetryHistory ?? 100;
|
|
25
|
+
this.onQuery = options.onQuery;
|
|
26
|
+
this.onError = options.onError;
|
|
27
|
+
}
|
|
28
|
+
async query(sql, params = []) {
|
|
29
|
+
const start = performance.now();
|
|
30
|
+
try {
|
|
31
|
+
const result = await this.adapter.query(sql, params);
|
|
32
|
+
const durationMs = Math.round((performance.now() - start) * 100) / 100;
|
|
33
|
+
const event = {
|
|
34
|
+
sql,
|
|
35
|
+
params,
|
|
36
|
+
durationMs,
|
|
37
|
+
rowCount: result.rowCount,
|
|
38
|
+
slow: durationMs >= this.slowThresholdMs,
|
|
39
|
+
timestamp: Date.now(),
|
|
40
|
+
dialect: this.dialect
|
|
41
|
+
};
|
|
42
|
+
this.recordTelemetry(event);
|
|
43
|
+
return { ...result, durationMs };
|
|
44
|
+
} catch (err) {
|
|
45
|
+
this.onError?.(err, sql);
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async execute(sql, params = []) {
|
|
50
|
+
const res = await this.query(sql, params);
|
|
51
|
+
return { rowCount: res.rowCount, durationMs: res.durationMs };
|
|
52
|
+
}
|
|
53
|
+
async transaction(fn) {
|
|
54
|
+
return this.adapter.transaction(async (rawTx) => {
|
|
55
|
+
const instrumentedTx = {
|
|
56
|
+
query: async (sql, params = []) => {
|
|
57
|
+
const start = performance.now();
|
|
58
|
+
const res = await rawTx.query(sql, params);
|
|
59
|
+
const durationMs = Math.round((performance.now() - start) * 100) / 100;
|
|
60
|
+
this.recordTelemetry({
|
|
61
|
+
sql,
|
|
62
|
+
params,
|
|
63
|
+
durationMs,
|
|
64
|
+
rowCount: res.rowCount,
|
|
65
|
+
slow: durationMs >= this.slowThresholdMs,
|
|
66
|
+
timestamp: Date.now(),
|
|
67
|
+
dialect: this.dialect
|
|
68
|
+
});
|
|
69
|
+
return { ...res, durationMs };
|
|
70
|
+
},
|
|
71
|
+
execute: async (sql, params = []) => {
|
|
72
|
+
const res = await rawTx.execute(sql, params);
|
|
73
|
+
return res;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
return fn(instrumentedTx);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
async healthCheck() {
|
|
80
|
+
return this.adapter.healthCheck();
|
|
81
|
+
}
|
|
82
|
+
getTelemetry() {
|
|
83
|
+
return [...this.telemetryHistory];
|
|
84
|
+
}
|
|
85
|
+
clearTelemetry() {
|
|
86
|
+
this.telemetryHistory = [];
|
|
87
|
+
}
|
|
88
|
+
repository(model) {
|
|
89
|
+
if (this.adapter instanceof MemoryDatabaseAdapter) {
|
|
90
|
+
return this.adapter.createRepository(model);
|
|
91
|
+
}
|
|
92
|
+
throw new Error(`Use MemoryDatabaseAdapter or custom SQL repository for model "${model.tableName}"`);
|
|
93
|
+
}
|
|
94
|
+
recordTelemetry(event) {
|
|
95
|
+
this.telemetryHistory.unshift(event);
|
|
96
|
+
if (this.telemetryHistory.length > this.maxHistory) {
|
|
97
|
+
this.telemetryHistory.pop();
|
|
98
|
+
}
|
|
99
|
+
this.onQuery?.(event);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
function createDatabaseClient(adapter, options) {
|
|
103
|
+
return new KilnDatabaseClient(adapter, options);
|
|
104
|
+
}
|
|
105
|
+
var MemoryDatabaseAdapter = class {
|
|
106
|
+
name = "memory-db";
|
|
107
|
+
dialect = "memory";
|
|
108
|
+
tables = /* @__PURE__ */ new Map();
|
|
109
|
+
getTable(tableName) {
|
|
110
|
+
let table = this.tables.get(tableName);
|
|
111
|
+
if (!table) {
|
|
112
|
+
table = /* @__PURE__ */ new Map();
|
|
113
|
+
this.tables.set(tableName, table);
|
|
114
|
+
}
|
|
115
|
+
return table;
|
|
116
|
+
}
|
|
117
|
+
async query(sql, params = []) {
|
|
118
|
+
const start = performance.now();
|
|
119
|
+
const trimmed = sql.trim();
|
|
120
|
+
if (/^SELECT\s+1/i.test(trimmed)) {
|
|
121
|
+
return {
|
|
122
|
+
rows: [{ "?column?": 1 }],
|
|
123
|
+
rowCount: 1,
|
|
124
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100,
|
|
125
|
+
sql
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
const selectMatch = trimmed.match(/^SELECT\s+\*\s+FROM\s+([a-zA-Z0-9_]+)/i);
|
|
129
|
+
if (selectMatch) {
|
|
130
|
+
const tableName = selectMatch[1];
|
|
131
|
+
const rows = Array.from(this.getTable(tableName).values());
|
|
132
|
+
return {
|
|
133
|
+
rows,
|
|
134
|
+
rowCount: rows.length,
|
|
135
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100,
|
|
136
|
+
sql
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
void params;
|
|
140
|
+
return {
|
|
141
|
+
rows: [],
|
|
142
|
+
rowCount: 0,
|
|
143
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100,
|
|
144
|
+
sql
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
async execute(sql, params = []) {
|
|
148
|
+
const res = await this.query(sql, params);
|
|
149
|
+
return { rowCount: res.rowCount, durationMs: res.durationMs };
|
|
150
|
+
}
|
|
151
|
+
async transaction(fn) {
|
|
152
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
153
|
+
for (const [tName, rows] of this.tables.entries()) {
|
|
154
|
+
const copy = /* @__PURE__ */ new Map();
|
|
155
|
+
for (const [id, row] of rows.entries()) {
|
|
156
|
+
copy.set(id, { ...row });
|
|
157
|
+
}
|
|
158
|
+
snapshot.set(tName, copy);
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
return await fn(this);
|
|
162
|
+
} catch (err) {
|
|
163
|
+
this.tables = snapshot;
|
|
164
|
+
throw err;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async healthCheck() {
|
|
168
|
+
const start = performance.now();
|
|
169
|
+
await this.query("SELECT 1");
|
|
170
|
+
return {
|
|
171
|
+
ok: true,
|
|
172
|
+
dialect: "memory",
|
|
173
|
+
latencyMs: Math.round((performance.now() - start) * 100) / 100,
|
|
174
|
+
version: "Kiln MemoryDB 0.3.0"
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
createRepository(model) {
|
|
178
|
+
const getStore = () => this.getTable(model.tableName);
|
|
179
|
+
return {
|
|
180
|
+
tableName: model.tableName,
|
|
181
|
+
async findById(id) {
|
|
182
|
+
const found = getStore().get(id);
|
|
183
|
+
return found ? { ...found } : null;
|
|
184
|
+
},
|
|
185
|
+
async findMany(filter) {
|
|
186
|
+
const all = Array.from(getStore().values());
|
|
187
|
+
if (!filter || Object.keys(filter).length === 0) return all;
|
|
188
|
+
return all.filter(
|
|
189
|
+
(item) => Object.entries(filter).every(([k, v]) => v === void 0 || item[k] === v)
|
|
190
|
+
);
|
|
191
|
+
},
|
|
192
|
+
async create(input) {
|
|
193
|
+
const validated = validate(model.schema, input);
|
|
194
|
+
if (!validated.ok) {
|
|
195
|
+
const messages = Object.entries(validated.errors).map(([field, msg]) => `${field}: ${msg}`).join("; ");
|
|
196
|
+
throw new Error(`Model validation failed on "${model.tableName}": ${messages}`);
|
|
197
|
+
}
|
|
198
|
+
const id = input.id ?? crypto.randomUUID();
|
|
199
|
+
const entity = { id, ...validated.data };
|
|
200
|
+
getStore().set(id, entity);
|
|
201
|
+
return entity;
|
|
202
|
+
},
|
|
203
|
+
async update(id, patch) {
|
|
204
|
+
const current = getStore().get(id);
|
|
205
|
+
if (!current) return null;
|
|
206
|
+
const merged = { ...current, ...patch, id };
|
|
207
|
+
const validated = validate(model.schema, merged);
|
|
208
|
+
if (!validated.ok) {
|
|
209
|
+
const messages = Object.entries(validated.errors).map(([field, msg]) => `${field}: ${msg}`).join("; ");
|
|
210
|
+
throw new Error(`Model validation failed on "${model.tableName}": ${messages}`);
|
|
211
|
+
}
|
|
212
|
+
const updated = { id, ...validated.data };
|
|
213
|
+
getStore().set(id, updated);
|
|
214
|
+
return updated;
|
|
215
|
+
},
|
|
216
|
+
async delete(id) {
|
|
217
|
+
return getStore().delete(id);
|
|
218
|
+
},
|
|
219
|
+
async count(filter) {
|
|
220
|
+
const items = await this.findMany(filter);
|
|
221
|
+
return items.length;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
function createSqlAdapter(executor) {
|
|
227
|
+
const dialect = executor.dialect ?? "postgresql";
|
|
228
|
+
const name = executor.name ?? `${dialect}-adapter`;
|
|
229
|
+
return {
|
|
230
|
+
name,
|
|
231
|
+
dialect,
|
|
232
|
+
async query(sql, params = []) {
|
|
233
|
+
const start = performance.now();
|
|
234
|
+
const res = await executor.query(sql, params);
|
|
235
|
+
return {
|
|
236
|
+
rows: res.rows ?? [],
|
|
237
|
+
rowCount: res.rowCount ?? res.rows?.length ?? 0,
|
|
238
|
+
durationMs: Math.round((performance.now() - start) * 100) / 100,
|
|
239
|
+
sql
|
|
240
|
+
};
|
|
241
|
+
},
|
|
242
|
+
async execute(sql, params = []) {
|
|
243
|
+
const res = await this.query(sql, params);
|
|
244
|
+
return { rowCount: res.rowCount, durationMs: res.durationMs };
|
|
245
|
+
},
|
|
246
|
+
async transaction(fn) {
|
|
247
|
+
return fn(this);
|
|
248
|
+
},
|
|
249
|
+
async healthCheck() {
|
|
250
|
+
const start = performance.now();
|
|
251
|
+
try {
|
|
252
|
+
await executor.query("SELECT 1");
|
|
253
|
+
return {
|
|
254
|
+
ok: true,
|
|
255
|
+
dialect,
|
|
256
|
+
latencyMs: Math.round((performance.now() - start) * 100) / 100
|
|
257
|
+
};
|
|
258
|
+
} catch (err) {
|
|
259
|
+
return {
|
|
260
|
+
ok: false,
|
|
261
|
+
dialect,
|
|
262
|
+
latencyMs: Math.round((performance.now() - start) * 100) / 100,
|
|
263
|
+
error: err instanceof Error ? err.message : String(err)
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
export {
|
|
270
|
+
KilnDatabaseClient,
|
|
271
|
+
MemoryDatabaseAdapter,
|
|
272
|
+
createDatabaseClient,
|
|
273
|
+
createSqlAdapter,
|
|
274
|
+
defineModel
|
|
275
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
|
-
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@kiln-js/db",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist"
|
|
7
|
+
],
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "bun build ./src/index.ts --outdir ./dist --target bun \u0026\u0026 tsc -p tsconfig.json --emitDeclarationOnly",
|
|
16
|
+
"test": "bun test",
|
|
17
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
18
|
+
},
|
|
19
|
+
"repository": "github:kiln-js/db",
|
|
20
|
+
"homepage": "https://kiln-js.vercel.app",
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@kiln-js/core": "^0.3.0"
|
|
23
|
+
}
|
|
24
|
+
}
|