@hasna/brains 0.0.6 → 0.0.8
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/README.md +190 -0
- package/dist/cli/index.js +1172 -809
- package/dist/db/index.d.ts.map +1 -1
- package/dist/index.js +4294 -142
- package/dist/lib/config.d.ts +11 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/gatherers/assistants.d.ts +3 -0
- package/dist/lib/gatherers/assistants.d.ts.map +1 -0
- package/dist/lib/gatherers/economy.d.ts +3 -0
- package/dist/lib/gatherers/economy.d.ts.map +1 -0
- package/dist/lib/gatherers/index.d.ts +3 -0
- package/dist/lib/gatherers/index.d.ts.map +1 -1
- package/dist/lib/gatherers/protocol.d.ts +29 -0
- package/dist/lib/gatherers/protocol.d.ts.map +1 -0
- package/dist/lib/gatherers/recordings.d.ts +3 -0
- package/dist/lib/gatherers/recordings.d.ts.map +1 -0
- package/dist/lib/gatherers/registry.d.ts +7 -0
- package/dist/lib/gatherers/registry.d.ts.map +1 -0
- package/dist/lib/gatherers/researcher.d.ts +3 -0
- package/dist/lib/gatherers/researcher.d.ts.map +1 -0
- package/dist/lib/gatherers/styles.d.ts +3 -0
- package/dist/lib/gatherers/styles.d.ts.map +1 -0
- package/dist/lib/gatherers/tickets.d.ts +3 -0
- package/dist/lib/gatherers/tickets.d.ts.map +1 -0
- package/dist/lib/index.d.ts +3 -0
- package/dist/lib/index.d.ts.map +1 -1
- package/dist/lib/providers/openai.d.ts +2 -0
- package/dist/lib/providers/openai.d.ts.map +1 -1
- package/dist/lib/providers/thinker-labs.d.ts +1 -0
- package/dist/lib/providers/thinker-labs.d.ts.map +1 -1
- package/dist/lib/retry.d.ts +7 -0
- package/dist/lib/retry.d.ts.map +1 -0
- package/dist/lib/schemas.d.ts +87 -0
- package/dist/lib/schemas.d.ts.map +1 -0
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +4585 -196
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +4638 -9
- package/drizzle/0000_foamy_daimon_hellstrom.sql +36 -0
- package/drizzle/meta/0000_snapshot.json +259 -0
- package/drizzle/meta/_journal.json +13 -0
- package/package.json +6 -2
package/dist/server/index.js
CHANGED
|
@@ -1,16 +1,4645 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
9
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
10
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
11
|
+
for (let key of __getOwnPropNames(mod))
|
|
12
|
+
if (!__hasOwnProp.call(to, key))
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: () => mod[key],
|
|
15
|
+
enumerable: true
|
|
16
|
+
});
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __export = (target, all) => {
|
|
20
|
+
for (var name in all)
|
|
21
|
+
__defProp(target, name, {
|
|
22
|
+
get: all[name],
|
|
23
|
+
enumerable: true,
|
|
24
|
+
configurable: true,
|
|
25
|
+
set: (newValue) => all[name] = () => newValue
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
var __require = import.meta.require;
|
|
29
|
+
|
|
30
|
+
// node_modules/drizzle-orm/entity.js
|
|
31
|
+
var entityKind = Symbol.for("drizzle:entityKind");
|
|
32
|
+
var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
|
|
33
|
+
function is(value, type) {
|
|
34
|
+
if (!value || typeof value !== "object") {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (value instanceof type) {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
|
|
41
|
+
throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
|
|
42
|
+
}
|
|
43
|
+
let cls = Object.getPrototypeOf(value).constructor;
|
|
44
|
+
if (cls) {
|
|
45
|
+
while (cls) {
|
|
46
|
+
if (entityKind in cls && cls[entityKind] === type[entityKind]) {
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
cls = Object.getPrototypeOf(cls);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// node_modules/drizzle-orm/column.js
|
|
56
|
+
class Column {
|
|
57
|
+
constructor(table, config) {
|
|
58
|
+
this.table = table;
|
|
59
|
+
this.config = config;
|
|
60
|
+
this.name = config.name;
|
|
61
|
+
this.keyAsName = config.keyAsName;
|
|
62
|
+
this.notNull = config.notNull;
|
|
63
|
+
this.default = config.default;
|
|
64
|
+
this.defaultFn = config.defaultFn;
|
|
65
|
+
this.onUpdateFn = config.onUpdateFn;
|
|
66
|
+
this.hasDefault = config.hasDefault;
|
|
67
|
+
this.primary = config.primaryKey;
|
|
68
|
+
this.isUnique = config.isUnique;
|
|
69
|
+
this.uniqueName = config.uniqueName;
|
|
70
|
+
this.uniqueType = config.uniqueType;
|
|
71
|
+
this.dataType = config.dataType;
|
|
72
|
+
this.columnType = config.columnType;
|
|
73
|
+
this.generated = config.generated;
|
|
74
|
+
this.generatedIdentity = config.generatedIdentity;
|
|
75
|
+
}
|
|
76
|
+
static [entityKind] = "Column";
|
|
77
|
+
name;
|
|
78
|
+
keyAsName;
|
|
79
|
+
primary;
|
|
80
|
+
notNull;
|
|
81
|
+
default;
|
|
82
|
+
defaultFn;
|
|
83
|
+
onUpdateFn;
|
|
84
|
+
hasDefault;
|
|
85
|
+
isUnique;
|
|
86
|
+
uniqueName;
|
|
87
|
+
uniqueType;
|
|
88
|
+
dataType;
|
|
89
|
+
columnType;
|
|
90
|
+
enumValues = undefined;
|
|
91
|
+
generated = undefined;
|
|
92
|
+
generatedIdentity = undefined;
|
|
93
|
+
config;
|
|
94
|
+
mapFromDriverValue(value) {
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
mapToDriverValue(value) {
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
shouldDisableInsert() {
|
|
101
|
+
return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// node_modules/drizzle-orm/column-builder.js
|
|
106
|
+
class ColumnBuilder {
|
|
107
|
+
static [entityKind] = "ColumnBuilder";
|
|
108
|
+
config;
|
|
109
|
+
constructor(name, dataType, columnType) {
|
|
110
|
+
this.config = {
|
|
111
|
+
name,
|
|
112
|
+
keyAsName: name === "",
|
|
113
|
+
notNull: false,
|
|
114
|
+
default: undefined,
|
|
115
|
+
hasDefault: false,
|
|
116
|
+
primaryKey: false,
|
|
117
|
+
isUnique: false,
|
|
118
|
+
uniqueName: undefined,
|
|
119
|
+
uniqueType: undefined,
|
|
120
|
+
dataType,
|
|
121
|
+
columnType,
|
|
122
|
+
generated: undefined
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
$type() {
|
|
126
|
+
return this;
|
|
127
|
+
}
|
|
128
|
+
notNull() {
|
|
129
|
+
this.config.notNull = true;
|
|
130
|
+
return this;
|
|
131
|
+
}
|
|
132
|
+
default(value) {
|
|
133
|
+
this.config.default = value;
|
|
134
|
+
this.config.hasDefault = true;
|
|
135
|
+
return this;
|
|
136
|
+
}
|
|
137
|
+
$defaultFn(fn) {
|
|
138
|
+
this.config.defaultFn = fn;
|
|
139
|
+
this.config.hasDefault = true;
|
|
140
|
+
return this;
|
|
141
|
+
}
|
|
142
|
+
$default = this.$defaultFn;
|
|
143
|
+
$onUpdateFn(fn) {
|
|
144
|
+
this.config.onUpdateFn = fn;
|
|
145
|
+
this.config.hasDefault = true;
|
|
146
|
+
return this;
|
|
147
|
+
}
|
|
148
|
+
$onUpdate = this.$onUpdateFn;
|
|
149
|
+
primaryKey() {
|
|
150
|
+
this.config.primaryKey = true;
|
|
151
|
+
this.config.notNull = true;
|
|
152
|
+
return this;
|
|
153
|
+
}
|
|
154
|
+
setName(name) {
|
|
155
|
+
if (this.config.name !== "")
|
|
156
|
+
return;
|
|
157
|
+
this.config.name = name;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// node_modules/drizzle-orm/table.utils.js
|
|
162
|
+
var TableName = Symbol.for("drizzle:Name");
|
|
163
|
+
|
|
164
|
+
// node_modules/drizzle-orm/tracing-utils.js
|
|
165
|
+
function iife(fn, ...args) {
|
|
166
|
+
return fn(...args);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// node_modules/drizzle-orm/pg-core/unique-constraint.js
|
|
170
|
+
function uniqueKeyName(table, columns) {
|
|
171
|
+
return `${table[TableName]}_${columns.join("_")}_unique`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// node_modules/drizzle-orm/pg-core/columns/common.js
|
|
175
|
+
class PgColumn extends Column {
|
|
176
|
+
constructor(table, config) {
|
|
177
|
+
if (!config.uniqueName) {
|
|
178
|
+
config.uniqueName = uniqueKeyName(table, [config.name]);
|
|
179
|
+
}
|
|
180
|
+
super(table, config);
|
|
181
|
+
this.table = table;
|
|
182
|
+
}
|
|
183
|
+
static [entityKind] = "PgColumn";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
class ExtraConfigColumn extends PgColumn {
|
|
187
|
+
static [entityKind] = "ExtraConfigColumn";
|
|
188
|
+
getSQLType() {
|
|
189
|
+
return this.getSQLType();
|
|
190
|
+
}
|
|
191
|
+
indexConfig = {
|
|
192
|
+
order: this.config.order ?? "asc",
|
|
193
|
+
nulls: this.config.nulls ?? "last",
|
|
194
|
+
opClass: this.config.opClass
|
|
195
|
+
};
|
|
196
|
+
defaultConfig = {
|
|
197
|
+
order: "asc",
|
|
198
|
+
nulls: "last",
|
|
199
|
+
opClass: undefined
|
|
200
|
+
};
|
|
201
|
+
asc() {
|
|
202
|
+
this.indexConfig.order = "asc";
|
|
203
|
+
return this;
|
|
204
|
+
}
|
|
205
|
+
desc() {
|
|
206
|
+
this.indexConfig.order = "desc";
|
|
207
|
+
return this;
|
|
208
|
+
}
|
|
209
|
+
nullsFirst() {
|
|
210
|
+
this.indexConfig.nulls = "first";
|
|
211
|
+
return this;
|
|
212
|
+
}
|
|
213
|
+
nullsLast() {
|
|
214
|
+
this.indexConfig.nulls = "last";
|
|
215
|
+
return this;
|
|
216
|
+
}
|
|
217
|
+
op(opClass) {
|
|
218
|
+
this.indexConfig.opClass = opClass;
|
|
219
|
+
return this;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// node_modules/drizzle-orm/pg-core/columns/enum.js
|
|
224
|
+
var isPgEnumSym = Symbol.for("drizzle:isPgEnum");
|
|
225
|
+
function isPgEnum(obj) {
|
|
226
|
+
return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
|
|
227
|
+
}
|
|
228
|
+
class PgEnumColumn extends PgColumn {
|
|
229
|
+
static [entityKind] = "PgEnumColumn";
|
|
230
|
+
enum = this.config.enum;
|
|
231
|
+
enumValues = this.config.enum.enumValues;
|
|
232
|
+
constructor(table, config) {
|
|
233
|
+
super(table, config);
|
|
234
|
+
this.enum = config.enum;
|
|
235
|
+
}
|
|
236
|
+
getSQLType() {
|
|
237
|
+
return this.enum.enumName;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// node_modules/drizzle-orm/subquery.js
|
|
242
|
+
class Subquery {
|
|
243
|
+
static [entityKind] = "Subquery";
|
|
244
|
+
constructor(sql, selection, alias, isWith = false) {
|
|
245
|
+
this._ = {
|
|
246
|
+
brand: "Subquery",
|
|
247
|
+
sql,
|
|
248
|
+
selectedFields: selection,
|
|
249
|
+
alias,
|
|
250
|
+
isWith
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
class WithSubquery extends Subquery {
|
|
256
|
+
static [entityKind] = "WithSubquery";
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// node_modules/drizzle-orm/version.js
|
|
260
|
+
var version = "0.40.1";
|
|
261
|
+
|
|
262
|
+
// node_modules/drizzle-orm/tracing.js
|
|
263
|
+
var otel;
|
|
264
|
+
var rawTracer;
|
|
265
|
+
var tracer = {
|
|
266
|
+
startActiveSpan(name, fn) {
|
|
267
|
+
if (!otel) {
|
|
268
|
+
return fn();
|
|
269
|
+
}
|
|
270
|
+
if (!rawTracer) {
|
|
271
|
+
rawTracer = otel.trace.getTracer("drizzle-orm", version);
|
|
272
|
+
}
|
|
273
|
+
return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
|
|
274
|
+
try {
|
|
275
|
+
return fn(span);
|
|
276
|
+
} catch (e) {
|
|
277
|
+
span.setStatus({
|
|
278
|
+
code: otel2.SpanStatusCode.ERROR,
|
|
279
|
+
message: e instanceof Error ? e.message : "Unknown error"
|
|
280
|
+
});
|
|
281
|
+
throw e;
|
|
282
|
+
} finally {
|
|
283
|
+
span.end();
|
|
284
|
+
}
|
|
285
|
+
}), otel, rawTracer);
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// node_modules/drizzle-orm/view-common.js
|
|
290
|
+
var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
|
|
291
|
+
|
|
292
|
+
// node_modules/drizzle-orm/table.js
|
|
293
|
+
var Schema = Symbol.for("drizzle:Schema");
|
|
294
|
+
var Columns = Symbol.for("drizzle:Columns");
|
|
295
|
+
var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
|
|
296
|
+
var OriginalName = Symbol.for("drizzle:OriginalName");
|
|
297
|
+
var BaseName = Symbol.for("drizzle:BaseName");
|
|
298
|
+
var IsAlias = Symbol.for("drizzle:IsAlias");
|
|
299
|
+
var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
|
|
300
|
+
var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
|
|
301
|
+
|
|
302
|
+
class Table {
|
|
303
|
+
static [entityKind] = "Table";
|
|
304
|
+
static Symbol = {
|
|
305
|
+
Name: TableName,
|
|
306
|
+
Schema,
|
|
307
|
+
OriginalName,
|
|
308
|
+
Columns,
|
|
309
|
+
ExtraConfigColumns,
|
|
310
|
+
BaseName,
|
|
311
|
+
IsAlias,
|
|
312
|
+
ExtraConfigBuilder
|
|
313
|
+
};
|
|
314
|
+
[TableName];
|
|
315
|
+
[OriginalName];
|
|
316
|
+
[Schema];
|
|
317
|
+
[Columns];
|
|
318
|
+
[ExtraConfigColumns];
|
|
319
|
+
[BaseName];
|
|
320
|
+
[IsAlias] = false;
|
|
321
|
+
[IsDrizzleTable] = true;
|
|
322
|
+
[ExtraConfigBuilder] = undefined;
|
|
323
|
+
constructor(name, schema, baseName) {
|
|
324
|
+
this[TableName] = this[OriginalName] = name;
|
|
325
|
+
this[Schema] = schema;
|
|
326
|
+
this[BaseName] = baseName;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function getTableName(table) {
|
|
330
|
+
return table[TableName];
|
|
331
|
+
}
|
|
332
|
+
function getTableUniqueName(table) {
|
|
333
|
+
return `${table[Schema] ?? "public"}.${table[TableName]}`;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// node_modules/drizzle-orm/sql/sql.js
|
|
337
|
+
function isSQLWrapper(value) {
|
|
338
|
+
return value !== null && value !== undefined && typeof value.getSQL === "function";
|
|
339
|
+
}
|
|
340
|
+
function mergeQueries(queries) {
|
|
341
|
+
const result = { sql: "", params: [] };
|
|
342
|
+
for (const query of queries) {
|
|
343
|
+
result.sql += query.sql;
|
|
344
|
+
result.params.push(...query.params);
|
|
345
|
+
if (query.typings?.length) {
|
|
346
|
+
if (!result.typings) {
|
|
347
|
+
result.typings = [];
|
|
348
|
+
}
|
|
349
|
+
result.typings.push(...query.typings);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return result;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
class StringChunk {
|
|
356
|
+
static [entityKind] = "StringChunk";
|
|
357
|
+
value;
|
|
358
|
+
constructor(value) {
|
|
359
|
+
this.value = Array.isArray(value) ? value : [value];
|
|
360
|
+
}
|
|
361
|
+
getSQL() {
|
|
362
|
+
return new SQL([this]);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
class SQL {
|
|
367
|
+
constructor(queryChunks) {
|
|
368
|
+
this.queryChunks = queryChunks;
|
|
369
|
+
}
|
|
370
|
+
static [entityKind] = "SQL";
|
|
371
|
+
decoder = noopDecoder;
|
|
372
|
+
shouldInlineParams = false;
|
|
373
|
+
append(query) {
|
|
374
|
+
this.queryChunks.push(...query.queryChunks);
|
|
375
|
+
return this;
|
|
376
|
+
}
|
|
377
|
+
toQuery(config) {
|
|
378
|
+
return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
|
|
379
|
+
const query = this.buildQueryFromSourceParams(this.queryChunks, config);
|
|
380
|
+
span?.setAttributes({
|
|
381
|
+
"drizzle.query.text": query.sql,
|
|
382
|
+
"drizzle.query.params": JSON.stringify(query.params)
|
|
383
|
+
});
|
|
384
|
+
return query;
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
buildQueryFromSourceParams(chunks, _config) {
|
|
388
|
+
const config = Object.assign({}, _config, {
|
|
389
|
+
inlineParams: _config.inlineParams || this.shouldInlineParams,
|
|
390
|
+
paramStartIndex: _config.paramStartIndex || { value: 0 }
|
|
391
|
+
});
|
|
392
|
+
const {
|
|
393
|
+
casing,
|
|
394
|
+
escapeName,
|
|
395
|
+
escapeParam,
|
|
396
|
+
prepareTyping,
|
|
397
|
+
inlineParams,
|
|
398
|
+
paramStartIndex
|
|
399
|
+
} = config;
|
|
400
|
+
return mergeQueries(chunks.map((chunk) => {
|
|
401
|
+
if (is(chunk, StringChunk)) {
|
|
402
|
+
return { sql: chunk.value.join(""), params: [] };
|
|
403
|
+
}
|
|
404
|
+
if (is(chunk, Name)) {
|
|
405
|
+
return { sql: escapeName(chunk.value), params: [] };
|
|
406
|
+
}
|
|
407
|
+
if (chunk === undefined) {
|
|
408
|
+
return { sql: "", params: [] };
|
|
409
|
+
}
|
|
410
|
+
if (Array.isArray(chunk)) {
|
|
411
|
+
const result = [new StringChunk("(")];
|
|
412
|
+
for (const [i, p] of chunk.entries()) {
|
|
413
|
+
result.push(p);
|
|
414
|
+
if (i < chunk.length - 1) {
|
|
415
|
+
result.push(new StringChunk(", "));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
result.push(new StringChunk(")"));
|
|
419
|
+
return this.buildQueryFromSourceParams(result, config);
|
|
420
|
+
}
|
|
421
|
+
if (is(chunk, SQL)) {
|
|
422
|
+
return this.buildQueryFromSourceParams(chunk.queryChunks, {
|
|
423
|
+
...config,
|
|
424
|
+
inlineParams: inlineParams || chunk.shouldInlineParams
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
if (is(chunk, Table)) {
|
|
428
|
+
const schemaName = chunk[Table.Symbol.Schema];
|
|
429
|
+
const tableName = chunk[Table.Symbol.Name];
|
|
430
|
+
return {
|
|
431
|
+
sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
|
|
432
|
+
params: []
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
if (is(chunk, Column)) {
|
|
436
|
+
const columnName = casing.getColumnCasing(chunk);
|
|
437
|
+
if (_config.invokeSource === "indexes") {
|
|
438
|
+
return { sql: escapeName(columnName), params: [] };
|
|
439
|
+
}
|
|
440
|
+
const schemaName = chunk.table[Table.Symbol.Schema];
|
|
441
|
+
return {
|
|
442
|
+
sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
|
|
443
|
+
params: []
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
if (is(chunk, View)) {
|
|
447
|
+
const schemaName = chunk[ViewBaseConfig].schema;
|
|
448
|
+
const viewName = chunk[ViewBaseConfig].name;
|
|
449
|
+
return {
|
|
450
|
+
sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
|
|
451
|
+
params: []
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
if (is(chunk, Param)) {
|
|
455
|
+
if (is(chunk.value, Placeholder)) {
|
|
456
|
+
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
|
|
457
|
+
}
|
|
458
|
+
const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
|
|
459
|
+
if (is(mappedValue, SQL)) {
|
|
460
|
+
return this.buildQueryFromSourceParams([mappedValue], config);
|
|
461
|
+
}
|
|
462
|
+
if (inlineParams) {
|
|
463
|
+
return { sql: this.mapInlineParam(mappedValue, config), params: [] };
|
|
464
|
+
}
|
|
465
|
+
let typings = ["none"];
|
|
466
|
+
if (prepareTyping) {
|
|
467
|
+
typings = [prepareTyping(chunk.encoder)];
|
|
468
|
+
}
|
|
469
|
+
return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
|
|
470
|
+
}
|
|
471
|
+
if (is(chunk, Placeholder)) {
|
|
472
|
+
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
|
|
473
|
+
}
|
|
474
|
+
if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
|
|
475
|
+
return { sql: escapeName(chunk.fieldAlias), params: [] };
|
|
476
|
+
}
|
|
477
|
+
if (is(chunk, Subquery)) {
|
|
478
|
+
if (chunk._.isWith) {
|
|
479
|
+
return { sql: escapeName(chunk._.alias), params: [] };
|
|
480
|
+
}
|
|
481
|
+
return this.buildQueryFromSourceParams([
|
|
482
|
+
new StringChunk("("),
|
|
483
|
+
chunk._.sql,
|
|
484
|
+
new StringChunk(") "),
|
|
485
|
+
new Name(chunk._.alias)
|
|
486
|
+
], config);
|
|
487
|
+
}
|
|
488
|
+
if (isPgEnum(chunk)) {
|
|
489
|
+
if (chunk.schema) {
|
|
490
|
+
return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
|
|
491
|
+
}
|
|
492
|
+
return { sql: escapeName(chunk.enumName), params: [] };
|
|
493
|
+
}
|
|
494
|
+
if (isSQLWrapper(chunk)) {
|
|
495
|
+
if (chunk.shouldOmitSQLParens?.()) {
|
|
496
|
+
return this.buildQueryFromSourceParams([chunk.getSQL()], config);
|
|
497
|
+
}
|
|
498
|
+
return this.buildQueryFromSourceParams([
|
|
499
|
+
new StringChunk("("),
|
|
500
|
+
chunk.getSQL(),
|
|
501
|
+
new StringChunk(")")
|
|
502
|
+
], config);
|
|
503
|
+
}
|
|
504
|
+
if (inlineParams) {
|
|
505
|
+
return { sql: this.mapInlineParam(chunk, config), params: [] };
|
|
506
|
+
}
|
|
507
|
+
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
|
|
508
|
+
}));
|
|
509
|
+
}
|
|
510
|
+
mapInlineParam(chunk, { escapeString }) {
|
|
511
|
+
if (chunk === null) {
|
|
512
|
+
return "null";
|
|
513
|
+
}
|
|
514
|
+
if (typeof chunk === "number" || typeof chunk === "boolean") {
|
|
515
|
+
return chunk.toString();
|
|
516
|
+
}
|
|
517
|
+
if (typeof chunk === "string") {
|
|
518
|
+
return escapeString(chunk);
|
|
519
|
+
}
|
|
520
|
+
if (typeof chunk === "object") {
|
|
521
|
+
const mappedValueAsString = chunk.toString();
|
|
522
|
+
if (mappedValueAsString === "[object Object]") {
|
|
523
|
+
return escapeString(JSON.stringify(chunk));
|
|
524
|
+
}
|
|
525
|
+
return escapeString(mappedValueAsString);
|
|
526
|
+
}
|
|
527
|
+
throw new Error("Unexpected param value: " + chunk);
|
|
528
|
+
}
|
|
529
|
+
getSQL() {
|
|
530
|
+
return this;
|
|
531
|
+
}
|
|
532
|
+
as(alias) {
|
|
533
|
+
if (alias === undefined) {
|
|
534
|
+
return this;
|
|
535
|
+
}
|
|
536
|
+
return new SQL.Aliased(this, alias);
|
|
537
|
+
}
|
|
538
|
+
mapWith(decoder) {
|
|
539
|
+
this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
|
|
540
|
+
return this;
|
|
541
|
+
}
|
|
542
|
+
inlineParams() {
|
|
543
|
+
this.shouldInlineParams = true;
|
|
544
|
+
return this;
|
|
545
|
+
}
|
|
546
|
+
if(condition) {
|
|
547
|
+
return condition ? this : undefined;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
class Name {
|
|
552
|
+
constructor(value) {
|
|
553
|
+
this.value = value;
|
|
554
|
+
}
|
|
555
|
+
static [entityKind] = "Name";
|
|
556
|
+
brand;
|
|
557
|
+
getSQL() {
|
|
558
|
+
return new SQL([this]);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
function isDriverValueEncoder(value) {
|
|
562
|
+
return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
|
|
563
|
+
}
|
|
564
|
+
var noopDecoder = {
|
|
565
|
+
mapFromDriverValue: (value) => value
|
|
566
|
+
};
|
|
567
|
+
var noopEncoder = {
|
|
568
|
+
mapToDriverValue: (value) => value
|
|
569
|
+
};
|
|
570
|
+
var noopMapper = {
|
|
571
|
+
...noopDecoder,
|
|
572
|
+
...noopEncoder
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
class Param {
|
|
576
|
+
constructor(value, encoder = noopEncoder) {
|
|
577
|
+
this.value = value;
|
|
578
|
+
this.encoder = encoder;
|
|
579
|
+
}
|
|
580
|
+
static [entityKind] = "Param";
|
|
581
|
+
brand;
|
|
582
|
+
getSQL() {
|
|
583
|
+
return new SQL([this]);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function sql(strings, ...params) {
|
|
587
|
+
const queryChunks = [];
|
|
588
|
+
if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
|
|
589
|
+
queryChunks.push(new StringChunk(strings[0]));
|
|
590
|
+
}
|
|
591
|
+
for (const [paramIndex, param2] of params.entries()) {
|
|
592
|
+
queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
|
|
593
|
+
}
|
|
594
|
+
return new SQL(queryChunks);
|
|
595
|
+
}
|
|
596
|
+
((sql2) => {
|
|
597
|
+
function empty() {
|
|
598
|
+
return new SQL([]);
|
|
599
|
+
}
|
|
600
|
+
sql2.empty = empty;
|
|
601
|
+
function fromList(list) {
|
|
602
|
+
return new SQL(list);
|
|
603
|
+
}
|
|
604
|
+
sql2.fromList = fromList;
|
|
605
|
+
function raw(str) {
|
|
606
|
+
return new SQL([new StringChunk(str)]);
|
|
607
|
+
}
|
|
608
|
+
sql2.raw = raw;
|
|
609
|
+
function join(chunks, separator) {
|
|
610
|
+
const result = [];
|
|
611
|
+
for (const [i, chunk] of chunks.entries()) {
|
|
612
|
+
if (i > 0 && separator !== undefined) {
|
|
613
|
+
result.push(separator);
|
|
614
|
+
}
|
|
615
|
+
result.push(chunk);
|
|
616
|
+
}
|
|
617
|
+
return new SQL(result);
|
|
618
|
+
}
|
|
619
|
+
sql2.join = join;
|
|
620
|
+
function identifier(value) {
|
|
621
|
+
return new Name(value);
|
|
622
|
+
}
|
|
623
|
+
sql2.identifier = identifier;
|
|
624
|
+
function placeholder2(name2) {
|
|
625
|
+
return new Placeholder(name2);
|
|
626
|
+
}
|
|
627
|
+
sql2.placeholder = placeholder2;
|
|
628
|
+
function param2(value, encoder) {
|
|
629
|
+
return new Param(value, encoder);
|
|
630
|
+
}
|
|
631
|
+
sql2.param = param2;
|
|
632
|
+
})(sql || (sql = {}));
|
|
633
|
+
((SQL2) => {
|
|
634
|
+
|
|
635
|
+
class Aliased {
|
|
636
|
+
constructor(sql2, fieldAlias) {
|
|
637
|
+
this.sql = sql2;
|
|
638
|
+
this.fieldAlias = fieldAlias;
|
|
639
|
+
}
|
|
640
|
+
static [entityKind] = "SQL.Aliased";
|
|
641
|
+
isSelectionField = false;
|
|
642
|
+
getSQL() {
|
|
643
|
+
return this.sql;
|
|
644
|
+
}
|
|
645
|
+
clone() {
|
|
646
|
+
return new Aliased(this.sql, this.fieldAlias);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
SQL2.Aliased = Aliased;
|
|
650
|
+
})(SQL || (SQL = {}));
|
|
651
|
+
|
|
652
|
+
class Placeholder {
|
|
653
|
+
constructor(name2) {
|
|
654
|
+
this.name = name2;
|
|
655
|
+
}
|
|
656
|
+
static [entityKind] = "Placeholder";
|
|
657
|
+
getSQL() {
|
|
658
|
+
return new SQL([this]);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
function fillPlaceholders(params, values) {
|
|
662
|
+
return params.map((p) => {
|
|
663
|
+
if (is(p, Placeholder)) {
|
|
664
|
+
if (!(p.name in values)) {
|
|
665
|
+
throw new Error(`No value for placeholder "${p.name}" was provided`);
|
|
666
|
+
}
|
|
667
|
+
return values[p.name];
|
|
668
|
+
}
|
|
669
|
+
if (is(p, Param) && is(p.value, Placeholder)) {
|
|
670
|
+
if (!(p.value.name in values)) {
|
|
671
|
+
throw new Error(`No value for placeholder "${p.value.name}" was provided`);
|
|
672
|
+
}
|
|
673
|
+
return p.encoder.mapToDriverValue(values[p.value.name]);
|
|
674
|
+
}
|
|
675
|
+
return p;
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
|
|
679
|
+
|
|
680
|
+
class View {
|
|
681
|
+
static [entityKind] = "View";
|
|
682
|
+
[ViewBaseConfig];
|
|
683
|
+
[IsDrizzleView] = true;
|
|
684
|
+
constructor({ name: name2, schema, selectedFields, query }) {
|
|
685
|
+
this[ViewBaseConfig] = {
|
|
686
|
+
name: name2,
|
|
687
|
+
originalName: name2,
|
|
688
|
+
schema,
|
|
689
|
+
selectedFields,
|
|
690
|
+
query,
|
|
691
|
+
isExisting: !query,
|
|
692
|
+
isAlias: false
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
getSQL() {
|
|
696
|
+
return new SQL([this]);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
Column.prototype.getSQL = function() {
|
|
700
|
+
return new SQL([this]);
|
|
701
|
+
};
|
|
702
|
+
Table.prototype.getSQL = function() {
|
|
703
|
+
return new SQL([this]);
|
|
704
|
+
};
|
|
705
|
+
Subquery.prototype.getSQL = function() {
|
|
706
|
+
return new SQL([this]);
|
|
707
|
+
};
|
|
708
|
+
|
|
709
|
+
// node_modules/drizzle-orm/alias.js
|
|
710
|
+
class ColumnAliasProxyHandler {
|
|
711
|
+
constructor(table) {
|
|
712
|
+
this.table = table;
|
|
713
|
+
}
|
|
714
|
+
static [entityKind] = "ColumnAliasProxyHandler";
|
|
715
|
+
get(columnObj, prop) {
|
|
716
|
+
if (prop === "table") {
|
|
717
|
+
return this.table;
|
|
718
|
+
}
|
|
719
|
+
return columnObj[prop];
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
class TableAliasProxyHandler {
|
|
724
|
+
constructor(alias, replaceOriginalName) {
|
|
725
|
+
this.alias = alias;
|
|
726
|
+
this.replaceOriginalName = replaceOriginalName;
|
|
727
|
+
}
|
|
728
|
+
static [entityKind] = "TableAliasProxyHandler";
|
|
729
|
+
get(target, prop) {
|
|
730
|
+
if (prop === Table.Symbol.IsAlias) {
|
|
731
|
+
return true;
|
|
732
|
+
}
|
|
733
|
+
if (prop === Table.Symbol.Name) {
|
|
734
|
+
return this.alias;
|
|
735
|
+
}
|
|
736
|
+
if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
|
|
737
|
+
return this.alias;
|
|
738
|
+
}
|
|
739
|
+
if (prop === ViewBaseConfig) {
|
|
740
|
+
return {
|
|
741
|
+
...target[ViewBaseConfig],
|
|
742
|
+
name: this.alias,
|
|
743
|
+
isAlias: true
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
if (prop === Table.Symbol.Columns) {
|
|
747
|
+
const columns = target[Table.Symbol.Columns];
|
|
748
|
+
if (!columns) {
|
|
749
|
+
return columns;
|
|
750
|
+
}
|
|
751
|
+
const proxiedColumns = {};
|
|
752
|
+
Object.keys(columns).map((key) => {
|
|
753
|
+
proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
|
|
754
|
+
});
|
|
755
|
+
return proxiedColumns;
|
|
756
|
+
}
|
|
757
|
+
const value = target[prop];
|
|
758
|
+
if (is(value, Column)) {
|
|
759
|
+
return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
|
|
760
|
+
}
|
|
761
|
+
return value;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
function aliasedTable(table, tableAlias) {
|
|
765
|
+
return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
|
|
766
|
+
}
|
|
767
|
+
function aliasedTableColumn(column, tableAlias) {
|
|
768
|
+
return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
|
|
769
|
+
}
|
|
770
|
+
function mapColumnsInAliasedSQLToAlias(query, alias) {
|
|
771
|
+
return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
|
|
772
|
+
}
|
|
773
|
+
function mapColumnsInSQLToAlias(query, alias) {
|
|
774
|
+
return sql.join(query.queryChunks.map((c) => {
|
|
775
|
+
if (is(c, Column)) {
|
|
776
|
+
return aliasedTableColumn(c, alias);
|
|
777
|
+
}
|
|
778
|
+
if (is(c, SQL)) {
|
|
779
|
+
return mapColumnsInSQLToAlias(c, alias);
|
|
780
|
+
}
|
|
781
|
+
if (is(c, SQL.Aliased)) {
|
|
782
|
+
return mapColumnsInAliasedSQLToAlias(c, alias);
|
|
783
|
+
}
|
|
784
|
+
return c;
|
|
785
|
+
}));
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// node_modules/drizzle-orm/errors.js
|
|
789
|
+
class DrizzleError extends Error {
|
|
790
|
+
static [entityKind] = "DrizzleError";
|
|
791
|
+
constructor({ message, cause }) {
|
|
792
|
+
super(message);
|
|
793
|
+
this.name = "DrizzleError";
|
|
794
|
+
this.cause = cause;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
class TransactionRollbackError extends DrizzleError {
|
|
799
|
+
static [entityKind] = "TransactionRollbackError";
|
|
800
|
+
constructor() {
|
|
801
|
+
super({ message: "Rollback" });
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// node_modules/drizzle-orm/sql/expressions/conditions.js
|
|
806
|
+
function bindIfParam(value, column) {
|
|
807
|
+
if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
|
|
808
|
+
return new Param(value, column);
|
|
809
|
+
}
|
|
810
|
+
return value;
|
|
811
|
+
}
|
|
812
|
+
var eq = (left, right) => {
|
|
813
|
+
return sql`${left} = ${bindIfParam(right, left)}`;
|
|
814
|
+
};
|
|
815
|
+
var ne = (left, right) => {
|
|
816
|
+
return sql`${left} <> ${bindIfParam(right, left)}`;
|
|
817
|
+
};
|
|
818
|
+
function and(...unfilteredConditions) {
|
|
819
|
+
const conditions = unfilteredConditions.filter((c) => c !== undefined);
|
|
820
|
+
if (conditions.length === 0) {
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
if (conditions.length === 1) {
|
|
824
|
+
return new SQL(conditions);
|
|
825
|
+
}
|
|
826
|
+
return new SQL([
|
|
827
|
+
new StringChunk("("),
|
|
828
|
+
sql.join(conditions, new StringChunk(" and ")),
|
|
829
|
+
new StringChunk(")")
|
|
830
|
+
]);
|
|
831
|
+
}
|
|
832
|
+
function or(...unfilteredConditions) {
|
|
833
|
+
const conditions = unfilteredConditions.filter((c) => c !== undefined);
|
|
834
|
+
if (conditions.length === 0) {
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
if (conditions.length === 1) {
|
|
838
|
+
return new SQL(conditions);
|
|
839
|
+
}
|
|
840
|
+
return new SQL([
|
|
841
|
+
new StringChunk("("),
|
|
842
|
+
sql.join(conditions, new StringChunk(" or ")),
|
|
843
|
+
new StringChunk(")")
|
|
844
|
+
]);
|
|
845
|
+
}
|
|
846
|
+
function not(condition) {
|
|
847
|
+
return sql`not ${condition}`;
|
|
848
|
+
}
|
|
849
|
+
var gt = (left, right) => {
|
|
850
|
+
return sql`${left} > ${bindIfParam(right, left)}`;
|
|
851
|
+
};
|
|
852
|
+
var gte = (left, right) => {
|
|
853
|
+
return sql`${left} >= ${bindIfParam(right, left)}`;
|
|
854
|
+
};
|
|
855
|
+
var lt = (left, right) => {
|
|
856
|
+
return sql`${left} < ${bindIfParam(right, left)}`;
|
|
857
|
+
};
|
|
858
|
+
var lte = (left, right) => {
|
|
859
|
+
return sql`${left} <= ${bindIfParam(right, left)}`;
|
|
860
|
+
};
|
|
861
|
+
function inArray(column, values) {
|
|
862
|
+
if (Array.isArray(values)) {
|
|
863
|
+
if (values.length === 0) {
|
|
864
|
+
return sql`false`;
|
|
865
|
+
}
|
|
866
|
+
return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
|
|
867
|
+
}
|
|
868
|
+
return sql`${column} in ${bindIfParam(values, column)}`;
|
|
869
|
+
}
|
|
870
|
+
function notInArray(column, values) {
|
|
871
|
+
if (Array.isArray(values)) {
|
|
872
|
+
if (values.length === 0) {
|
|
873
|
+
return sql`true`;
|
|
874
|
+
}
|
|
875
|
+
return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
|
|
876
|
+
}
|
|
877
|
+
return sql`${column} not in ${bindIfParam(values, column)}`;
|
|
878
|
+
}
|
|
879
|
+
function isNull(value) {
|
|
880
|
+
return sql`${value} is null`;
|
|
881
|
+
}
|
|
882
|
+
function isNotNull(value) {
|
|
883
|
+
return sql`${value} is not null`;
|
|
884
|
+
}
|
|
885
|
+
function exists(subquery) {
|
|
886
|
+
return sql`exists ${subquery}`;
|
|
887
|
+
}
|
|
888
|
+
function notExists(subquery) {
|
|
889
|
+
return sql`not exists ${subquery}`;
|
|
890
|
+
}
|
|
891
|
+
function between(column, min, max) {
|
|
892
|
+
return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
|
|
893
|
+
}
|
|
894
|
+
function notBetween(column, min, max) {
|
|
895
|
+
return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
|
|
896
|
+
}
|
|
897
|
+
function like(column, value) {
|
|
898
|
+
return sql`${column} like ${value}`;
|
|
899
|
+
}
|
|
900
|
+
function notLike(column, value) {
|
|
901
|
+
return sql`${column} not like ${value}`;
|
|
902
|
+
}
|
|
903
|
+
function ilike(column, value) {
|
|
904
|
+
return sql`${column} ilike ${value}`;
|
|
905
|
+
}
|
|
906
|
+
function notIlike(column, value) {
|
|
907
|
+
return sql`${column} not ilike ${value}`;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// node_modules/drizzle-orm/sql/expressions/select.js
|
|
911
|
+
function asc(column) {
|
|
912
|
+
return sql`${column} asc`;
|
|
913
|
+
}
|
|
914
|
+
function desc(column) {
|
|
915
|
+
return sql`${column} desc`;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// node_modules/drizzle-orm/logger.js
|
|
919
|
+
class ConsoleLogWriter {
|
|
920
|
+
static [entityKind] = "ConsoleLogWriter";
|
|
921
|
+
write(message) {
|
|
922
|
+
console.log(message);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
class DefaultLogger {
|
|
927
|
+
static [entityKind] = "DefaultLogger";
|
|
928
|
+
writer;
|
|
929
|
+
constructor(config) {
|
|
930
|
+
this.writer = config?.writer ?? new ConsoleLogWriter;
|
|
931
|
+
}
|
|
932
|
+
logQuery(query, params) {
|
|
933
|
+
const stringifiedParams = params.map((p) => {
|
|
934
|
+
try {
|
|
935
|
+
return JSON.stringify(p);
|
|
936
|
+
} catch {
|
|
937
|
+
return String(p);
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
|
|
941
|
+
this.writer.write(`Query: ${query}${paramsStr}`);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
class NoopLogger {
|
|
946
|
+
static [entityKind] = "NoopLogger";
|
|
947
|
+
logQuery() {}
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// node_modules/drizzle-orm/query-promise.js
|
|
951
|
+
class QueryPromise {
|
|
952
|
+
static [entityKind] = "QueryPromise";
|
|
953
|
+
[Symbol.toStringTag] = "QueryPromise";
|
|
954
|
+
catch(onRejected) {
|
|
955
|
+
return this.then(undefined, onRejected);
|
|
956
|
+
}
|
|
957
|
+
finally(onFinally) {
|
|
958
|
+
return this.then((value) => {
|
|
959
|
+
onFinally?.();
|
|
960
|
+
return value;
|
|
961
|
+
}, (reason) => {
|
|
962
|
+
onFinally?.();
|
|
963
|
+
throw reason;
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
then(onFulfilled, onRejected) {
|
|
967
|
+
return this.execute().then(onFulfilled, onRejected);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// node_modules/drizzle-orm/utils.js
|
|
972
|
+
function mapResultRow(columns, row, joinsNotNullableMap) {
|
|
973
|
+
const nullifyMap = {};
|
|
974
|
+
const result = columns.reduce((result2, { path, field }, columnIndex) => {
|
|
975
|
+
let decoder;
|
|
976
|
+
if (is(field, Column)) {
|
|
977
|
+
decoder = field;
|
|
978
|
+
} else if (is(field, SQL)) {
|
|
979
|
+
decoder = field.decoder;
|
|
980
|
+
} else {
|
|
981
|
+
decoder = field.sql.decoder;
|
|
982
|
+
}
|
|
983
|
+
let node = result2;
|
|
984
|
+
for (const [pathChunkIndex, pathChunk] of path.entries()) {
|
|
985
|
+
if (pathChunkIndex < path.length - 1) {
|
|
986
|
+
if (!(pathChunk in node)) {
|
|
987
|
+
node[pathChunk] = {};
|
|
988
|
+
}
|
|
989
|
+
node = node[pathChunk];
|
|
990
|
+
} else {
|
|
991
|
+
const rawValue = row[columnIndex];
|
|
992
|
+
const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
|
|
993
|
+
if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
|
|
994
|
+
const objectName = path[0];
|
|
995
|
+
if (!(objectName in nullifyMap)) {
|
|
996
|
+
nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
|
|
997
|
+
} else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
|
|
998
|
+
nullifyMap[objectName] = false;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
return result2;
|
|
1004
|
+
}, {});
|
|
1005
|
+
if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
|
|
1006
|
+
for (const [objectName, tableName] of Object.entries(nullifyMap)) {
|
|
1007
|
+
if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
|
|
1008
|
+
result[objectName] = null;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return result;
|
|
1013
|
+
}
|
|
1014
|
+
function orderSelectedFields(fields, pathPrefix) {
|
|
1015
|
+
return Object.entries(fields).reduce((result, [name, field]) => {
|
|
1016
|
+
if (typeof name !== "string") {
|
|
1017
|
+
return result;
|
|
1018
|
+
}
|
|
1019
|
+
const newPath = pathPrefix ? [...pathPrefix, name] : [name];
|
|
1020
|
+
if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
|
|
1021
|
+
result.push({ path: newPath, field });
|
|
1022
|
+
} else if (is(field, Table)) {
|
|
1023
|
+
result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
|
|
1024
|
+
} else {
|
|
1025
|
+
result.push(...orderSelectedFields(field, newPath));
|
|
1026
|
+
}
|
|
1027
|
+
return result;
|
|
1028
|
+
}, []);
|
|
1029
|
+
}
|
|
1030
|
+
function haveSameKeys(left, right) {
|
|
1031
|
+
const leftKeys = Object.keys(left);
|
|
1032
|
+
const rightKeys = Object.keys(right);
|
|
1033
|
+
if (leftKeys.length !== rightKeys.length) {
|
|
1034
|
+
return false;
|
|
1035
|
+
}
|
|
1036
|
+
for (const [index, key] of leftKeys.entries()) {
|
|
1037
|
+
if (key !== rightKeys[index]) {
|
|
1038
|
+
return false;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return true;
|
|
1042
|
+
}
|
|
1043
|
+
function mapUpdateSet(table, values) {
|
|
1044
|
+
const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => {
|
|
1045
|
+
if (is(value, SQL) || is(value, Column)) {
|
|
1046
|
+
return [key, value];
|
|
1047
|
+
} else {
|
|
1048
|
+
return [key, new Param(value, table[Table.Symbol.Columns][key])];
|
|
1049
|
+
}
|
|
1050
|
+
});
|
|
1051
|
+
if (entries.length === 0) {
|
|
1052
|
+
throw new Error("No values to set");
|
|
1053
|
+
}
|
|
1054
|
+
return Object.fromEntries(entries);
|
|
1055
|
+
}
|
|
1056
|
+
function applyMixins(baseClass, extendedClasses) {
|
|
1057
|
+
for (const extendedClass of extendedClasses) {
|
|
1058
|
+
for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
|
|
1059
|
+
if (name === "constructor")
|
|
1060
|
+
continue;
|
|
1061
|
+
Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null));
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
function getTableColumns(table) {
|
|
1066
|
+
return table[Table.Symbol.Columns];
|
|
1067
|
+
}
|
|
1068
|
+
function getTableLikeName(table) {
|
|
1069
|
+
return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
|
|
1070
|
+
}
|
|
1071
|
+
function getColumnNameAndConfig(a, b) {
|
|
1072
|
+
return {
|
|
1073
|
+
name: typeof a === "string" && a.length > 0 ? a : "",
|
|
1074
|
+
config: typeof a === "object" ? a : b
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
function isConfig(data) {
|
|
1078
|
+
if (typeof data !== "object" || data === null)
|
|
1079
|
+
return false;
|
|
1080
|
+
if (data.constructor.name !== "Object")
|
|
1081
|
+
return false;
|
|
1082
|
+
if ("logger" in data) {
|
|
1083
|
+
const type = typeof data["logger"];
|
|
1084
|
+
if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined")
|
|
1085
|
+
return false;
|
|
1086
|
+
return true;
|
|
1087
|
+
}
|
|
1088
|
+
if ("schema" in data) {
|
|
1089
|
+
const type = typeof data["logger"];
|
|
1090
|
+
if (type !== "object" && type !== "undefined")
|
|
1091
|
+
return false;
|
|
1092
|
+
return true;
|
|
1093
|
+
}
|
|
1094
|
+
if ("casing" in data) {
|
|
1095
|
+
const type = typeof data["logger"];
|
|
1096
|
+
if (type !== "string" && type !== "undefined")
|
|
1097
|
+
return false;
|
|
1098
|
+
return true;
|
|
1099
|
+
}
|
|
1100
|
+
if ("mode" in data) {
|
|
1101
|
+
if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined)
|
|
1102
|
+
return false;
|
|
1103
|
+
return true;
|
|
1104
|
+
}
|
|
1105
|
+
if ("connection" in data) {
|
|
1106
|
+
const type = typeof data["connection"];
|
|
1107
|
+
if (type !== "string" && type !== "object" && type !== "undefined")
|
|
1108
|
+
return false;
|
|
1109
|
+
return true;
|
|
1110
|
+
}
|
|
1111
|
+
if ("client" in data) {
|
|
1112
|
+
const type = typeof data["client"];
|
|
1113
|
+
if (type !== "object" && type !== "function" && type !== "undefined")
|
|
1114
|
+
return false;
|
|
1115
|
+
return true;
|
|
1116
|
+
}
|
|
1117
|
+
if (Object.keys(data).length === 0)
|
|
1118
|
+
return true;
|
|
1119
|
+
return false;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// node_modules/drizzle-orm/pg-core/table.js
|
|
1123
|
+
var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
|
|
1124
|
+
var EnableRLS = Symbol.for("drizzle:EnableRLS");
|
|
1125
|
+
|
|
1126
|
+
class PgTable extends Table {
|
|
1127
|
+
static [entityKind] = "PgTable";
|
|
1128
|
+
static Symbol = Object.assign({}, Table.Symbol, {
|
|
1129
|
+
InlineForeignKeys,
|
|
1130
|
+
EnableRLS
|
|
1131
|
+
});
|
|
1132
|
+
[InlineForeignKeys] = [];
|
|
1133
|
+
[EnableRLS] = false;
|
|
1134
|
+
[Table.Symbol.ExtraConfigBuilder] = undefined;
|
|
1135
|
+
[Table.Symbol.ExtraConfigColumns] = {};
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// node_modules/drizzle-orm/pg-core/primary-keys.js
|
|
1139
|
+
class PrimaryKeyBuilder {
|
|
1140
|
+
static [entityKind] = "PgPrimaryKeyBuilder";
|
|
1141
|
+
columns;
|
|
1142
|
+
name;
|
|
1143
|
+
constructor(columns, name) {
|
|
1144
|
+
this.columns = columns;
|
|
1145
|
+
this.name = name;
|
|
1146
|
+
}
|
|
1147
|
+
build(table) {
|
|
1148
|
+
return new PrimaryKey(table, this.columns, this.name);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
class PrimaryKey {
|
|
1153
|
+
constructor(table, columns, name) {
|
|
1154
|
+
this.table = table;
|
|
1155
|
+
this.columns = columns;
|
|
1156
|
+
this.name = name;
|
|
1157
|
+
}
|
|
1158
|
+
static [entityKind] = "PgPrimaryKey";
|
|
1159
|
+
columns;
|
|
1160
|
+
name;
|
|
1161
|
+
getName() {
|
|
1162
|
+
return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// node_modules/drizzle-orm/relations.js
|
|
1167
|
+
class Relation {
|
|
1168
|
+
constructor(sourceTable, referencedTable, relationName) {
|
|
1169
|
+
this.sourceTable = sourceTable;
|
|
1170
|
+
this.referencedTable = referencedTable;
|
|
1171
|
+
this.relationName = relationName;
|
|
1172
|
+
this.referencedTableName = referencedTable[Table.Symbol.Name];
|
|
1173
|
+
}
|
|
1174
|
+
static [entityKind] = "Relation";
|
|
1175
|
+
referencedTableName;
|
|
1176
|
+
fieldName;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
class Relations {
|
|
1180
|
+
constructor(table, config) {
|
|
1181
|
+
this.table = table;
|
|
1182
|
+
this.config = config;
|
|
1183
|
+
}
|
|
1184
|
+
static [entityKind] = "Relations";
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
class One extends Relation {
|
|
1188
|
+
constructor(sourceTable, referencedTable, config, isNullable) {
|
|
1189
|
+
super(sourceTable, referencedTable, config?.relationName);
|
|
1190
|
+
this.config = config;
|
|
1191
|
+
this.isNullable = isNullable;
|
|
1192
|
+
}
|
|
1193
|
+
static [entityKind] = "One";
|
|
1194
|
+
withFieldName(fieldName) {
|
|
1195
|
+
const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
|
|
1196
|
+
relation.fieldName = fieldName;
|
|
1197
|
+
return relation;
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
class Many extends Relation {
|
|
1202
|
+
constructor(sourceTable, referencedTable, config) {
|
|
1203
|
+
super(sourceTable, referencedTable, config?.relationName);
|
|
1204
|
+
this.config = config;
|
|
1205
|
+
}
|
|
1206
|
+
static [entityKind] = "Many";
|
|
1207
|
+
withFieldName(fieldName) {
|
|
1208
|
+
const relation = new Many(this.sourceTable, this.referencedTable, this.config);
|
|
1209
|
+
relation.fieldName = fieldName;
|
|
1210
|
+
return relation;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
function getOperators() {
|
|
1214
|
+
return {
|
|
1215
|
+
and,
|
|
1216
|
+
between,
|
|
1217
|
+
eq,
|
|
1218
|
+
exists,
|
|
1219
|
+
gt,
|
|
1220
|
+
gte,
|
|
1221
|
+
ilike,
|
|
1222
|
+
inArray,
|
|
1223
|
+
isNull,
|
|
1224
|
+
isNotNull,
|
|
1225
|
+
like,
|
|
1226
|
+
lt,
|
|
1227
|
+
lte,
|
|
1228
|
+
ne,
|
|
1229
|
+
not,
|
|
1230
|
+
notBetween,
|
|
1231
|
+
notExists,
|
|
1232
|
+
notLike,
|
|
1233
|
+
notIlike,
|
|
1234
|
+
notInArray,
|
|
1235
|
+
or,
|
|
1236
|
+
sql
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
function getOrderByOperators() {
|
|
1240
|
+
return {
|
|
1241
|
+
sql,
|
|
1242
|
+
asc,
|
|
1243
|
+
desc
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
function extractTablesRelationalConfig(schema, configHelpers) {
|
|
1247
|
+
if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
|
|
1248
|
+
schema = schema["default"];
|
|
1249
|
+
}
|
|
1250
|
+
const tableNamesMap = {};
|
|
1251
|
+
const relationsBuffer = {};
|
|
1252
|
+
const tablesConfig = {};
|
|
1253
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
1254
|
+
if (is(value, Table)) {
|
|
1255
|
+
const dbName = getTableUniqueName(value);
|
|
1256
|
+
const bufferedRelations = relationsBuffer[dbName];
|
|
1257
|
+
tableNamesMap[dbName] = key;
|
|
1258
|
+
tablesConfig[key] = {
|
|
1259
|
+
tsName: key,
|
|
1260
|
+
dbName: value[Table.Symbol.Name],
|
|
1261
|
+
schema: value[Table.Symbol.Schema],
|
|
1262
|
+
columns: value[Table.Symbol.Columns],
|
|
1263
|
+
relations: bufferedRelations?.relations ?? {},
|
|
1264
|
+
primaryKey: bufferedRelations?.primaryKey ?? []
|
|
1265
|
+
};
|
|
1266
|
+
for (const column of Object.values(value[Table.Symbol.Columns])) {
|
|
1267
|
+
if (column.primary) {
|
|
1268
|
+
tablesConfig[key].primaryKey.push(column);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
|
|
1272
|
+
if (extraConfig) {
|
|
1273
|
+
for (const configEntry of Object.values(extraConfig)) {
|
|
1274
|
+
if (is(configEntry, PrimaryKeyBuilder)) {
|
|
1275
|
+
tablesConfig[key].primaryKey.push(...configEntry.columns);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
} else if (is(value, Relations)) {
|
|
1280
|
+
const dbName = getTableUniqueName(value.table);
|
|
1281
|
+
const tableName = tableNamesMap[dbName];
|
|
1282
|
+
const relations2 = value.config(configHelpers(value.table));
|
|
1283
|
+
let primaryKey;
|
|
1284
|
+
for (const [relationName, relation] of Object.entries(relations2)) {
|
|
1285
|
+
if (tableName) {
|
|
1286
|
+
const tableConfig = tablesConfig[tableName];
|
|
1287
|
+
tableConfig.relations[relationName] = relation;
|
|
1288
|
+
if (primaryKey) {
|
|
1289
|
+
tableConfig.primaryKey.push(...primaryKey);
|
|
1290
|
+
}
|
|
1291
|
+
} else {
|
|
1292
|
+
if (!(dbName in relationsBuffer)) {
|
|
1293
|
+
relationsBuffer[dbName] = {
|
|
1294
|
+
relations: {},
|
|
1295
|
+
primaryKey
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
relationsBuffer[dbName].relations[relationName] = relation;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
return { tables: tablesConfig, tableNamesMap };
|
|
1304
|
+
}
|
|
1305
|
+
function createOne(sourceTable) {
|
|
1306
|
+
return function one(table, config) {
|
|
1307
|
+
return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
function createMany(sourceTable) {
|
|
1311
|
+
return function many(referencedTable, config) {
|
|
1312
|
+
return new Many(sourceTable, referencedTable, config);
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
function normalizeRelation(schema, tableNamesMap, relation) {
|
|
1316
|
+
if (is(relation, One) && relation.config) {
|
|
1317
|
+
return {
|
|
1318
|
+
fields: relation.config.fields,
|
|
1319
|
+
references: relation.config.references
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
|
|
1323
|
+
if (!referencedTableTsName) {
|
|
1324
|
+
throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
|
|
1325
|
+
}
|
|
1326
|
+
const referencedTableConfig = schema[referencedTableTsName];
|
|
1327
|
+
if (!referencedTableConfig) {
|
|
1328
|
+
throw new Error(`Table "${referencedTableTsName}" not found in schema`);
|
|
1329
|
+
}
|
|
1330
|
+
const sourceTable = relation.sourceTable;
|
|
1331
|
+
const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
|
|
1332
|
+
if (!sourceTableTsName) {
|
|
1333
|
+
throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
|
|
1334
|
+
}
|
|
1335
|
+
const reverseRelations = [];
|
|
1336
|
+
for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) {
|
|
1337
|
+
if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
|
|
1338
|
+
reverseRelations.push(referencedTableRelation);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
if (reverseRelations.length > 1) {
|
|
1342
|
+
throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
|
|
1343
|
+
}
|
|
1344
|
+
if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
|
|
1345
|
+
return {
|
|
1346
|
+
fields: reverseRelations[0].config.references,
|
|
1347
|
+
references: reverseRelations[0].config.fields
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
|
|
1351
|
+
}
|
|
1352
|
+
function createTableRelationsHelpers(sourceTable) {
|
|
1353
|
+
return {
|
|
1354
|
+
one: createOne(sourceTable),
|
|
1355
|
+
many: createMany(sourceTable)
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
|
|
1359
|
+
const result = {};
|
|
1360
|
+
for (const [
|
|
1361
|
+
selectionItemIndex,
|
|
1362
|
+
selectionItem
|
|
1363
|
+
] of buildQueryResultSelection.entries()) {
|
|
1364
|
+
if (selectionItem.isJson) {
|
|
1365
|
+
const relation = tableConfig.relations[selectionItem.tsKey];
|
|
1366
|
+
const rawSubRows = row[selectionItemIndex];
|
|
1367
|
+
const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
|
|
1368
|
+
result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
|
|
1369
|
+
} else {
|
|
1370
|
+
const value = mapColumnValue(row[selectionItemIndex]);
|
|
1371
|
+
const field = selectionItem.field;
|
|
1372
|
+
let decoder;
|
|
1373
|
+
if (is(field, Column)) {
|
|
1374
|
+
decoder = field;
|
|
1375
|
+
} else if (is(field, SQL)) {
|
|
1376
|
+
decoder = field.decoder;
|
|
1377
|
+
} else {
|
|
1378
|
+
decoder = field.sql.decoder;
|
|
1379
|
+
}
|
|
1380
|
+
result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
return result;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
// src/server/index.ts
|
|
1387
|
+
import { randomUUID } from "crypto";
|
|
1388
|
+
|
|
1389
|
+
// node_modules/drizzle-orm/bun-sqlite/driver.js
|
|
1390
|
+
import { Database } from "bun:sqlite";
|
|
1391
|
+
|
|
1392
|
+
// node_modules/drizzle-orm/selection-proxy.js
|
|
1393
|
+
class SelectionProxyHandler {
|
|
1394
|
+
static [entityKind] = "SelectionProxyHandler";
|
|
1395
|
+
config;
|
|
1396
|
+
constructor(config) {
|
|
1397
|
+
this.config = { ...config };
|
|
1398
|
+
}
|
|
1399
|
+
get(subquery, prop) {
|
|
1400
|
+
if (prop === "_") {
|
|
1401
|
+
return {
|
|
1402
|
+
...subquery["_"],
|
|
1403
|
+
selectedFields: new Proxy(subquery._.selectedFields, this)
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
if (prop === ViewBaseConfig) {
|
|
1407
|
+
return {
|
|
1408
|
+
...subquery[ViewBaseConfig],
|
|
1409
|
+
selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
if (typeof prop === "symbol") {
|
|
1413
|
+
return subquery[prop];
|
|
1414
|
+
}
|
|
1415
|
+
const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
|
|
1416
|
+
const value = columns[prop];
|
|
1417
|
+
if (is(value, SQL.Aliased)) {
|
|
1418
|
+
if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
|
|
1419
|
+
return value.sql;
|
|
1420
|
+
}
|
|
1421
|
+
const newValue = value.clone();
|
|
1422
|
+
newValue.isSelectionField = true;
|
|
1423
|
+
return newValue;
|
|
1424
|
+
}
|
|
1425
|
+
if (is(value, SQL)) {
|
|
1426
|
+
if (this.config.sqlBehavior === "sql") {
|
|
1427
|
+
return value;
|
|
1428
|
+
}
|
|
1429
|
+
throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
|
|
1430
|
+
}
|
|
1431
|
+
if (is(value, Column)) {
|
|
1432
|
+
if (this.config.alias) {
|
|
1433
|
+
return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
|
|
1434
|
+
}
|
|
1435
|
+
return value;
|
|
1436
|
+
}
|
|
1437
|
+
if (typeof value !== "object" || value === null) {
|
|
1438
|
+
return value;
|
|
1439
|
+
}
|
|
1440
|
+
return new Proxy(value, new SelectionProxyHandler(this.config));
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
// node_modules/drizzle-orm/sqlite-core/foreign-keys.js
|
|
1445
|
+
class ForeignKeyBuilder {
|
|
1446
|
+
static [entityKind] = "SQLiteForeignKeyBuilder";
|
|
1447
|
+
reference;
|
|
1448
|
+
_onUpdate;
|
|
1449
|
+
_onDelete;
|
|
1450
|
+
constructor(config, actions) {
|
|
1451
|
+
this.reference = () => {
|
|
1452
|
+
const { name, columns, foreignColumns } = config();
|
|
1453
|
+
return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
|
|
1454
|
+
};
|
|
1455
|
+
if (actions) {
|
|
1456
|
+
this._onUpdate = actions.onUpdate;
|
|
1457
|
+
this._onDelete = actions.onDelete;
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
onUpdate(action) {
|
|
1461
|
+
this._onUpdate = action;
|
|
1462
|
+
return this;
|
|
1463
|
+
}
|
|
1464
|
+
onDelete(action) {
|
|
1465
|
+
this._onDelete = action;
|
|
1466
|
+
return this;
|
|
1467
|
+
}
|
|
1468
|
+
build(table) {
|
|
1469
|
+
return new ForeignKey(table, this);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
class ForeignKey {
|
|
1474
|
+
constructor(table, builder) {
|
|
1475
|
+
this.table = table;
|
|
1476
|
+
this.reference = builder.reference;
|
|
1477
|
+
this.onUpdate = builder._onUpdate;
|
|
1478
|
+
this.onDelete = builder._onDelete;
|
|
1479
|
+
}
|
|
1480
|
+
static [entityKind] = "SQLiteForeignKey";
|
|
1481
|
+
reference;
|
|
1482
|
+
onUpdate;
|
|
1483
|
+
onDelete;
|
|
1484
|
+
getName() {
|
|
1485
|
+
const { name, columns, foreignColumns } = this.reference();
|
|
1486
|
+
const columnNames = columns.map((column) => column.name);
|
|
1487
|
+
const foreignColumnNames = foreignColumns.map((column) => column.name);
|
|
1488
|
+
const chunks = [
|
|
1489
|
+
this.table[TableName],
|
|
1490
|
+
...columnNames,
|
|
1491
|
+
foreignColumns[0].table[TableName],
|
|
1492
|
+
...foreignColumnNames
|
|
1493
|
+
];
|
|
1494
|
+
return name ?? `${chunks.join("_")}_fk`;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
// node_modules/drizzle-orm/sqlite-core/unique-constraint.js
|
|
1499
|
+
function uniqueKeyName2(table, columns) {
|
|
1500
|
+
return `${table[TableName]}_${columns.join("_")}_unique`;
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// node_modules/drizzle-orm/sqlite-core/columns/common.js
|
|
1504
|
+
class SQLiteColumnBuilder extends ColumnBuilder {
|
|
1505
|
+
static [entityKind] = "SQLiteColumnBuilder";
|
|
1506
|
+
foreignKeyConfigs = [];
|
|
1507
|
+
references(ref, actions = {}) {
|
|
1508
|
+
this.foreignKeyConfigs.push({ ref, actions });
|
|
1509
|
+
return this;
|
|
1510
|
+
}
|
|
1511
|
+
unique(name) {
|
|
1512
|
+
this.config.isUnique = true;
|
|
1513
|
+
this.config.uniqueName = name;
|
|
1514
|
+
return this;
|
|
1515
|
+
}
|
|
1516
|
+
generatedAlwaysAs(as, config) {
|
|
1517
|
+
this.config.generated = {
|
|
1518
|
+
as,
|
|
1519
|
+
type: "always",
|
|
1520
|
+
mode: config?.mode ?? "virtual"
|
|
1521
|
+
};
|
|
1522
|
+
return this;
|
|
1523
|
+
}
|
|
1524
|
+
buildForeignKeys(column, table) {
|
|
1525
|
+
return this.foreignKeyConfigs.map(({ ref, actions }) => {
|
|
1526
|
+
return ((ref2, actions2) => {
|
|
1527
|
+
const builder = new ForeignKeyBuilder(() => {
|
|
1528
|
+
const foreignColumn = ref2();
|
|
1529
|
+
return { columns: [column], foreignColumns: [foreignColumn] };
|
|
1530
|
+
});
|
|
1531
|
+
if (actions2.onUpdate) {
|
|
1532
|
+
builder.onUpdate(actions2.onUpdate);
|
|
1533
|
+
}
|
|
1534
|
+
if (actions2.onDelete) {
|
|
1535
|
+
builder.onDelete(actions2.onDelete);
|
|
1536
|
+
}
|
|
1537
|
+
return builder.build(table);
|
|
1538
|
+
})(ref, actions);
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
class SQLiteColumn extends Column {
|
|
1544
|
+
constructor(table, config) {
|
|
1545
|
+
if (!config.uniqueName) {
|
|
1546
|
+
config.uniqueName = uniqueKeyName2(table, [config.name]);
|
|
1547
|
+
}
|
|
1548
|
+
super(table, config);
|
|
1549
|
+
this.table = table;
|
|
1550
|
+
}
|
|
1551
|
+
static [entityKind] = "SQLiteColumn";
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// node_modules/drizzle-orm/sqlite-core/columns/blob.js
|
|
1555
|
+
class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
|
|
1556
|
+
static [entityKind] = "SQLiteBigIntBuilder";
|
|
1557
|
+
constructor(name) {
|
|
1558
|
+
super(name, "bigint", "SQLiteBigInt");
|
|
1559
|
+
}
|
|
1560
|
+
build(table) {
|
|
1561
|
+
return new SQLiteBigInt(table, this.config);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
class SQLiteBigInt extends SQLiteColumn {
|
|
1566
|
+
static [entityKind] = "SQLiteBigInt";
|
|
1567
|
+
getSQLType() {
|
|
1568
|
+
return "blob";
|
|
1569
|
+
}
|
|
1570
|
+
mapFromDriverValue(value) {
|
|
1571
|
+
if (Buffer.isBuffer(value)) {
|
|
1572
|
+
return BigInt(value.toString());
|
|
1573
|
+
}
|
|
1574
|
+
if (value instanceof ArrayBuffer) {
|
|
1575
|
+
const decoder = new TextDecoder;
|
|
1576
|
+
return BigInt(decoder.decode(value));
|
|
1577
|
+
}
|
|
1578
|
+
return BigInt(String.fromCodePoint(...value));
|
|
1579
|
+
}
|
|
1580
|
+
mapToDriverValue(value) {
|
|
1581
|
+
return Buffer.from(value.toString());
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
class SQLiteBlobJsonBuilder extends SQLiteColumnBuilder {
|
|
1586
|
+
static [entityKind] = "SQLiteBlobJsonBuilder";
|
|
1587
|
+
constructor(name) {
|
|
1588
|
+
super(name, "json", "SQLiteBlobJson");
|
|
1589
|
+
}
|
|
1590
|
+
build(table) {
|
|
1591
|
+
return new SQLiteBlobJson(table, this.config);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
class SQLiteBlobJson extends SQLiteColumn {
|
|
1596
|
+
static [entityKind] = "SQLiteBlobJson";
|
|
1597
|
+
getSQLType() {
|
|
1598
|
+
return "blob";
|
|
1599
|
+
}
|
|
1600
|
+
mapFromDriverValue(value) {
|
|
1601
|
+
if (Buffer.isBuffer(value)) {
|
|
1602
|
+
return JSON.parse(value.toString());
|
|
1603
|
+
}
|
|
1604
|
+
if (value instanceof ArrayBuffer) {
|
|
1605
|
+
const decoder = new TextDecoder;
|
|
1606
|
+
return JSON.parse(decoder.decode(value));
|
|
1607
|
+
}
|
|
1608
|
+
return JSON.parse(String.fromCodePoint(...value));
|
|
1609
|
+
}
|
|
1610
|
+
mapToDriverValue(value) {
|
|
1611
|
+
return Buffer.from(JSON.stringify(value));
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
class SQLiteBlobBufferBuilder extends SQLiteColumnBuilder {
|
|
1616
|
+
static [entityKind] = "SQLiteBlobBufferBuilder";
|
|
1617
|
+
constructor(name) {
|
|
1618
|
+
super(name, "buffer", "SQLiteBlobBuffer");
|
|
1619
|
+
}
|
|
1620
|
+
build(table) {
|
|
1621
|
+
return new SQLiteBlobBuffer(table, this.config);
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
class SQLiteBlobBuffer extends SQLiteColumn {
|
|
1626
|
+
static [entityKind] = "SQLiteBlobBuffer";
|
|
1627
|
+
getSQLType() {
|
|
1628
|
+
return "blob";
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
function blob(a, b) {
|
|
1632
|
+
const { name, config } = getColumnNameAndConfig(a, b);
|
|
1633
|
+
if (config?.mode === "json") {
|
|
1634
|
+
return new SQLiteBlobJsonBuilder(name);
|
|
1635
|
+
}
|
|
1636
|
+
if (config?.mode === "bigint") {
|
|
1637
|
+
return new SQLiteBigIntBuilder(name);
|
|
1638
|
+
}
|
|
1639
|
+
return new SQLiteBlobBufferBuilder(name);
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// node_modules/drizzle-orm/sqlite-core/columns/custom.js
|
|
1643
|
+
class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
|
|
1644
|
+
static [entityKind] = "SQLiteCustomColumnBuilder";
|
|
1645
|
+
constructor(name, fieldConfig, customTypeParams) {
|
|
1646
|
+
super(name, "custom", "SQLiteCustomColumn");
|
|
1647
|
+
this.config.fieldConfig = fieldConfig;
|
|
1648
|
+
this.config.customTypeParams = customTypeParams;
|
|
1649
|
+
}
|
|
1650
|
+
build(table) {
|
|
1651
|
+
return new SQLiteCustomColumn(table, this.config);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
class SQLiteCustomColumn extends SQLiteColumn {
|
|
1656
|
+
static [entityKind] = "SQLiteCustomColumn";
|
|
1657
|
+
sqlName;
|
|
1658
|
+
mapTo;
|
|
1659
|
+
mapFrom;
|
|
1660
|
+
constructor(table, config) {
|
|
1661
|
+
super(table, config);
|
|
1662
|
+
this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
|
|
1663
|
+
this.mapTo = config.customTypeParams.toDriver;
|
|
1664
|
+
this.mapFrom = config.customTypeParams.fromDriver;
|
|
1665
|
+
}
|
|
1666
|
+
getSQLType() {
|
|
1667
|
+
return this.sqlName;
|
|
1668
|
+
}
|
|
1669
|
+
mapFromDriverValue(value) {
|
|
1670
|
+
return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
|
|
1671
|
+
}
|
|
1672
|
+
mapToDriverValue(value) {
|
|
1673
|
+
return typeof this.mapTo === "function" ? this.mapTo(value) : value;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
function customType(customTypeParams) {
|
|
1677
|
+
return (a, b) => {
|
|
1678
|
+
const { name, config } = getColumnNameAndConfig(a, b);
|
|
1679
|
+
return new SQLiteCustomColumnBuilder(name, config, customTypeParams);
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
// node_modules/drizzle-orm/sqlite-core/columns/integer.js
|
|
1684
|
+
class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
|
|
1685
|
+
static [entityKind] = "SQLiteBaseIntegerBuilder";
|
|
1686
|
+
constructor(name, dataType, columnType) {
|
|
1687
|
+
super(name, dataType, columnType);
|
|
1688
|
+
this.config.autoIncrement = false;
|
|
1689
|
+
}
|
|
1690
|
+
primaryKey(config) {
|
|
1691
|
+
if (config?.autoIncrement) {
|
|
1692
|
+
this.config.autoIncrement = true;
|
|
1693
|
+
}
|
|
1694
|
+
this.config.hasDefault = true;
|
|
1695
|
+
return super.primaryKey();
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
class SQLiteBaseInteger extends SQLiteColumn {
|
|
1700
|
+
static [entityKind] = "SQLiteBaseInteger";
|
|
1701
|
+
autoIncrement = this.config.autoIncrement;
|
|
1702
|
+
getSQLType() {
|
|
1703
|
+
return "integer";
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
class SQLiteIntegerBuilder extends SQLiteBaseIntegerBuilder {
|
|
1708
|
+
static [entityKind] = "SQLiteIntegerBuilder";
|
|
1709
|
+
constructor(name) {
|
|
1710
|
+
super(name, "number", "SQLiteInteger");
|
|
1711
|
+
}
|
|
1712
|
+
build(table) {
|
|
1713
|
+
return new SQLiteInteger(table, this.config);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
class SQLiteInteger extends SQLiteBaseInteger {
|
|
1718
|
+
static [entityKind] = "SQLiteInteger";
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
class SQLiteTimestampBuilder extends SQLiteBaseIntegerBuilder {
|
|
1722
|
+
static [entityKind] = "SQLiteTimestampBuilder";
|
|
1723
|
+
constructor(name, mode) {
|
|
1724
|
+
super(name, "date", "SQLiteTimestamp");
|
|
1725
|
+
this.config.mode = mode;
|
|
1726
|
+
}
|
|
1727
|
+
defaultNow() {
|
|
1728
|
+
return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
|
|
1729
|
+
}
|
|
1730
|
+
build(table) {
|
|
1731
|
+
return new SQLiteTimestamp(table, this.config);
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
class SQLiteTimestamp extends SQLiteBaseInteger {
|
|
1736
|
+
static [entityKind] = "SQLiteTimestamp";
|
|
1737
|
+
mode = this.config.mode;
|
|
1738
|
+
mapFromDriverValue(value) {
|
|
1739
|
+
if (this.config.mode === "timestamp") {
|
|
1740
|
+
return new Date(value * 1000);
|
|
1741
|
+
}
|
|
1742
|
+
return new Date(value);
|
|
1743
|
+
}
|
|
1744
|
+
mapToDriverValue(value) {
|
|
1745
|
+
const unix = value.getTime();
|
|
1746
|
+
if (this.config.mode === "timestamp") {
|
|
1747
|
+
return Math.floor(unix / 1000);
|
|
1748
|
+
}
|
|
1749
|
+
return unix;
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
class SQLiteBooleanBuilder extends SQLiteBaseIntegerBuilder {
|
|
1754
|
+
static [entityKind] = "SQLiteBooleanBuilder";
|
|
1755
|
+
constructor(name, mode) {
|
|
1756
|
+
super(name, "boolean", "SQLiteBoolean");
|
|
1757
|
+
this.config.mode = mode;
|
|
1758
|
+
}
|
|
1759
|
+
build(table) {
|
|
1760
|
+
return new SQLiteBoolean(table, this.config);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
class SQLiteBoolean extends SQLiteBaseInteger {
|
|
1765
|
+
static [entityKind] = "SQLiteBoolean";
|
|
1766
|
+
mode = this.config.mode;
|
|
1767
|
+
mapFromDriverValue(value) {
|
|
1768
|
+
return Number(value) === 1;
|
|
1769
|
+
}
|
|
1770
|
+
mapToDriverValue(value) {
|
|
1771
|
+
return value ? 1 : 0;
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
function integer(a, b) {
|
|
1775
|
+
const { name, config } = getColumnNameAndConfig(a, b);
|
|
1776
|
+
if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
|
|
1777
|
+
return new SQLiteTimestampBuilder(name, config.mode);
|
|
1778
|
+
}
|
|
1779
|
+
if (config?.mode === "boolean") {
|
|
1780
|
+
return new SQLiteBooleanBuilder(name, config.mode);
|
|
1781
|
+
}
|
|
1782
|
+
return new SQLiteIntegerBuilder(name);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
// node_modules/drizzle-orm/sqlite-core/columns/numeric.js
|
|
1786
|
+
class SQLiteNumericBuilder extends SQLiteColumnBuilder {
|
|
1787
|
+
static [entityKind] = "SQLiteNumericBuilder";
|
|
1788
|
+
constructor(name) {
|
|
1789
|
+
super(name, "string", "SQLiteNumeric");
|
|
1790
|
+
}
|
|
1791
|
+
build(table) {
|
|
1792
|
+
return new SQLiteNumeric(table, this.config);
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
class SQLiteNumeric extends SQLiteColumn {
|
|
1797
|
+
static [entityKind] = "SQLiteNumeric";
|
|
1798
|
+
getSQLType() {
|
|
1799
|
+
return "numeric";
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
function numeric(name) {
|
|
1803
|
+
return new SQLiteNumericBuilder(name ?? "");
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
// node_modules/drizzle-orm/sqlite-core/columns/real.js
|
|
1807
|
+
class SQLiteRealBuilder extends SQLiteColumnBuilder {
|
|
1808
|
+
static [entityKind] = "SQLiteRealBuilder";
|
|
1809
|
+
constructor(name) {
|
|
1810
|
+
super(name, "number", "SQLiteReal");
|
|
1811
|
+
}
|
|
1812
|
+
build(table) {
|
|
1813
|
+
return new SQLiteReal(table, this.config);
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
class SQLiteReal extends SQLiteColumn {
|
|
1818
|
+
static [entityKind] = "SQLiteReal";
|
|
1819
|
+
getSQLType() {
|
|
1820
|
+
return "real";
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
function real(name) {
|
|
1824
|
+
return new SQLiteRealBuilder(name ?? "");
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// node_modules/drizzle-orm/sqlite-core/columns/text.js
|
|
1828
|
+
class SQLiteTextBuilder extends SQLiteColumnBuilder {
|
|
1829
|
+
static [entityKind] = "SQLiteTextBuilder";
|
|
1830
|
+
constructor(name, config) {
|
|
1831
|
+
super(name, "string", "SQLiteText");
|
|
1832
|
+
this.config.enumValues = config.enum;
|
|
1833
|
+
this.config.length = config.length;
|
|
1834
|
+
}
|
|
1835
|
+
build(table) {
|
|
1836
|
+
return new SQLiteText(table, this.config);
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
class SQLiteText extends SQLiteColumn {
|
|
1841
|
+
static [entityKind] = "SQLiteText";
|
|
1842
|
+
enumValues = this.config.enumValues;
|
|
1843
|
+
length = this.config.length;
|
|
1844
|
+
constructor(table, config) {
|
|
1845
|
+
super(table, config);
|
|
1846
|
+
}
|
|
1847
|
+
getSQLType() {
|
|
1848
|
+
return `text${this.config.length ? `(${this.config.length})` : ""}`;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
class SQLiteTextJsonBuilder extends SQLiteColumnBuilder {
|
|
1853
|
+
static [entityKind] = "SQLiteTextJsonBuilder";
|
|
1854
|
+
constructor(name) {
|
|
1855
|
+
super(name, "json", "SQLiteTextJson");
|
|
1856
|
+
}
|
|
1857
|
+
build(table) {
|
|
1858
|
+
return new SQLiteTextJson(table, this.config);
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
class SQLiteTextJson extends SQLiteColumn {
|
|
1863
|
+
static [entityKind] = "SQLiteTextJson";
|
|
1864
|
+
getSQLType() {
|
|
1865
|
+
return "text";
|
|
1866
|
+
}
|
|
1867
|
+
mapFromDriverValue(value) {
|
|
1868
|
+
return JSON.parse(value);
|
|
1869
|
+
}
|
|
1870
|
+
mapToDriverValue(value) {
|
|
1871
|
+
return JSON.stringify(value);
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
function text(a, b = {}) {
|
|
1875
|
+
const { name, config } = getColumnNameAndConfig(a, b);
|
|
1876
|
+
if (config.mode === "json") {
|
|
1877
|
+
return new SQLiteTextJsonBuilder(name);
|
|
1878
|
+
}
|
|
1879
|
+
return new SQLiteTextBuilder(name, config);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// node_modules/drizzle-orm/sqlite-core/columns/all.js
|
|
1883
|
+
function getSQLiteColumnBuilders() {
|
|
1884
|
+
return {
|
|
1885
|
+
blob,
|
|
1886
|
+
customType,
|
|
1887
|
+
integer,
|
|
1888
|
+
numeric,
|
|
1889
|
+
real,
|
|
1890
|
+
text
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
// node_modules/drizzle-orm/sqlite-core/table.js
|
|
1895
|
+
var InlineForeignKeys2 = Symbol.for("drizzle:SQLiteInlineForeignKeys");
|
|
1896
|
+
|
|
1897
|
+
class SQLiteTable extends Table {
|
|
1898
|
+
static [entityKind] = "SQLiteTable";
|
|
1899
|
+
static Symbol = Object.assign({}, Table.Symbol, {
|
|
1900
|
+
InlineForeignKeys: InlineForeignKeys2
|
|
1901
|
+
});
|
|
1902
|
+
[Table.Symbol.Columns];
|
|
1903
|
+
[InlineForeignKeys2] = [];
|
|
1904
|
+
[Table.Symbol.ExtraConfigBuilder] = undefined;
|
|
1905
|
+
}
|
|
1906
|
+
function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
|
|
1907
|
+
const rawTable = new SQLiteTable(name, schema, baseName);
|
|
1908
|
+
const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
|
|
1909
|
+
const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
|
|
1910
|
+
const colBuilder = colBuilderBase;
|
|
1911
|
+
colBuilder.setName(name2);
|
|
1912
|
+
const column = colBuilder.build(rawTable);
|
|
1913
|
+
rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable));
|
|
1914
|
+
return [name2, column];
|
|
1915
|
+
}));
|
|
1916
|
+
const table = Object.assign(rawTable, builtColumns);
|
|
1917
|
+
table[Table.Symbol.Columns] = builtColumns;
|
|
1918
|
+
table[Table.Symbol.ExtraConfigColumns] = builtColumns;
|
|
1919
|
+
if (extraConfig) {
|
|
1920
|
+
table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
|
|
1921
|
+
}
|
|
1922
|
+
return table;
|
|
1923
|
+
}
|
|
1924
|
+
var sqliteTable = (name, columns, extraConfig) => {
|
|
1925
|
+
return sqliteTableBase(name, columns, extraConfig);
|
|
1926
|
+
};
|
|
1927
|
+
|
|
1928
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
|
|
1929
|
+
class SQLiteDeleteBase extends QueryPromise {
|
|
1930
|
+
constructor(table, session, dialect, withList) {
|
|
1931
|
+
super();
|
|
1932
|
+
this.table = table;
|
|
1933
|
+
this.session = session;
|
|
1934
|
+
this.dialect = dialect;
|
|
1935
|
+
this.config = { table, withList };
|
|
1936
|
+
}
|
|
1937
|
+
static [entityKind] = "SQLiteDelete";
|
|
1938
|
+
config;
|
|
1939
|
+
where(where) {
|
|
1940
|
+
this.config.where = where;
|
|
1941
|
+
return this;
|
|
1942
|
+
}
|
|
1943
|
+
orderBy(...columns) {
|
|
1944
|
+
if (typeof columns[0] === "function") {
|
|
1945
|
+
const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
|
|
1946
|
+
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
1947
|
+
this.config.orderBy = orderByArray;
|
|
1948
|
+
} else {
|
|
1949
|
+
const orderByArray = columns;
|
|
1950
|
+
this.config.orderBy = orderByArray;
|
|
1951
|
+
}
|
|
1952
|
+
return this;
|
|
1953
|
+
}
|
|
1954
|
+
limit(limit) {
|
|
1955
|
+
this.config.limit = limit;
|
|
1956
|
+
return this;
|
|
1957
|
+
}
|
|
1958
|
+
returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
|
|
1959
|
+
this.config.returning = orderSelectedFields(fields);
|
|
1960
|
+
return this;
|
|
1961
|
+
}
|
|
1962
|
+
getSQL() {
|
|
1963
|
+
return this.dialect.buildDeleteQuery(this.config);
|
|
1964
|
+
}
|
|
1965
|
+
toSQL() {
|
|
1966
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
1967
|
+
return rest;
|
|
1968
|
+
}
|
|
1969
|
+
_prepare(isOneTimeQuery = true) {
|
|
1970
|
+
return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true);
|
|
1971
|
+
}
|
|
1972
|
+
prepare() {
|
|
1973
|
+
return this._prepare(false);
|
|
1974
|
+
}
|
|
1975
|
+
run = (placeholderValues) => {
|
|
1976
|
+
return this._prepare().run(placeholderValues);
|
|
1977
|
+
};
|
|
1978
|
+
all = (placeholderValues) => {
|
|
1979
|
+
return this._prepare().all(placeholderValues);
|
|
1980
|
+
};
|
|
1981
|
+
get = (placeholderValues) => {
|
|
1982
|
+
return this._prepare().get(placeholderValues);
|
|
1983
|
+
};
|
|
1984
|
+
values = (placeholderValues) => {
|
|
1985
|
+
return this._prepare().values(placeholderValues);
|
|
1986
|
+
};
|
|
1987
|
+
async execute(placeholderValues) {
|
|
1988
|
+
return this._prepare().execute(placeholderValues);
|
|
1989
|
+
}
|
|
1990
|
+
$dynamic() {
|
|
1991
|
+
return this;
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
// node_modules/drizzle-orm/casing.js
|
|
1996
|
+
function toSnakeCase(input) {
|
|
1997
|
+
const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
|
|
1998
|
+
return words.map((word) => word.toLowerCase()).join("_");
|
|
1999
|
+
}
|
|
2000
|
+
function toCamelCase(input) {
|
|
2001
|
+
const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
|
|
2002
|
+
return words.reduce((acc, word, i) => {
|
|
2003
|
+
const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
|
|
2004
|
+
return acc + formattedWord;
|
|
2005
|
+
}, "");
|
|
2006
|
+
}
|
|
2007
|
+
function noopCase(input) {
|
|
2008
|
+
return input;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
class CasingCache {
|
|
2012
|
+
static [entityKind] = "CasingCache";
|
|
2013
|
+
cache = {};
|
|
2014
|
+
cachedTables = {};
|
|
2015
|
+
convert;
|
|
2016
|
+
constructor(casing) {
|
|
2017
|
+
this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
|
|
2018
|
+
}
|
|
2019
|
+
getColumnCasing(column) {
|
|
2020
|
+
if (!column.keyAsName)
|
|
2021
|
+
return column.name;
|
|
2022
|
+
const schema = column.table[Table.Symbol.Schema] ?? "public";
|
|
2023
|
+
const tableName = column.table[Table.Symbol.OriginalName];
|
|
2024
|
+
const key = `${schema}.${tableName}.${column.name}`;
|
|
2025
|
+
if (!this.cache[key]) {
|
|
2026
|
+
this.cacheTable(column.table);
|
|
2027
|
+
}
|
|
2028
|
+
return this.cache[key];
|
|
2029
|
+
}
|
|
2030
|
+
cacheTable(table) {
|
|
2031
|
+
const schema = table[Table.Symbol.Schema] ?? "public";
|
|
2032
|
+
const tableName = table[Table.Symbol.OriginalName];
|
|
2033
|
+
const tableKey = `${schema}.${tableName}`;
|
|
2034
|
+
if (!this.cachedTables[tableKey]) {
|
|
2035
|
+
for (const column of Object.values(table[Table.Symbol.Columns])) {
|
|
2036
|
+
const columnKey = `${tableKey}.${column.name}`;
|
|
2037
|
+
this.cache[columnKey] = this.convert(column.name);
|
|
2038
|
+
}
|
|
2039
|
+
this.cachedTables[tableKey] = true;
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
clearCache() {
|
|
2043
|
+
this.cache = {};
|
|
2044
|
+
this.cachedTables = {};
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
// node_modules/drizzle-orm/sqlite-core/view-base.js
|
|
2049
|
+
class SQLiteViewBase extends View {
|
|
2050
|
+
static [entityKind] = "SQLiteViewBase";
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
// node_modules/drizzle-orm/sqlite-core/dialect.js
|
|
2054
|
+
class SQLiteDialect {
|
|
2055
|
+
static [entityKind] = "SQLiteDialect";
|
|
2056
|
+
casing;
|
|
2057
|
+
constructor(config) {
|
|
2058
|
+
this.casing = new CasingCache(config?.casing);
|
|
2059
|
+
}
|
|
2060
|
+
escapeName(name) {
|
|
2061
|
+
return `"${name}"`;
|
|
2062
|
+
}
|
|
2063
|
+
escapeParam(_num) {
|
|
2064
|
+
return "?";
|
|
2065
|
+
}
|
|
2066
|
+
escapeString(str) {
|
|
2067
|
+
return `'${str.replace(/'/g, "''")}'`;
|
|
2068
|
+
}
|
|
2069
|
+
buildWithCTE(queries) {
|
|
2070
|
+
if (!queries?.length)
|
|
2071
|
+
return;
|
|
2072
|
+
const withSqlChunks = [sql`with `];
|
|
2073
|
+
for (const [i, w] of queries.entries()) {
|
|
2074
|
+
withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
|
|
2075
|
+
if (i < queries.length - 1) {
|
|
2076
|
+
withSqlChunks.push(sql`, `);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
withSqlChunks.push(sql` `);
|
|
2080
|
+
return sql.join(withSqlChunks);
|
|
2081
|
+
}
|
|
2082
|
+
buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
|
|
2083
|
+
const withSql = this.buildWithCTE(withList);
|
|
2084
|
+
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
|
|
2085
|
+
const whereSql = where ? sql` where ${where}` : undefined;
|
|
2086
|
+
const orderBySql = this.buildOrderBy(orderBy);
|
|
2087
|
+
const limitSql = this.buildLimit(limit);
|
|
2088
|
+
return sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`;
|
|
2089
|
+
}
|
|
2090
|
+
buildUpdateSet(table, set) {
|
|
2091
|
+
const tableColumns = table[Table.Symbol.Columns];
|
|
2092
|
+
const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined);
|
|
2093
|
+
const setSize = columnNames.length;
|
|
2094
|
+
return sql.join(columnNames.flatMap((colName, i) => {
|
|
2095
|
+
const col = tableColumns[colName];
|
|
2096
|
+
const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
|
|
2097
|
+
const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
|
|
2098
|
+
if (i < setSize - 1) {
|
|
2099
|
+
return [res, sql.raw(", ")];
|
|
2100
|
+
}
|
|
2101
|
+
return [res];
|
|
2102
|
+
}));
|
|
2103
|
+
}
|
|
2104
|
+
buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) {
|
|
2105
|
+
const withSql = this.buildWithCTE(withList);
|
|
2106
|
+
const setSql = this.buildUpdateSet(table, set);
|
|
2107
|
+
const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
|
|
2108
|
+
const joinsSql = this.buildJoins(joins);
|
|
2109
|
+
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
|
|
2110
|
+
const whereSql = where ? sql` where ${where}` : undefined;
|
|
2111
|
+
const orderBySql = this.buildOrderBy(orderBy);
|
|
2112
|
+
const limitSql = this.buildLimit(limit);
|
|
2113
|
+
return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
|
|
2114
|
+
}
|
|
2115
|
+
buildSelection(fields, { isSingleTable = false } = {}) {
|
|
2116
|
+
const columnsLen = fields.length;
|
|
2117
|
+
const chunks = fields.flatMap(({ field }, i) => {
|
|
2118
|
+
const chunk = [];
|
|
2119
|
+
if (is(field, SQL.Aliased) && field.isSelectionField) {
|
|
2120
|
+
chunk.push(sql.identifier(field.fieldAlias));
|
|
2121
|
+
} else if (is(field, SQL.Aliased) || is(field, SQL)) {
|
|
2122
|
+
const query = is(field, SQL.Aliased) ? field.sql : field;
|
|
2123
|
+
if (isSingleTable) {
|
|
2124
|
+
chunk.push(new SQL(query.queryChunks.map((c) => {
|
|
2125
|
+
if (is(c, Column)) {
|
|
2126
|
+
return sql.identifier(this.casing.getColumnCasing(c));
|
|
2127
|
+
}
|
|
2128
|
+
return c;
|
|
2129
|
+
})));
|
|
2130
|
+
} else {
|
|
2131
|
+
chunk.push(query);
|
|
2132
|
+
}
|
|
2133
|
+
if (is(field, SQL.Aliased)) {
|
|
2134
|
+
chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
|
|
2135
|
+
}
|
|
2136
|
+
} else if (is(field, Column)) {
|
|
2137
|
+
const tableName = field.table[Table.Symbol.Name];
|
|
2138
|
+
if (isSingleTable) {
|
|
2139
|
+
chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
|
|
2140
|
+
} else {
|
|
2141
|
+
chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
if (i < columnsLen - 1) {
|
|
2145
|
+
chunk.push(sql`, `);
|
|
2146
|
+
}
|
|
2147
|
+
return chunk;
|
|
2148
|
+
});
|
|
2149
|
+
return sql.join(chunks);
|
|
2150
|
+
}
|
|
2151
|
+
buildJoins(joins) {
|
|
2152
|
+
if (!joins || joins.length === 0) {
|
|
2153
|
+
return;
|
|
2154
|
+
}
|
|
2155
|
+
const joinsArray = [];
|
|
2156
|
+
if (joins) {
|
|
2157
|
+
for (const [index, joinMeta] of joins.entries()) {
|
|
2158
|
+
if (index === 0) {
|
|
2159
|
+
joinsArray.push(sql` `);
|
|
2160
|
+
}
|
|
2161
|
+
const table = joinMeta.table;
|
|
2162
|
+
if (is(table, SQLiteTable)) {
|
|
2163
|
+
const tableName = table[SQLiteTable.Symbol.Name];
|
|
2164
|
+
const tableSchema = table[SQLiteTable.Symbol.Schema];
|
|
2165
|
+
const origTableName = table[SQLiteTable.Symbol.OriginalName];
|
|
2166
|
+
const alias = tableName === origTableName ? undefined : joinMeta.alias;
|
|
2167
|
+
joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
|
|
2168
|
+
} else {
|
|
2169
|
+
joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table} on ${joinMeta.on}`);
|
|
2170
|
+
}
|
|
2171
|
+
if (index < joins.length - 1) {
|
|
2172
|
+
joinsArray.push(sql` `);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
return sql.join(joinsArray);
|
|
2177
|
+
}
|
|
2178
|
+
buildLimit(limit) {
|
|
2179
|
+
return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
|
|
2180
|
+
}
|
|
2181
|
+
buildOrderBy(orderBy) {
|
|
2182
|
+
const orderByList = [];
|
|
2183
|
+
if (orderBy) {
|
|
2184
|
+
for (const [index, orderByValue] of orderBy.entries()) {
|
|
2185
|
+
orderByList.push(orderByValue);
|
|
2186
|
+
if (index < orderBy.length - 1) {
|
|
2187
|
+
orderByList.push(sql`, `);
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : undefined;
|
|
2192
|
+
}
|
|
2193
|
+
buildFromTable(table) {
|
|
2194
|
+
if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {
|
|
2195
|
+
return sql`${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`;
|
|
2196
|
+
}
|
|
2197
|
+
return table;
|
|
2198
|
+
}
|
|
2199
|
+
buildSelectQuery({
|
|
2200
|
+
withList,
|
|
2201
|
+
fields,
|
|
2202
|
+
fieldsFlat,
|
|
2203
|
+
where,
|
|
2204
|
+
having,
|
|
2205
|
+
table,
|
|
2206
|
+
joins,
|
|
2207
|
+
orderBy,
|
|
2208
|
+
groupBy,
|
|
2209
|
+
limit,
|
|
2210
|
+
offset,
|
|
2211
|
+
distinct,
|
|
2212
|
+
setOperators
|
|
2213
|
+
}) {
|
|
2214
|
+
const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
|
|
2215
|
+
for (const f of fieldsList) {
|
|
2216
|
+
if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, SQLiteViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) {
|
|
2217
|
+
const tableName = getTableName(f.field.table);
|
|
2218
|
+
throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
const isSingleTable = !joins || joins.length === 0;
|
|
2222
|
+
const withSql = this.buildWithCTE(withList);
|
|
2223
|
+
const distinctSql = distinct ? sql` distinct` : undefined;
|
|
2224
|
+
const selection = this.buildSelection(fieldsList, { isSingleTable });
|
|
2225
|
+
const tableSql = this.buildFromTable(table);
|
|
2226
|
+
const joinsSql = this.buildJoins(joins);
|
|
2227
|
+
const whereSql = where ? sql` where ${where}` : undefined;
|
|
2228
|
+
const havingSql = having ? sql` having ${having}` : undefined;
|
|
2229
|
+
const groupByList = [];
|
|
2230
|
+
if (groupBy) {
|
|
2231
|
+
for (const [index, groupByValue] of groupBy.entries()) {
|
|
2232
|
+
groupByList.push(groupByValue);
|
|
2233
|
+
if (index < groupBy.length - 1) {
|
|
2234
|
+
groupByList.push(sql`, `);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : undefined;
|
|
2239
|
+
const orderBySql = this.buildOrderBy(orderBy);
|
|
2240
|
+
const limitSql = this.buildLimit(limit);
|
|
2241
|
+
const offsetSql = offset ? sql` offset ${offset}` : undefined;
|
|
2242
|
+
const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
|
|
2243
|
+
if (setOperators.length > 0) {
|
|
2244
|
+
return this.buildSetOperations(finalQuery, setOperators);
|
|
2245
|
+
}
|
|
2246
|
+
return finalQuery;
|
|
2247
|
+
}
|
|
2248
|
+
buildSetOperations(leftSelect, setOperators) {
|
|
2249
|
+
const [setOperator, ...rest] = setOperators;
|
|
2250
|
+
if (!setOperator) {
|
|
2251
|
+
throw new Error("Cannot pass undefined values to any set operator");
|
|
2252
|
+
}
|
|
2253
|
+
if (rest.length === 0) {
|
|
2254
|
+
return this.buildSetOperationQuery({ leftSelect, setOperator });
|
|
2255
|
+
}
|
|
2256
|
+
return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest);
|
|
2257
|
+
}
|
|
2258
|
+
buildSetOperationQuery({
|
|
2259
|
+
leftSelect,
|
|
2260
|
+
setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
|
|
2261
|
+
}) {
|
|
2262
|
+
const leftChunk = sql`${leftSelect.getSQL()} `;
|
|
2263
|
+
const rightChunk = sql`${rightSelect.getSQL()}`;
|
|
2264
|
+
let orderBySql;
|
|
2265
|
+
if (orderBy && orderBy.length > 0) {
|
|
2266
|
+
const orderByValues = [];
|
|
2267
|
+
for (const singleOrderBy of orderBy) {
|
|
2268
|
+
if (is(singleOrderBy, SQLiteColumn)) {
|
|
2269
|
+
orderByValues.push(sql.identifier(singleOrderBy.name));
|
|
2270
|
+
} else if (is(singleOrderBy, SQL)) {
|
|
2271
|
+
for (let i = 0;i < singleOrderBy.queryChunks.length; i++) {
|
|
2272
|
+
const chunk = singleOrderBy.queryChunks[i];
|
|
2273
|
+
if (is(chunk, SQLiteColumn)) {
|
|
2274
|
+
singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
orderByValues.push(sql`${singleOrderBy}`);
|
|
2278
|
+
} else {
|
|
2279
|
+
orderByValues.push(sql`${singleOrderBy}`);
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
|
|
2283
|
+
}
|
|
2284
|
+
const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
|
|
2285
|
+
const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
|
|
2286
|
+
const offsetSql = offset ? sql` offset ${offset}` : undefined;
|
|
2287
|
+
return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
|
|
2288
|
+
}
|
|
2289
|
+
buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) {
|
|
2290
|
+
const valuesSqlList = [];
|
|
2291
|
+
const columns = table[Table.Symbol.Columns];
|
|
2292
|
+
const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
|
|
2293
|
+
const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
|
|
2294
|
+
if (select) {
|
|
2295
|
+
const select2 = valuesOrSelect;
|
|
2296
|
+
if (is(select2, SQL)) {
|
|
2297
|
+
valuesSqlList.push(select2);
|
|
2298
|
+
} else {
|
|
2299
|
+
valuesSqlList.push(select2.getSQL());
|
|
2300
|
+
}
|
|
2301
|
+
} else {
|
|
2302
|
+
const values = valuesOrSelect;
|
|
2303
|
+
valuesSqlList.push(sql.raw("values "));
|
|
2304
|
+
for (const [valueIndex, value] of values.entries()) {
|
|
2305
|
+
const valueList = [];
|
|
2306
|
+
for (const [fieldName, col] of colEntries) {
|
|
2307
|
+
const colValue = value[fieldName];
|
|
2308
|
+
if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) {
|
|
2309
|
+
let defaultValue;
|
|
2310
|
+
if (col.default !== null && col.default !== undefined) {
|
|
2311
|
+
defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
|
|
2312
|
+
} else if (col.defaultFn !== undefined) {
|
|
2313
|
+
const defaultFnResult = col.defaultFn();
|
|
2314
|
+
defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
|
|
2315
|
+
} else if (!col.default && col.onUpdateFn !== undefined) {
|
|
2316
|
+
const onUpdateFnResult = col.onUpdateFn();
|
|
2317
|
+
defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
|
|
2318
|
+
} else {
|
|
2319
|
+
defaultValue = sql`null`;
|
|
2320
|
+
}
|
|
2321
|
+
valueList.push(defaultValue);
|
|
2322
|
+
} else {
|
|
2323
|
+
valueList.push(colValue);
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
valuesSqlList.push(valueList);
|
|
2327
|
+
if (valueIndex < values.length - 1) {
|
|
2328
|
+
valuesSqlList.push(sql`, `);
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
const withSql = this.buildWithCTE(withList);
|
|
2333
|
+
const valuesSql = sql.join(valuesSqlList);
|
|
2334
|
+
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
|
|
2335
|
+
const onConflictSql = onConflict?.length ? sql.join(onConflict) : undefined;
|
|
2336
|
+
return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
|
|
2337
|
+
}
|
|
2338
|
+
sqlToQuery(sql2, invokeSource) {
|
|
2339
|
+
return sql2.toQuery({
|
|
2340
|
+
casing: this.casing,
|
|
2341
|
+
escapeName: this.escapeName,
|
|
2342
|
+
escapeParam: this.escapeParam,
|
|
2343
|
+
escapeString: this.escapeString,
|
|
2344
|
+
invokeSource
|
|
2345
|
+
});
|
|
2346
|
+
}
|
|
2347
|
+
buildRelationalQuery({
|
|
2348
|
+
fullSchema,
|
|
2349
|
+
schema,
|
|
2350
|
+
tableNamesMap,
|
|
2351
|
+
table,
|
|
2352
|
+
tableConfig,
|
|
2353
|
+
queryConfig: config,
|
|
2354
|
+
tableAlias,
|
|
2355
|
+
nestedQueryRelation,
|
|
2356
|
+
joinOn
|
|
2357
|
+
}) {
|
|
2358
|
+
let selection = [];
|
|
2359
|
+
let limit, offset, orderBy = [], where;
|
|
2360
|
+
const joins = [];
|
|
2361
|
+
if (config === true) {
|
|
2362
|
+
const selectionEntries = Object.entries(tableConfig.columns);
|
|
2363
|
+
selection = selectionEntries.map(([key, value]) => ({
|
|
2364
|
+
dbKey: value.name,
|
|
2365
|
+
tsKey: key,
|
|
2366
|
+
field: aliasedTableColumn(value, tableAlias),
|
|
2367
|
+
relationTableTsKey: undefined,
|
|
2368
|
+
isJson: false,
|
|
2369
|
+
selection: []
|
|
2370
|
+
}));
|
|
2371
|
+
} else {
|
|
2372
|
+
const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
|
|
2373
|
+
if (config.where) {
|
|
2374
|
+
const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
|
|
2375
|
+
where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
|
|
2376
|
+
}
|
|
2377
|
+
const fieldsSelection = [];
|
|
2378
|
+
let selectedColumns = [];
|
|
2379
|
+
if (config.columns) {
|
|
2380
|
+
let isIncludeMode = false;
|
|
2381
|
+
for (const [field, value] of Object.entries(config.columns)) {
|
|
2382
|
+
if (value === undefined) {
|
|
2383
|
+
continue;
|
|
2384
|
+
}
|
|
2385
|
+
if (field in tableConfig.columns) {
|
|
2386
|
+
if (!isIncludeMode && value === true) {
|
|
2387
|
+
isIncludeMode = true;
|
|
2388
|
+
}
|
|
2389
|
+
selectedColumns.push(field);
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
if (selectedColumns.length > 0) {
|
|
2393
|
+
selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
|
|
2394
|
+
}
|
|
2395
|
+
} else {
|
|
2396
|
+
selectedColumns = Object.keys(tableConfig.columns);
|
|
2397
|
+
}
|
|
2398
|
+
for (const field of selectedColumns) {
|
|
2399
|
+
const column = tableConfig.columns[field];
|
|
2400
|
+
fieldsSelection.push({ tsKey: field, value: column });
|
|
2401
|
+
}
|
|
2402
|
+
let selectedRelations = [];
|
|
2403
|
+
if (config.with) {
|
|
2404
|
+
selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
|
|
2405
|
+
}
|
|
2406
|
+
let extras;
|
|
2407
|
+
if (config.extras) {
|
|
2408
|
+
extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
|
|
2409
|
+
for (const [tsKey, value] of Object.entries(extras)) {
|
|
2410
|
+
fieldsSelection.push({
|
|
2411
|
+
tsKey,
|
|
2412
|
+
value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
|
|
2413
|
+
});
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
for (const { tsKey, value } of fieldsSelection) {
|
|
2417
|
+
selection.push({
|
|
2418
|
+
dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
|
|
2419
|
+
tsKey,
|
|
2420
|
+
field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
|
|
2421
|
+
relationTableTsKey: undefined,
|
|
2422
|
+
isJson: false,
|
|
2423
|
+
selection: []
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
|
|
2427
|
+
if (!Array.isArray(orderByOrig)) {
|
|
2428
|
+
orderByOrig = [orderByOrig];
|
|
2429
|
+
}
|
|
2430
|
+
orderBy = orderByOrig.map((orderByValue) => {
|
|
2431
|
+
if (is(orderByValue, Column)) {
|
|
2432
|
+
return aliasedTableColumn(orderByValue, tableAlias);
|
|
2433
|
+
}
|
|
2434
|
+
return mapColumnsInSQLToAlias(orderByValue, tableAlias);
|
|
2435
|
+
});
|
|
2436
|
+
limit = config.limit;
|
|
2437
|
+
offset = config.offset;
|
|
2438
|
+
for (const {
|
|
2439
|
+
tsKey: selectedRelationTsKey,
|
|
2440
|
+
queryConfig: selectedRelationConfigValue,
|
|
2441
|
+
relation
|
|
2442
|
+
} of selectedRelations) {
|
|
2443
|
+
const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
|
|
2444
|
+
const relationTableName = getTableUniqueName(relation.referencedTable);
|
|
2445
|
+
const relationTableTsName = tableNamesMap[relationTableName];
|
|
2446
|
+
const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
|
|
2447
|
+
const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
|
|
2448
|
+
const builtRelation = this.buildRelationalQuery({
|
|
2449
|
+
fullSchema,
|
|
2450
|
+
schema,
|
|
2451
|
+
tableNamesMap,
|
|
2452
|
+
table: fullSchema[relationTableTsName],
|
|
2453
|
+
tableConfig: schema[relationTableTsName],
|
|
2454
|
+
queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
|
|
2455
|
+
tableAlias: relationTableAlias,
|
|
2456
|
+
joinOn: joinOn2,
|
|
2457
|
+
nestedQueryRelation: relation
|
|
2458
|
+
});
|
|
2459
|
+
const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
|
|
2460
|
+
selection.push({
|
|
2461
|
+
dbKey: selectedRelationTsKey,
|
|
2462
|
+
tsKey: selectedRelationTsKey,
|
|
2463
|
+
field,
|
|
2464
|
+
relationTableTsKey: relationTableTsName,
|
|
2465
|
+
isJson: true,
|
|
2466
|
+
selection: builtRelation.selection
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
if (selection.length === 0) {
|
|
2471
|
+
throw new DrizzleError({
|
|
2472
|
+
message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
|
|
2473
|
+
});
|
|
2474
|
+
}
|
|
2475
|
+
let result;
|
|
2476
|
+
where = and(joinOn, where);
|
|
2477
|
+
if (nestedQueryRelation) {
|
|
2478
|
+
let field = sql`json_array(${sql.join(selection.map(({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
|
|
2479
|
+
if (is(nestedQueryRelation, Many)) {
|
|
2480
|
+
field = sql`coalesce(json_group_array(${field}), json_array())`;
|
|
2481
|
+
}
|
|
2482
|
+
const nestedSelection = [{
|
|
2483
|
+
dbKey: "data",
|
|
2484
|
+
tsKey: "data",
|
|
2485
|
+
field: field.as("data"),
|
|
2486
|
+
isJson: true,
|
|
2487
|
+
relationTableTsKey: tableConfig.tsName,
|
|
2488
|
+
selection
|
|
2489
|
+
}];
|
|
2490
|
+
const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;
|
|
2491
|
+
if (needsSubquery) {
|
|
2492
|
+
result = this.buildSelectQuery({
|
|
2493
|
+
table: aliasedTable(table, tableAlias),
|
|
2494
|
+
fields: {},
|
|
2495
|
+
fieldsFlat: [
|
|
2496
|
+
{
|
|
2497
|
+
path: [],
|
|
2498
|
+
field: sql.raw("*")
|
|
2499
|
+
}
|
|
2500
|
+
],
|
|
2501
|
+
where,
|
|
2502
|
+
limit,
|
|
2503
|
+
offset,
|
|
2504
|
+
orderBy,
|
|
2505
|
+
setOperators: []
|
|
2506
|
+
});
|
|
2507
|
+
where = undefined;
|
|
2508
|
+
limit = undefined;
|
|
2509
|
+
offset = undefined;
|
|
2510
|
+
orderBy = undefined;
|
|
2511
|
+
} else {
|
|
2512
|
+
result = aliasedTable(table, tableAlias);
|
|
2513
|
+
}
|
|
2514
|
+
result = this.buildSelectQuery({
|
|
2515
|
+
table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
|
|
2516
|
+
fields: {},
|
|
2517
|
+
fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
|
|
2518
|
+
path: [],
|
|
2519
|
+
field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
|
|
2520
|
+
})),
|
|
2521
|
+
joins,
|
|
2522
|
+
where,
|
|
2523
|
+
limit,
|
|
2524
|
+
offset,
|
|
2525
|
+
orderBy,
|
|
2526
|
+
setOperators: []
|
|
2527
|
+
});
|
|
2528
|
+
} else {
|
|
2529
|
+
result = this.buildSelectQuery({
|
|
2530
|
+
table: aliasedTable(table, tableAlias),
|
|
2531
|
+
fields: {},
|
|
2532
|
+
fieldsFlat: selection.map(({ field }) => ({
|
|
2533
|
+
path: [],
|
|
2534
|
+
field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
|
|
2535
|
+
})),
|
|
2536
|
+
joins,
|
|
2537
|
+
where,
|
|
2538
|
+
limit,
|
|
2539
|
+
offset,
|
|
2540
|
+
orderBy,
|
|
2541
|
+
setOperators: []
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2544
|
+
return {
|
|
2545
|
+
tableTsKey: tableConfig.tsName,
|
|
2546
|
+
sql: result,
|
|
2547
|
+
selection
|
|
2548
|
+
};
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
class SQLiteSyncDialect extends SQLiteDialect {
|
|
2553
|
+
static [entityKind] = "SQLiteSyncDialect";
|
|
2554
|
+
migrate(migrations, session, config) {
|
|
2555
|
+
const migrationsTable = config === undefined ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
|
|
2556
|
+
const migrationTableCreate = sql`
|
|
2557
|
+
CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
|
|
2558
|
+
id SERIAL PRIMARY KEY,
|
|
2559
|
+
hash text NOT NULL,
|
|
2560
|
+
created_at numeric
|
|
2561
|
+
)
|
|
2562
|
+
`;
|
|
2563
|
+
session.run(migrationTableCreate);
|
|
2564
|
+
const dbMigrations = session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`);
|
|
2565
|
+
const lastDbMigration = dbMigrations[0] ?? undefined;
|
|
2566
|
+
session.run(sql`BEGIN`);
|
|
2567
|
+
try {
|
|
2568
|
+
for (const migration of migrations) {
|
|
2569
|
+
if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
|
|
2570
|
+
for (const stmt of migration.sql) {
|
|
2571
|
+
session.run(sql.raw(stmt));
|
|
2572
|
+
}
|
|
2573
|
+
session.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
session.run(sql`COMMIT`);
|
|
2577
|
+
} catch (e) {
|
|
2578
|
+
session.run(sql`ROLLBACK`);
|
|
2579
|
+
throw e;
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
// node_modules/drizzle-orm/query-builders/query-builder.js
|
|
2585
|
+
class TypedQueryBuilder {
|
|
2586
|
+
static [entityKind] = "TypedQueryBuilder";
|
|
2587
|
+
getSelectedFields() {
|
|
2588
|
+
return this._.selectedFields;
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/select.js
|
|
2593
|
+
class SQLiteSelectBuilder {
|
|
2594
|
+
static [entityKind] = "SQLiteSelectBuilder";
|
|
2595
|
+
fields;
|
|
2596
|
+
session;
|
|
2597
|
+
dialect;
|
|
2598
|
+
withList;
|
|
2599
|
+
distinct;
|
|
2600
|
+
constructor(config) {
|
|
2601
|
+
this.fields = config.fields;
|
|
2602
|
+
this.session = config.session;
|
|
2603
|
+
this.dialect = config.dialect;
|
|
2604
|
+
this.withList = config.withList;
|
|
2605
|
+
this.distinct = config.distinct;
|
|
2606
|
+
}
|
|
2607
|
+
from(source) {
|
|
2608
|
+
const isPartialSelect = !!this.fields;
|
|
2609
|
+
let fields;
|
|
2610
|
+
if (this.fields) {
|
|
2611
|
+
fields = this.fields;
|
|
2612
|
+
} else if (is(source, Subquery)) {
|
|
2613
|
+
fields = Object.fromEntries(Object.keys(source._.selectedFields).map((key) => [key, source[key]]));
|
|
2614
|
+
} else if (is(source, SQLiteViewBase)) {
|
|
2615
|
+
fields = source[ViewBaseConfig].selectedFields;
|
|
2616
|
+
} else if (is(source, SQL)) {
|
|
2617
|
+
fields = {};
|
|
2618
|
+
} else {
|
|
2619
|
+
fields = getTableColumns(source);
|
|
2620
|
+
}
|
|
2621
|
+
return new SQLiteSelectBase({
|
|
2622
|
+
table: source,
|
|
2623
|
+
fields,
|
|
2624
|
+
isPartialSelect,
|
|
2625
|
+
session: this.session,
|
|
2626
|
+
dialect: this.dialect,
|
|
2627
|
+
withList: this.withList,
|
|
2628
|
+
distinct: this.distinct
|
|
2629
|
+
});
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
|
|
2633
|
+
class SQLiteSelectQueryBuilderBase extends TypedQueryBuilder {
|
|
2634
|
+
static [entityKind] = "SQLiteSelectQueryBuilder";
|
|
2635
|
+
_;
|
|
2636
|
+
config;
|
|
2637
|
+
joinsNotNullableMap;
|
|
2638
|
+
tableName;
|
|
2639
|
+
isPartialSelect;
|
|
2640
|
+
session;
|
|
2641
|
+
dialect;
|
|
2642
|
+
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
|
|
2643
|
+
super();
|
|
2644
|
+
this.config = {
|
|
2645
|
+
withList,
|
|
2646
|
+
table,
|
|
2647
|
+
fields: { ...fields },
|
|
2648
|
+
distinct,
|
|
2649
|
+
setOperators: []
|
|
2650
|
+
};
|
|
2651
|
+
this.isPartialSelect = isPartialSelect;
|
|
2652
|
+
this.session = session;
|
|
2653
|
+
this.dialect = dialect;
|
|
2654
|
+
this._ = {
|
|
2655
|
+
selectedFields: fields
|
|
2656
|
+
};
|
|
2657
|
+
this.tableName = getTableLikeName(table);
|
|
2658
|
+
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
|
|
2659
|
+
}
|
|
2660
|
+
createJoin(joinType) {
|
|
2661
|
+
return (table, on) => {
|
|
2662
|
+
const baseTableName = this.tableName;
|
|
2663
|
+
const tableName = getTableLikeName(table);
|
|
2664
|
+
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
|
|
2665
|
+
throw new Error(`Alias "${tableName}" is already used in this query`);
|
|
2666
|
+
}
|
|
2667
|
+
if (!this.isPartialSelect) {
|
|
2668
|
+
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
|
|
2669
|
+
this.config.fields = {
|
|
2670
|
+
[baseTableName]: this.config.fields
|
|
2671
|
+
};
|
|
2672
|
+
}
|
|
2673
|
+
if (typeof tableName === "string" && !is(table, SQL)) {
|
|
2674
|
+
const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
|
|
2675
|
+
this.config.fields[tableName] = selection;
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
if (typeof on === "function") {
|
|
2679
|
+
on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
|
|
2680
|
+
}
|
|
2681
|
+
if (!this.config.joins) {
|
|
2682
|
+
this.config.joins = [];
|
|
2683
|
+
}
|
|
2684
|
+
this.config.joins.push({ on, table, joinType, alias: tableName });
|
|
2685
|
+
if (typeof tableName === "string") {
|
|
2686
|
+
switch (joinType) {
|
|
2687
|
+
case "left": {
|
|
2688
|
+
this.joinsNotNullableMap[tableName] = false;
|
|
2689
|
+
break;
|
|
2690
|
+
}
|
|
2691
|
+
case "right": {
|
|
2692
|
+
this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
|
|
2693
|
+
this.joinsNotNullableMap[tableName] = true;
|
|
2694
|
+
break;
|
|
2695
|
+
}
|
|
2696
|
+
case "inner": {
|
|
2697
|
+
this.joinsNotNullableMap[tableName] = true;
|
|
2698
|
+
break;
|
|
2699
|
+
}
|
|
2700
|
+
case "full": {
|
|
2701
|
+
this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
|
|
2702
|
+
this.joinsNotNullableMap[tableName] = false;
|
|
2703
|
+
break;
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
return this;
|
|
2708
|
+
};
|
|
2709
|
+
}
|
|
2710
|
+
leftJoin = this.createJoin("left");
|
|
2711
|
+
rightJoin = this.createJoin("right");
|
|
2712
|
+
innerJoin = this.createJoin("inner");
|
|
2713
|
+
fullJoin = this.createJoin("full");
|
|
2714
|
+
createSetOperator(type, isAll) {
|
|
2715
|
+
return (rightSelection) => {
|
|
2716
|
+
const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
|
|
2717
|
+
if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
|
|
2718
|
+
throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
|
|
2719
|
+
}
|
|
2720
|
+
this.config.setOperators.push({ type, isAll, rightSelect });
|
|
2721
|
+
return this;
|
|
2722
|
+
};
|
|
2723
|
+
}
|
|
2724
|
+
union = this.createSetOperator("union", false);
|
|
2725
|
+
unionAll = this.createSetOperator("union", true);
|
|
2726
|
+
intersect = this.createSetOperator("intersect", false);
|
|
2727
|
+
except = this.createSetOperator("except", false);
|
|
2728
|
+
addSetOperators(setOperators) {
|
|
2729
|
+
this.config.setOperators.push(...setOperators);
|
|
2730
|
+
return this;
|
|
2731
|
+
}
|
|
2732
|
+
where(where) {
|
|
2733
|
+
if (typeof where === "function") {
|
|
2734
|
+
where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
|
|
2735
|
+
}
|
|
2736
|
+
this.config.where = where;
|
|
2737
|
+
return this;
|
|
2738
|
+
}
|
|
2739
|
+
having(having) {
|
|
2740
|
+
if (typeof having === "function") {
|
|
2741
|
+
having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
|
|
2742
|
+
}
|
|
2743
|
+
this.config.having = having;
|
|
2744
|
+
return this;
|
|
2745
|
+
}
|
|
2746
|
+
groupBy(...columns) {
|
|
2747
|
+
if (typeof columns[0] === "function") {
|
|
2748
|
+
const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
|
|
2749
|
+
this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
|
|
2750
|
+
} else {
|
|
2751
|
+
this.config.groupBy = columns;
|
|
2752
|
+
}
|
|
2753
|
+
return this;
|
|
2754
|
+
}
|
|
2755
|
+
orderBy(...columns) {
|
|
2756
|
+
if (typeof columns[0] === "function") {
|
|
2757
|
+
const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
|
|
2758
|
+
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
2759
|
+
if (this.config.setOperators.length > 0) {
|
|
2760
|
+
this.config.setOperators.at(-1).orderBy = orderByArray;
|
|
2761
|
+
} else {
|
|
2762
|
+
this.config.orderBy = orderByArray;
|
|
2763
|
+
}
|
|
2764
|
+
} else {
|
|
2765
|
+
const orderByArray = columns;
|
|
2766
|
+
if (this.config.setOperators.length > 0) {
|
|
2767
|
+
this.config.setOperators.at(-1).orderBy = orderByArray;
|
|
2768
|
+
} else {
|
|
2769
|
+
this.config.orderBy = orderByArray;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
return this;
|
|
2773
|
+
}
|
|
2774
|
+
limit(limit) {
|
|
2775
|
+
if (this.config.setOperators.length > 0) {
|
|
2776
|
+
this.config.setOperators.at(-1).limit = limit;
|
|
2777
|
+
} else {
|
|
2778
|
+
this.config.limit = limit;
|
|
2779
|
+
}
|
|
2780
|
+
return this;
|
|
2781
|
+
}
|
|
2782
|
+
offset(offset) {
|
|
2783
|
+
if (this.config.setOperators.length > 0) {
|
|
2784
|
+
this.config.setOperators.at(-1).offset = offset;
|
|
2785
|
+
} else {
|
|
2786
|
+
this.config.offset = offset;
|
|
2787
|
+
}
|
|
2788
|
+
return this;
|
|
2789
|
+
}
|
|
2790
|
+
getSQL() {
|
|
2791
|
+
return this.dialect.buildSelectQuery(this.config);
|
|
2792
|
+
}
|
|
2793
|
+
toSQL() {
|
|
2794
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
2795
|
+
return rest;
|
|
2796
|
+
}
|
|
2797
|
+
as(alias) {
|
|
2798
|
+
return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
|
|
2799
|
+
}
|
|
2800
|
+
getSelectedFields() {
|
|
2801
|
+
return new Proxy(this.config.fields, new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
|
|
2802
|
+
}
|
|
2803
|
+
$dynamic() {
|
|
2804
|
+
return this;
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
|
|
2808
|
+
class SQLiteSelectBase extends SQLiteSelectQueryBuilderBase {
|
|
2809
|
+
static [entityKind] = "SQLiteSelect";
|
|
2810
|
+
_prepare(isOneTimeQuery = true) {
|
|
2811
|
+
if (!this.session) {
|
|
2812
|
+
throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
|
|
2813
|
+
}
|
|
2814
|
+
const fieldsList = orderSelectedFields(this.config.fields);
|
|
2815
|
+
const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all", true);
|
|
2816
|
+
query.joinsNotNullableMap = this.joinsNotNullableMap;
|
|
2817
|
+
return query;
|
|
2818
|
+
}
|
|
2819
|
+
prepare() {
|
|
2820
|
+
return this._prepare(false);
|
|
2821
|
+
}
|
|
2822
|
+
run = (placeholderValues) => {
|
|
2823
|
+
return this._prepare().run(placeholderValues);
|
|
2824
|
+
};
|
|
2825
|
+
all = (placeholderValues) => {
|
|
2826
|
+
return this._prepare().all(placeholderValues);
|
|
2827
|
+
};
|
|
2828
|
+
get = (placeholderValues) => {
|
|
2829
|
+
return this._prepare().get(placeholderValues);
|
|
2830
|
+
};
|
|
2831
|
+
values = (placeholderValues) => {
|
|
2832
|
+
return this._prepare().values(placeholderValues);
|
|
2833
|
+
};
|
|
2834
|
+
async execute() {
|
|
2835
|
+
return this.all();
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
applyMixins(SQLiteSelectBase, [QueryPromise]);
|
|
2839
|
+
function createSetOperator(type, isAll) {
|
|
2840
|
+
return (leftSelect, rightSelect, ...restSelects) => {
|
|
2841
|
+
const setOperators = [rightSelect, ...restSelects].map((select) => ({
|
|
2842
|
+
type,
|
|
2843
|
+
isAll,
|
|
2844
|
+
rightSelect: select
|
|
2845
|
+
}));
|
|
2846
|
+
for (const setOperator of setOperators) {
|
|
2847
|
+
if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
|
|
2848
|
+
throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
return leftSelect.addSetOperators(setOperators);
|
|
2852
|
+
};
|
|
2853
|
+
}
|
|
2854
|
+
var getSQLiteSetOperators = () => ({
|
|
2855
|
+
union,
|
|
2856
|
+
unionAll,
|
|
2857
|
+
intersect,
|
|
2858
|
+
except
|
|
2859
|
+
});
|
|
2860
|
+
var union = createSetOperator("union", false);
|
|
2861
|
+
var unionAll = createSetOperator("union", true);
|
|
2862
|
+
var intersect = createSetOperator("intersect", false);
|
|
2863
|
+
var except = createSetOperator("except", false);
|
|
2864
|
+
|
|
2865
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js
|
|
2866
|
+
class QueryBuilder {
|
|
2867
|
+
static [entityKind] = "SQLiteQueryBuilder";
|
|
2868
|
+
dialect;
|
|
2869
|
+
dialectConfig;
|
|
2870
|
+
constructor(dialect) {
|
|
2871
|
+
this.dialect = is(dialect, SQLiteDialect) ? dialect : undefined;
|
|
2872
|
+
this.dialectConfig = is(dialect, SQLiteDialect) ? undefined : dialect;
|
|
2873
|
+
}
|
|
2874
|
+
$with = (alias, selection) => {
|
|
2875
|
+
const queryBuilder = this;
|
|
2876
|
+
const as = (qb) => {
|
|
2877
|
+
if (typeof qb === "function") {
|
|
2878
|
+
qb = qb(queryBuilder);
|
|
2879
|
+
}
|
|
2880
|
+
return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
|
|
2881
|
+
};
|
|
2882
|
+
return { as };
|
|
2883
|
+
};
|
|
2884
|
+
with(...queries) {
|
|
2885
|
+
const self = this;
|
|
2886
|
+
function select(fields) {
|
|
2887
|
+
return new SQLiteSelectBuilder({
|
|
2888
|
+
fields: fields ?? undefined,
|
|
2889
|
+
session: undefined,
|
|
2890
|
+
dialect: self.getDialect(),
|
|
2891
|
+
withList: queries
|
|
2892
|
+
});
|
|
2893
|
+
}
|
|
2894
|
+
function selectDistinct(fields) {
|
|
2895
|
+
return new SQLiteSelectBuilder({
|
|
2896
|
+
fields: fields ?? undefined,
|
|
2897
|
+
session: undefined,
|
|
2898
|
+
dialect: self.getDialect(),
|
|
2899
|
+
withList: queries,
|
|
2900
|
+
distinct: true
|
|
2901
|
+
});
|
|
2902
|
+
}
|
|
2903
|
+
return { select, selectDistinct };
|
|
2904
|
+
}
|
|
2905
|
+
select(fields) {
|
|
2906
|
+
return new SQLiteSelectBuilder({ fields: fields ?? undefined, session: undefined, dialect: this.getDialect() });
|
|
2907
|
+
}
|
|
2908
|
+
selectDistinct(fields) {
|
|
2909
|
+
return new SQLiteSelectBuilder({
|
|
2910
|
+
fields: fields ?? undefined,
|
|
2911
|
+
session: undefined,
|
|
2912
|
+
dialect: this.getDialect(),
|
|
2913
|
+
distinct: true
|
|
2914
|
+
});
|
|
2915
|
+
}
|
|
2916
|
+
getDialect() {
|
|
2917
|
+
if (!this.dialect) {
|
|
2918
|
+
this.dialect = new SQLiteSyncDialect(this.dialectConfig);
|
|
2919
|
+
}
|
|
2920
|
+
return this.dialect;
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
|
|
2924
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
|
|
2925
|
+
class SQLiteInsertBuilder {
|
|
2926
|
+
constructor(table, session, dialect, withList) {
|
|
2927
|
+
this.table = table;
|
|
2928
|
+
this.session = session;
|
|
2929
|
+
this.dialect = dialect;
|
|
2930
|
+
this.withList = withList;
|
|
2931
|
+
}
|
|
2932
|
+
static [entityKind] = "SQLiteInsertBuilder";
|
|
2933
|
+
values(values) {
|
|
2934
|
+
values = Array.isArray(values) ? values : [values];
|
|
2935
|
+
if (values.length === 0) {
|
|
2936
|
+
throw new Error("values() must be called with at least one value");
|
|
2937
|
+
}
|
|
2938
|
+
const mappedValues = values.map((entry) => {
|
|
2939
|
+
const result = {};
|
|
2940
|
+
const cols = this.table[Table.Symbol.Columns];
|
|
2941
|
+
for (const colKey of Object.keys(entry)) {
|
|
2942
|
+
const colValue = entry[colKey];
|
|
2943
|
+
result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
|
|
2944
|
+
}
|
|
2945
|
+
return result;
|
|
2946
|
+
});
|
|
2947
|
+
return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
|
|
2948
|
+
}
|
|
2949
|
+
select(selectQuery) {
|
|
2950
|
+
const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder) : selectQuery;
|
|
2951
|
+
if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
|
|
2952
|
+
throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
|
|
2953
|
+
}
|
|
2954
|
+
return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
|
|
2958
|
+
class SQLiteInsertBase extends QueryPromise {
|
|
2959
|
+
constructor(table, values, session, dialect, withList, select) {
|
|
2960
|
+
super();
|
|
2961
|
+
this.session = session;
|
|
2962
|
+
this.dialect = dialect;
|
|
2963
|
+
this.config = { table, values, withList, select };
|
|
2964
|
+
}
|
|
2965
|
+
static [entityKind] = "SQLiteInsert";
|
|
2966
|
+
config;
|
|
2967
|
+
returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
|
|
2968
|
+
this.config.returning = orderSelectedFields(fields);
|
|
2969
|
+
return this;
|
|
2970
|
+
}
|
|
2971
|
+
onConflictDoNothing(config = {}) {
|
|
2972
|
+
if (!this.config.onConflict)
|
|
2973
|
+
this.config.onConflict = [];
|
|
2974
|
+
if (config.target === undefined) {
|
|
2975
|
+
this.config.onConflict.push(sql` on conflict do nothing`);
|
|
2976
|
+
} else {
|
|
2977
|
+
const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
|
|
2978
|
+
const whereSql = config.where ? sql` where ${config.where}` : sql``;
|
|
2979
|
+
this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
|
|
2980
|
+
}
|
|
2981
|
+
return this;
|
|
2982
|
+
}
|
|
2983
|
+
onConflictDoUpdate(config) {
|
|
2984
|
+
if (config.where && (config.targetWhere || config.setWhere)) {
|
|
2985
|
+
throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');
|
|
2986
|
+
}
|
|
2987
|
+
if (!this.config.onConflict)
|
|
2988
|
+
this.config.onConflict = [];
|
|
2989
|
+
const whereSql = config.where ? sql` where ${config.where}` : undefined;
|
|
2990
|
+
const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
|
|
2991
|
+
const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
|
|
2992
|
+
const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
|
|
2993
|
+
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
|
|
2994
|
+
this.config.onConflict.push(sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`);
|
|
2995
|
+
return this;
|
|
2996
|
+
}
|
|
2997
|
+
getSQL() {
|
|
2998
|
+
return this.dialect.buildInsertQuery(this.config);
|
|
2999
|
+
}
|
|
3000
|
+
toSQL() {
|
|
3001
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
3002
|
+
return rest;
|
|
3003
|
+
}
|
|
3004
|
+
_prepare(isOneTimeQuery = true) {
|
|
3005
|
+
return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true);
|
|
3006
|
+
}
|
|
3007
|
+
prepare() {
|
|
3008
|
+
return this._prepare(false);
|
|
3009
|
+
}
|
|
3010
|
+
run = (placeholderValues) => {
|
|
3011
|
+
return this._prepare().run(placeholderValues);
|
|
3012
|
+
};
|
|
3013
|
+
all = (placeholderValues) => {
|
|
3014
|
+
return this._prepare().all(placeholderValues);
|
|
3015
|
+
};
|
|
3016
|
+
get = (placeholderValues) => {
|
|
3017
|
+
return this._prepare().get(placeholderValues);
|
|
3018
|
+
};
|
|
3019
|
+
values = (placeholderValues) => {
|
|
3020
|
+
return this._prepare().values(placeholderValues);
|
|
3021
|
+
};
|
|
3022
|
+
async execute() {
|
|
3023
|
+
return this.config.returning ? this.all() : this.run();
|
|
3024
|
+
}
|
|
3025
|
+
$dynamic() {
|
|
3026
|
+
return this;
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/update.js
|
|
3031
|
+
class SQLiteUpdateBuilder {
|
|
3032
|
+
constructor(table, session, dialect, withList) {
|
|
3033
|
+
this.table = table;
|
|
3034
|
+
this.session = session;
|
|
3035
|
+
this.dialect = dialect;
|
|
3036
|
+
this.withList = withList;
|
|
3037
|
+
}
|
|
3038
|
+
static [entityKind] = "SQLiteUpdateBuilder";
|
|
3039
|
+
set(values) {
|
|
3040
|
+
return new SQLiteUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
class SQLiteUpdateBase extends QueryPromise {
|
|
3045
|
+
constructor(table, set, session, dialect, withList) {
|
|
3046
|
+
super();
|
|
3047
|
+
this.session = session;
|
|
3048
|
+
this.dialect = dialect;
|
|
3049
|
+
this.config = { set, table, withList, joins: [] };
|
|
3050
|
+
}
|
|
3051
|
+
static [entityKind] = "SQLiteUpdate";
|
|
3052
|
+
config;
|
|
3053
|
+
from(source) {
|
|
3054
|
+
this.config.from = source;
|
|
3055
|
+
return this;
|
|
3056
|
+
}
|
|
3057
|
+
createJoin(joinType) {
|
|
3058
|
+
return (table, on) => {
|
|
3059
|
+
const tableName = getTableLikeName(table);
|
|
3060
|
+
if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
|
|
3061
|
+
throw new Error(`Alias "${tableName}" is already used in this query`);
|
|
3062
|
+
}
|
|
3063
|
+
if (typeof on === "function") {
|
|
3064
|
+
const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : undefined : undefined;
|
|
3065
|
+
on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
|
|
3066
|
+
}
|
|
3067
|
+
this.config.joins.push({ on, table, joinType, alias: tableName });
|
|
3068
|
+
return this;
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
leftJoin = this.createJoin("left");
|
|
3072
|
+
rightJoin = this.createJoin("right");
|
|
3073
|
+
innerJoin = this.createJoin("inner");
|
|
3074
|
+
fullJoin = this.createJoin("full");
|
|
3075
|
+
where(where) {
|
|
3076
|
+
this.config.where = where;
|
|
3077
|
+
return this;
|
|
3078
|
+
}
|
|
3079
|
+
orderBy(...columns) {
|
|
3080
|
+
if (typeof columns[0] === "function") {
|
|
3081
|
+
const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
|
|
3082
|
+
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
3083
|
+
this.config.orderBy = orderByArray;
|
|
3084
|
+
} else {
|
|
3085
|
+
const orderByArray = columns;
|
|
3086
|
+
this.config.orderBy = orderByArray;
|
|
3087
|
+
}
|
|
3088
|
+
return this;
|
|
3089
|
+
}
|
|
3090
|
+
limit(limit) {
|
|
3091
|
+
this.config.limit = limit;
|
|
3092
|
+
return this;
|
|
3093
|
+
}
|
|
3094
|
+
returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
|
|
3095
|
+
this.config.returning = orderSelectedFields(fields);
|
|
3096
|
+
return this;
|
|
3097
|
+
}
|
|
3098
|
+
getSQL() {
|
|
3099
|
+
return this.dialect.buildUpdateQuery(this.config);
|
|
3100
|
+
}
|
|
3101
|
+
toSQL() {
|
|
3102
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
3103
|
+
return rest;
|
|
3104
|
+
}
|
|
3105
|
+
_prepare(isOneTimeQuery = true) {
|
|
3106
|
+
return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true);
|
|
3107
|
+
}
|
|
3108
|
+
prepare() {
|
|
3109
|
+
return this._prepare(false);
|
|
3110
|
+
}
|
|
3111
|
+
run = (placeholderValues) => {
|
|
3112
|
+
return this._prepare().run(placeholderValues);
|
|
3113
|
+
};
|
|
3114
|
+
all = (placeholderValues) => {
|
|
3115
|
+
return this._prepare().all(placeholderValues);
|
|
3116
|
+
};
|
|
3117
|
+
get = (placeholderValues) => {
|
|
3118
|
+
return this._prepare().get(placeholderValues);
|
|
3119
|
+
};
|
|
3120
|
+
values = (placeholderValues) => {
|
|
3121
|
+
return this._prepare().values(placeholderValues);
|
|
3122
|
+
};
|
|
3123
|
+
async execute() {
|
|
3124
|
+
return this.config.returning ? this.all() : this.run();
|
|
3125
|
+
}
|
|
3126
|
+
$dynamic() {
|
|
3127
|
+
return this;
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/count.js
|
|
3132
|
+
class SQLiteCountBuilder extends SQL {
|
|
3133
|
+
constructor(params) {
|
|
3134
|
+
super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
|
|
3135
|
+
this.params = params;
|
|
3136
|
+
this.session = params.session;
|
|
3137
|
+
this.sql = SQLiteCountBuilder.buildCount(params.source, params.filters);
|
|
3138
|
+
}
|
|
3139
|
+
sql;
|
|
3140
|
+
static [entityKind] = "SQLiteCountBuilderAsync";
|
|
3141
|
+
[Symbol.toStringTag] = "SQLiteCountBuilderAsync";
|
|
3142
|
+
session;
|
|
3143
|
+
static buildEmbeddedCount(source, filters) {
|
|
3144
|
+
return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
|
|
3145
|
+
}
|
|
3146
|
+
static buildCount(source, filters) {
|
|
3147
|
+
return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
|
|
3148
|
+
}
|
|
3149
|
+
then(onfulfilled, onrejected) {
|
|
3150
|
+
return Promise.resolve(this.session.count(this.sql)).then(onfulfilled, onrejected);
|
|
3151
|
+
}
|
|
3152
|
+
catch(onRejected) {
|
|
3153
|
+
return this.then(undefined, onRejected);
|
|
3154
|
+
}
|
|
3155
|
+
finally(onFinally) {
|
|
3156
|
+
return this.then((value) => {
|
|
3157
|
+
onFinally?.();
|
|
3158
|
+
return value;
|
|
3159
|
+
}, (reason) => {
|
|
3160
|
+
onFinally?.();
|
|
3161
|
+
throw reason;
|
|
3162
|
+
});
|
|
3163
|
+
}
|
|
3164
|
+
}
|
|
3165
|
+
|
|
3166
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/query.js
|
|
3167
|
+
class RelationalQueryBuilder {
|
|
3168
|
+
constructor(mode, fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
|
|
3169
|
+
this.mode = mode;
|
|
3170
|
+
this.fullSchema = fullSchema;
|
|
3171
|
+
this.schema = schema;
|
|
3172
|
+
this.tableNamesMap = tableNamesMap;
|
|
3173
|
+
this.table = table;
|
|
3174
|
+
this.tableConfig = tableConfig;
|
|
3175
|
+
this.dialect = dialect;
|
|
3176
|
+
this.session = session;
|
|
3177
|
+
}
|
|
3178
|
+
static [entityKind] = "SQLiteAsyncRelationalQueryBuilder";
|
|
3179
|
+
findMany(config) {
|
|
3180
|
+
return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
|
|
3181
|
+
}
|
|
3182
|
+
findFirst(config) {
|
|
3183
|
+
return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first");
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
|
|
3187
|
+
class SQLiteRelationalQuery extends QueryPromise {
|
|
3188
|
+
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
|
|
3189
|
+
super();
|
|
3190
|
+
this.fullSchema = fullSchema;
|
|
3191
|
+
this.schema = schema;
|
|
3192
|
+
this.tableNamesMap = tableNamesMap;
|
|
3193
|
+
this.table = table;
|
|
3194
|
+
this.tableConfig = tableConfig;
|
|
3195
|
+
this.dialect = dialect;
|
|
3196
|
+
this.session = session;
|
|
3197
|
+
this.config = config;
|
|
3198
|
+
this.mode = mode;
|
|
3199
|
+
}
|
|
3200
|
+
static [entityKind] = "SQLiteAsyncRelationalQuery";
|
|
3201
|
+
mode;
|
|
3202
|
+
getSQL() {
|
|
3203
|
+
return this.dialect.buildRelationalQuery({
|
|
3204
|
+
fullSchema: this.fullSchema,
|
|
3205
|
+
schema: this.schema,
|
|
3206
|
+
tableNamesMap: this.tableNamesMap,
|
|
3207
|
+
table: this.table,
|
|
3208
|
+
tableConfig: this.tableConfig,
|
|
3209
|
+
queryConfig: this.config,
|
|
3210
|
+
tableAlias: this.tableConfig.tsName
|
|
3211
|
+
}).sql;
|
|
3212
|
+
}
|
|
3213
|
+
_prepare(isOneTimeQuery = false) {
|
|
3214
|
+
const { query, builtQuery } = this._toSQL();
|
|
3215
|
+
return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](builtQuery, undefined, this.mode === "first" ? "get" : "all", true, (rawRows, mapColumnValue) => {
|
|
3216
|
+
const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
|
|
3217
|
+
if (this.mode === "first") {
|
|
3218
|
+
return rows[0];
|
|
3219
|
+
}
|
|
3220
|
+
return rows;
|
|
3221
|
+
});
|
|
3222
|
+
}
|
|
3223
|
+
prepare() {
|
|
3224
|
+
return this._prepare(false);
|
|
3225
|
+
}
|
|
3226
|
+
_toSQL() {
|
|
3227
|
+
const query = this.dialect.buildRelationalQuery({
|
|
3228
|
+
fullSchema: this.fullSchema,
|
|
3229
|
+
schema: this.schema,
|
|
3230
|
+
tableNamesMap: this.tableNamesMap,
|
|
3231
|
+
table: this.table,
|
|
3232
|
+
tableConfig: this.tableConfig,
|
|
3233
|
+
queryConfig: this.config,
|
|
3234
|
+
tableAlias: this.tableConfig.tsName
|
|
3235
|
+
});
|
|
3236
|
+
const builtQuery = this.dialect.sqlToQuery(query.sql);
|
|
3237
|
+
return { query, builtQuery };
|
|
3238
|
+
}
|
|
3239
|
+
toSQL() {
|
|
3240
|
+
return this._toSQL().builtQuery;
|
|
3241
|
+
}
|
|
3242
|
+
executeRaw() {
|
|
3243
|
+
if (this.mode === "first") {
|
|
3244
|
+
return this._prepare(false).get();
|
|
3245
|
+
}
|
|
3246
|
+
return this._prepare(false).all();
|
|
3247
|
+
}
|
|
3248
|
+
async execute() {
|
|
3249
|
+
return this.executeRaw();
|
|
3250
|
+
}
|
|
3251
|
+
}
|
|
3252
|
+
|
|
3253
|
+
class SQLiteSyncRelationalQuery extends SQLiteRelationalQuery {
|
|
3254
|
+
static [entityKind] = "SQLiteSyncRelationalQuery";
|
|
3255
|
+
sync() {
|
|
3256
|
+
return this.executeRaw();
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
|
|
3260
|
+
// node_modules/drizzle-orm/sqlite-core/query-builders/raw.js
|
|
3261
|
+
class SQLiteRaw extends QueryPromise {
|
|
3262
|
+
constructor(execute, getSQL, action, dialect, mapBatchResult) {
|
|
3263
|
+
super();
|
|
3264
|
+
this.execute = execute;
|
|
3265
|
+
this.getSQL = getSQL;
|
|
3266
|
+
this.dialect = dialect;
|
|
3267
|
+
this.mapBatchResult = mapBatchResult;
|
|
3268
|
+
this.config = { action };
|
|
3269
|
+
}
|
|
3270
|
+
static [entityKind] = "SQLiteRaw";
|
|
3271
|
+
config;
|
|
3272
|
+
getQuery() {
|
|
3273
|
+
return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };
|
|
3274
|
+
}
|
|
3275
|
+
mapResult(result, isFromBatch) {
|
|
3276
|
+
return isFromBatch ? this.mapBatchResult(result) : result;
|
|
3277
|
+
}
|
|
3278
|
+
_prepare() {
|
|
3279
|
+
return this;
|
|
3280
|
+
}
|
|
3281
|
+
isResponseInArrayMode() {
|
|
3282
|
+
return false;
|
|
3283
|
+
}
|
|
3284
|
+
}
|
|
3285
|
+
|
|
3286
|
+
// node_modules/drizzle-orm/sqlite-core/db.js
|
|
3287
|
+
class BaseSQLiteDatabase {
|
|
3288
|
+
constructor(resultKind, dialect, session, schema) {
|
|
3289
|
+
this.resultKind = resultKind;
|
|
3290
|
+
this.dialect = dialect;
|
|
3291
|
+
this.session = session;
|
|
3292
|
+
this._ = schema ? {
|
|
3293
|
+
schema: schema.schema,
|
|
3294
|
+
fullSchema: schema.fullSchema,
|
|
3295
|
+
tableNamesMap: schema.tableNamesMap
|
|
3296
|
+
} : {
|
|
3297
|
+
schema: undefined,
|
|
3298
|
+
fullSchema: {},
|
|
3299
|
+
tableNamesMap: {}
|
|
3300
|
+
};
|
|
3301
|
+
this.query = {};
|
|
3302
|
+
const query = this.query;
|
|
3303
|
+
if (this._.schema) {
|
|
3304
|
+
for (const [tableName, columns] of Object.entries(this._.schema)) {
|
|
3305
|
+
query[tableName] = new RelationalQueryBuilder(resultKind, schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
|
|
3306
|
+
}
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
static [entityKind] = "BaseSQLiteDatabase";
|
|
3310
|
+
query;
|
|
3311
|
+
$with = (alias, selection) => {
|
|
3312
|
+
const self = this;
|
|
3313
|
+
const as = (qb) => {
|
|
3314
|
+
if (typeof qb === "function") {
|
|
3315
|
+
qb = qb(new QueryBuilder(self.dialect));
|
|
3316
|
+
}
|
|
3317
|
+
return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
|
|
3318
|
+
};
|
|
3319
|
+
return { as };
|
|
3320
|
+
};
|
|
3321
|
+
$count(source, filters) {
|
|
3322
|
+
return new SQLiteCountBuilder({ source, filters, session: this.session });
|
|
3323
|
+
}
|
|
3324
|
+
with(...queries) {
|
|
3325
|
+
const self = this;
|
|
3326
|
+
function select(fields) {
|
|
3327
|
+
return new SQLiteSelectBuilder({
|
|
3328
|
+
fields: fields ?? undefined,
|
|
3329
|
+
session: self.session,
|
|
3330
|
+
dialect: self.dialect,
|
|
3331
|
+
withList: queries
|
|
3332
|
+
});
|
|
3333
|
+
}
|
|
3334
|
+
function selectDistinct(fields) {
|
|
3335
|
+
return new SQLiteSelectBuilder({
|
|
3336
|
+
fields: fields ?? undefined,
|
|
3337
|
+
session: self.session,
|
|
3338
|
+
dialect: self.dialect,
|
|
3339
|
+
withList: queries,
|
|
3340
|
+
distinct: true
|
|
3341
|
+
});
|
|
3342
|
+
}
|
|
3343
|
+
function update(table) {
|
|
3344
|
+
return new SQLiteUpdateBuilder(table, self.session, self.dialect, queries);
|
|
3345
|
+
}
|
|
3346
|
+
function insert(into) {
|
|
3347
|
+
return new SQLiteInsertBuilder(into, self.session, self.dialect, queries);
|
|
3348
|
+
}
|
|
3349
|
+
function delete_(from) {
|
|
3350
|
+
return new SQLiteDeleteBase(from, self.session, self.dialect, queries);
|
|
3351
|
+
}
|
|
3352
|
+
return { select, selectDistinct, update, insert, delete: delete_ };
|
|
3353
|
+
}
|
|
3354
|
+
select(fields) {
|
|
3355
|
+
return new SQLiteSelectBuilder({ fields: fields ?? undefined, session: this.session, dialect: this.dialect });
|
|
3356
|
+
}
|
|
3357
|
+
selectDistinct(fields) {
|
|
3358
|
+
return new SQLiteSelectBuilder({
|
|
3359
|
+
fields: fields ?? undefined,
|
|
3360
|
+
session: this.session,
|
|
3361
|
+
dialect: this.dialect,
|
|
3362
|
+
distinct: true
|
|
3363
|
+
});
|
|
3364
|
+
}
|
|
3365
|
+
update(table) {
|
|
3366
|
+
return new SQLiteUpdateBuilder(table, this.session, this.dialect);
|
|
3367
|
+
}
|
|
3368
|
+
insert(into) {
|
|
3369
|
+
return new SQLiteInsertBuilder(into, this.session, this.dialect);
|
|
3370
|
+
}
|
|
3371
|
+
delete(from) {
|
|
3372
|
+
return new SQLiteDeleteBase(from, this.session, this.dialect);
|
|
3373
|
+
}
|
|
3374
|
+
run(query) {
|
|
3375
|
+
const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
|
|
3376
|
+
if (this.resultKind === "async") {
|
|
3377
|
+
return new SQLiteRaw(async () => this.session.run(sequel), () => sequel, "run", this.dialect, this.session.extractRawRunValueFromBatchResult.bind(this.session));
|
|
3378
|
+
}
|
|
3379
|
+
return this.session.run(sequel);
|
|
3380
|
+
}
|
|
3381
|
+
all(query) {
|
|
3382
|
+
const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
|
|
3383
|
+
if (this.resultKind === "async") {
|
|
3384
|
+
return new SQLiteRaw(async () => this.session.all(sequel), () => sequel, "all", this.dialect, this.session.extractRawAllValueFromBatchResult.bind(this.session));
|
|
3385
|
+
}
|
|
3386
|
+
return this.session.all(sequel);
|
|
3387
|
+
}
|
|
3388
|
+
get(query) {
|
|
3389
|
+
const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
|
|
3390
|
+
if (this.resultKind === "async") {
|
|
3391
|
+
return new SQLiteRaw(async () => this.session.get(sequel), () => sequel, "get", this.dialect, this.session.extractRawGetValueFromBatchResult.bind(this.session));
|
|
3392
|
+
}
|
|
3393
|
+
return this.session.get(sequel);
|
|
3394
|
+
}
|
|
3395
|
+
values(query) {
|
|
3396
|
+
const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
|
|
3397
|
+
if (this.resultKind === "async") {
|
|
3398
|
+
return new SQLiteRaw(async () => this.session.values(sequel), () => sequel, "values", this.dialect, this.session.extractRawValuesValueFromBatchResult.bind(this.session));
|
|
3399
|
+
}
|
|
3400
|
+
return this.session.values(sequel);
|
|
3401
|
+
}
|
|
3402
|
+
transaction(transaction, config) {
|
|
3403
|
+
return this.session.transaction(transaction, config);
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
|
|
3407
|
+
// node_modules/drizzle-orm/sqlite-core/session.js
|
|
3408
|
+
class ExecuteResultSync extends QueryPromise {
|
|
3409
|
+
constructor(resultCb) {
|
|
3410
|
+
super();
|
|
3411
|
+
this.resultCb = resultCb;
|
|
3412
|
+
}
|
|
3413
|
+
static [entityKind] = "ExecuteResultSync";
|
|
3414
|
+
async execute() {
|
|
3415
|
+
return this.resultCb();
|
|
3416
|
+
}
|
|
3417
|
+
sync() {
|
|
3418
|
+
return this.resultCb();
|
|
3419
|
+
}
|
|
3420
|
+
}
|
|
3421
|
+
|
|
3422
|
+
class SQLitePreparedQuery {
|
|
3423
|
+
constructor(mode, executeMethod, query) {
|
|
3424
|
+
this.mode = mode;
|
|
3425
|
+
this.executeMethod = executeMethod;
|
|
3426
|
+
this.query = query;
|
|
3427
|
+
}
|
|
3428
|
+
static [entityKind] = "PreparedQuery";
|
|
3429
|
+
joinsNotNullableMap;
|
|
3430
|
+
getQuery() {
|
|
3431
|
+
return this.query;
|
|
3432
|
+
}
|
|
3433
|
+
mapRunResult(result, _isFromBatch) {
|
|
3434
|
+
return result;
|
|
3435
|
+
}
|
|
3436
|
+
mapAllResult(_result, _isFromBatch) {
|
|
3437
|
+
throw new Error("Not implemented");
|
|
3438
|
+
}
|
|
3439
|
+
mapGetResult(_result, _isFromBatch) {
|
|
3440
|
+
throw new Error("Not implemented");
|
|
3441
|
+
}
|
|
3442
|
+
execute(placeholderValues) {
|
|
3443
|
+
if (this.mode === "async") {
|
|
3444
|
+
return this[this.executeMethod](placeholderValues);
|
|
3445
|
+
}
|
|
3446
|
+
return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
|
|
3447
|
+
}
|
|
3448
|
+
mapResult(response, isFromBatch) {
|
|
3449
|
+
switch (this.executeMethod) {
|
|
3450
|
+
case "run": {
|
|
3451
|
+
return this.mapRunResult(response, isFromBatch);
|
|
3452
|
+
}
|
|
3453
|
+
case "all": {
|
|
3454
|
+
return this.mapAllResult(response, isFromBatch);
|
|
3455
|
+
}
|
|
3456
|
+
case "get": {
|
|
3457
|
+
return this.mapGetResult(response, isFromBatch);
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
|
|
3463
|
+
class SQLiteSession {
|
|
3464
|
+
constructor(dialect) {
|
|
3465
|
+
this.dialect = dialect;
|
|
3466
|
+
}
|
|
3467
|
+
static [entityKind] = "SQLiteSession";
|
|
3468
|
+
prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode) {
|
|
3469
|
+
return this.prepareQuery(query, fields, executeMethod, isResponseInArrayMode);
|
|
3470
|
+
}
|
|
3471
|
+
run(query) {
|
|
3472
|
+
const staticQuery = this.dialect.sqlToQuery(query);
|
|
3473
|
+
try {
|
|
3474
|
+
return this.prepareOneTimeQuery(staticQuery, undefined, "run", false).run();
|
|
3475
|
+
} catch (err) {
|
|
3476
|
+
throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });
|
|
3477
|
+
}
|
|
3478
|
+
}
|
|
3479
|
+
extractRawRunValueFromBatchResult(result) {
|
|
3480
|
+
return result;
|
|
3481
|
+
}
|
|
3482
|
+
all(query) {
|
|
3483
|
+
return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).all();
|
|
3484
|
+
}
|
|
3485
|
+
extractRawAllValueFromBatchResult(_result) {
|
|
3486
|
+
throw new Error("Not implemented");
|
|
3487
|
+
}
|
|
3488
|
+
get(query) {
|
|
3489
|
+
return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).get();
|
|
3490
|
+
}
|
|
3491
|
+
extractRawGetValueFromBatchResult(_result) {
|
|
3492
|
+
throw new Error("Not implemented");
|
|
3493
|
+
}
|
|
3494
|
+
values(query) {
|
|
3495
|
+
return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).values();
|
|
3496
|
+
}
|
|
3497
|
+
async count(sql2) {
|
|
3498
|
+
const result = await this.values(sql2);
|
|
3499
|
+
return result[0][0];
|
|
3500
|
+
}
|
|
3501
|
+
extractRawValuesValueFromBatchResult(_result) {
|
|
3502
|
+
throw new Error("Not implemented");
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
|
|
3506
|
+
class SQLiteTransaction extends BaseSQLiteDatabase {
|
|
3507
|
+
constructor(resultType, dialect, session, schema, nestedIndex = 0) {
|
|
3508
|
+
super(resultType, dialect, session, schema);
|
|
3509
|
+
this.schema = schema;
|
|
3510
|
+
this.nestedIndex = nestedIndex;
|
|
3511
|
+
}
|
|
3512
|
+
static [entityKind] = "SQLiteTransaction";
|
|
3513
|
+
rollback() {
|
|
3514
|
+
throw new TransactionRollbackError;
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
|
|
3518
|
+
// node_modules/drizzle-orm/bun-sqlite/session.js
|
|
3519
|
+
class SQLiteBunSession extends SQLiteSession {
|
|
3520
|
+
constructor(client, dialect, schema, options = {}) {
|
|
3521
|
+
super(dialect);
|
|
3522
|
+
this.client = client;
|
|
3523
|
+
this.schema = schema;
|
|
3524
|
+
this.logger = options.logger ?? new NoopLogger;
|
|
3525
|
+
}
|
|
3526
|
+
static [entityKind] = "SQLiteBunSession";
|
|
3527
|
+
logger;
|
|
3528
|
+
exec(query) {
|
|
3529
|
+
this.client.exec(query);
|
|
3530
|
+
}
|
|
3531
|
+
prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper) {
|
|
3532
|
+
const stmt = this.client.prepare(query.sql);
|
|
3533
|
+
return new PreparedQuery(stmt, query, this.logger, fields, executeMethod, isResponseInArrayMode, customResultMapper);
|
|
3534
|
+
}
|
|
3535
|
+
transaction(transaction, config = {}) {
|
|
3536
|
+
const tx = new SQLiteBunTransaction("sync", this.dialect, this, this.schema);
|
|
3537
|
+
let result;
|
|
3538
|
+
const nativeTx = this.client.transaction(() => {
|
|
3539
|
+
result = transaction(tx);
|
|
3540
|
+
});
|
|
3541
|
+
nativeTx[config.behavior ?? "deferred"]();
|
|
3542
|
+
return result;
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
class SQLiteBunTransaction extends SQLiteTransaction {
|
|
3547
|
+
static [entityKind] = "SQLiteBunTransaction";
|
|
3548
|
+
transaction(transaction) {
|
|
3549
|
+
const savepointName = `sp${this.nestedIndex}`;
|
|
3550
|
+
const tx = new SQLiteBunTransaction("sync", this.dialect, this.session, this.schema, this.nestedIndex + 1);
|
|
3551
|
+
this.session.run(sql.raw(`savepoint ${savepointName}`));
|
|
3552
|
+
try {
|
|
3553
|
+
const result = transaction(tx);
|
|
3554
|
+
this.session.run(sql.raw(`release savepoint ${savepointName}`));
|
|
3555
|
+
return result;
|
|
3556
|
+
} catch (err) {
|
|
3557
|
+
this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
|
|
3558
|
+
throw err;
|
|
3559
|
+
}
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
|
|
3563
|
+
class PreparedQuery extends SQLitePreparedQuery {
|
|
3564
|
+
constructor(stmt, query, logger, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
|
|
3565
|
+
super("sync", executeMethod, query);
|
|
3566
|
+
this.stmt = stmt;
|
|
3567
|
+
this.logger = logger;
|
|
3568
|
+
this.fields = fields;
|
|
3569
|
+
this._isResponseInArrayMode = _isResponseInArrayMode;
|
|
3570
|
+
this.customResultMapper = customResultMapper;
|
|
3571
|
+
}
|
|
3572
|
+
static [entityKind] = "SQLiteBunPreparedQuery";
|
|
3573
|
+
run(placeholderValues) {
|
|
3574
|
+
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
|
|
3575
|
+
this.logger.logQuery(this.query.sql, params);
|
|
3576
|
+
return this.stmt.run(...params);
|
|
3577
|
+
}
|
|
3578
|
+
all(placeholderValues) {
|
|
3579
|
+
const { fields, query, logger, joinsNotNullableMap, stmt, customResultMapper } = this;
|
|
3580
|
+
if (!fields && !customResultMapper) {
|
|
3581
|
+
const params = fillPlaceholders(query.params, placeholderValues ?? {});
|
|
3582
|
+
logger.logQuery(query.sql, params);
|
|
3583
|
+
return stmt.all(...params);
|
|
3584
|
+
}
|
|
3585
|
+
const rows = this.values(placeholderValues);
|
|
3586
|
+
if (customResultMapper) {
|
|
3587
|
+
return customResultMapper(rows);
|
|
3588
|
+
}
|
|
3589
|
+
return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
|
|
3590
|
+
}
|
|
3591
|
+
get(placeholderValues) {
|
|
3592
|
+
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
|
|
3593
|
+
this.logger.logQuery(this.query.sql, params);
|
|
3594
|
+
const row = this.stmt.values(...params)[0];
|
|
3595
|
+
if (!row) {
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
const { fields, joinsNotNullableMap, customResultMapper } = this;
|
|
3599
|
+
if (!fields && !customResultMapper) {
|
|
3600
|
+
return row;
|
|
3601
|
+
}
|
|
3602
|
+
if (customResultMapper) {
|
|
3603
|
+
return customResultMapper([row]);
|
|
3604
|
+
}
|
|
3605
|
+
return mapResultRow(fields, row, joinsNotNullableMap);
|
|
3606
|
+
}
|
|
3607
|
+
values(placeholderValues) {
|
|
3608
|
+
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
|
|
3609
|
+
this.logger.logQuery(this.query.sql, params);
|
|
3610
|
+
return this.stmt.values(...params);
|
|
3611
|
+
}
|
|
3612
|
+
isResponseInArrayMode() {
|
|
3613
|
+
return this._isResponseInArrayMode;
|
|
3614
|
+
}
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
// node_modules/drizzle-orm/bun-sqlite/driver.js
|
|
3618
|
+
class BunSQLiteDatabase extends BaseSQLiteDatabase {
|
|
3619
|
+
static [entityKind] = "BunSQLiteDatabase";
|
|
3620
|
+
}
|
|
3621
|
+
function construct(client, config = {}) {
|
|
3622
|
+
const dialect = new SQLiteSyncDialect({ casing: config.casing });
|
|
3623
|
+
let logger;
|
|
3624
|
+
if (config.logger === true) {
|
|
3625
|
+
logger = new DefaultLogger;
|
|
3626
|
+
} else if (config.logger !== false) {
|
|
3627
|
+
logger = config.logger;
|
|
3628
|
+
}
|
|
3629
|
+
let schema;
|
|
3630
|
+
if (config.schema) {
|
|
3631
|
+
const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
|
|
3632
|
+
schema = {
|
|
3633
|
+
fullSchema: config.schema,
|
|
3634
|
+
schema: tablesConfig.tables,
|
|
3635
|
+
tableNamesMap: tablesConfig.tableNamesMap
|
|
3636
|
+
};
|
|
3637
|
+
}
|
|
3638
|
+
const session = new SQLiteBunSession(client, dialect, schema, { logger });
|
|
3639
|
+
const db = new BunSQLiteDatabase("sync", dialect, session, schema);
|
|
3640
|
+
db.$client = client;
|
|
3641
|
+
return db;
|
|
3642
|
+
}
|
|
3643
|
+
function drizzle(...params) {
|
|
3644
|
+
if (params[0] === undefined || typeof params[0] === "string") {
|
|
3645
|
+
const instance = params[0] === undefined ? new Database : new Database(params[0]);
|
|
3646
|
+
return construct(instance, params[1]);
|
|
3647
|
+
}
|
|
3648
|
+
if (isConfig(params[0])) {
|
|
3649
|
+
const { connection, client, ...drizzleConfig } = params[0];
|
|
3650
|
+
if (client)
|
|
3651
|
+
return construct(client, drizzleConfig);
|
|
3652
|
+
if (typeof connection === "object") {
|
|
3653
|
+
const { source, ...opts } = connection;
|
|
3654
|
+
const options = Object.values(opts).filter((v) => v !== undefined).length ? opts : undefined;
|
|
3655
|
+
const instance2 = new Database(source, options);
|
|
3656
|
+
return construct(instance2, drizzleConfig);
|
|
3657
|
+
}
|
|
3658
|
+
const instance = new Database(connection);
|
|
3659
|
+
return construct(instance, drizzleConfig);
|
|
3660
|
+
}
|
|
3661
|
+
return construct(params[0], params[1]);
|
|
3662
|
+
}
|
|
3663
|
+
((drizzle2) => {
|
|
3664
|
+
function mock(config) {
|
|
3665
|
+
return construct({}, config);
|
|
3666
|
+
}
|
|
3667
|
+
drizzle2.mock = mock;
|
|
3668
|
+
})(drizzle || (drizzle = {}));
|
|
3669
|
+
|
|
3670
|
+
// node_modules/drizzle-orm/migrator.js
|
|
3671
|
+
import crypto from "crypto";
|
|
3672
|
+
import fs from "fs";
|
|
3673
|
+
function readMigrationFiles(config) {
|
|
3674
|
+
const migrationFolderTo = config.migrationsFolder;
|
|
3675
|
+
const migrationQueries = [];
|
|
3676
|
+
const journalPath = `${migrationFolderTo}/meta/_journal.json`;
|
|
3677
|
+
if (!fs.existsSync(journalPath)) {
|
|
3678
|
+
throw new Error(`Can't find meta/_journal.json file`);
|
|
3679
|
+
}
|
|
3680
|
+
const journalAsString = fs.readFileSync(`${migrationFolderTo}/meta/_journal.json`).toString();
|
|
3681
|
+
const journal = JSON.parse(journalAsString);
|
|
3682
|
+
for (const journalEntry of journal.entries) {
|
|
3683
|
+
const migrationPath = `${migrationFolderTo}/${journalEntry.tag}.sql`;
|
|
3684
|
+
try {
|
|
3685
|
+
const query = fs.readFileSync(`${migrationFolderTo}/${journalEntry.tag}.sql`).toString();
|
|
3686
|
+
const result = query.split("--> statement-breakpoint").map((it) => {
|
|
3687
|
+
return it;
|
|
3688
|
+
});
|
|
3689
|
+
migrationQueries.push({
|
|
3690
|
+
sql: result,
|
|
3691
|
+
bps: journalEntry.breakpoints,
|
|
3692
|
+
folderMillis: journalEntry.when,
|
|
3693
|
+
hash: crypto.createHash("sha256").update(query).digest("hex")
|
|
3694
|
+
});
|
|
3695
|
+
} catch {
|
|
3696
|
+
throw new Error(`No file ${migrationPath} found in ${migrationFolderTo} folder`);
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
return migrationQueries;
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
// node_modules/drizzle-orm/bun-sqlite/migrator.js
|
|
3703
|
+
function migrate(db, config) {
|
|
3704
|
+
const migrations = readMigrationFiles(config);
|
|
3705
|
+
db.dialect.migrate(migrations, db.session, config);
|
|
3706
|
+
}
|
|
3707
|
+
|
|
3708
|
+
// src/db/index.ts
|
|
3709
|
+
import { Database as Database2 } from "bun:sqlite";
|
|
3710
|
+
import { mkdirSync } from "fs";
|
|
3711
|
+
import { dirname, join, resolve } from "path";
|
|
3712
|
+
import { homedir } from "os";
|
|
3713
|
+
|
|
3714
|
+
// src/db/schema.ts
|
|
3715
|
+
var exports_schema = {};
|
|
3716
|
+
__export(exports_schema, {
|
|
3717
|
+
trainingJobs: () => trainingJobs,
|
|
3718
|
+
trainingDatasets: () => trainingDatasets,
|
|
3719
|
+
fineTunedModels: () => fineTunedModels
|
|
3720
|
+
});
|
|
3721
|
+
var fineTunedModels = sqliteTable("fine_tuned_models", {
|
|
3722
|
+
id: text("id").primaryKey(),
|
|
3723
|
+
baseModel: text("base_model").notNull(),
|
|
3724
|
+
name: text("name").notNull(),
|
|
3725
|
+
provider: text("provider", { enum: ["openai", "thinker-labs"] }).notNull(),
|
|
3726
|
+
status: text("status", {
|
|
3727
|
+
enum: ["pending", "running", "succeeded", "failed", "cancelled"]
|
|
3728
|
+
}).notNull().default("pending"),
|
|
3729
|
+
fineTuneJobId: text("fine_tune_job_id"),
|
|
3730
|
+
displayName: text("display_name"),
|
|
3731
|
+
description: text("description"),
|
|
3732
|
+
collection: text("collection"),
|
|
3733
|
+
tags: text("tags"),
|
|
3734
|
+
createdAt: integer("created_at").notNull(),
|
|
3735
|
+
updatedAt: integer("updated_at").notNull()
|
|
3736
|
+
});
|
|
3737
|
+
var trainingJobs = sqliteTable("training_jobs", {
|
|
3738
|
+
id: text("id").primaryKey(),
|
|
3739
|
+
modelId: text("model_id").notNull().references(() => fineTunedModels.id),
|
|
3740
|
+
provider: text("provider").notNull(),
|
|
3741
|
+
status: text("status").notNull(),
|
|
3742
|
+
startedAt: integer("started_at").notNull(),
|
|
3743
|
+
finishedAt: integer("finished_at"),
|
|
3744
|
+
metrics: text("metrics"),
|
|
3745
|
+
error: text("error")
|
|
3746
|
+
});
|
|
3747
|
+
var trainingDatasets = sqliteTable("training_datasets", {
|
|
3748
|
+
id: text("id").primaryKey(),
|
|
3749
|
+
source: text("source", {
|
|
3750
|
+
enum: ["todos", "mementos", "conversations", "sessions", "mixed"]
|
|
3751
|
+
}).notNull(),
|
|
3752
|
+
filePath: text("file_path").notNull(),
|
|
3753
|
+
exampleCount: integer("example_count").notNull(),
|
|
3754
|
+
createdAt: integer("created_at").notNull(),
|
|
3755
|
+
usedInJobId: text("used_in_job_id").references(() => trainingJobs.id)
|
|
3756
|
+
});
|
|
3757
|
+
|
|
3758
|
+
// src/db/index.ts
|
|
3759
|
+
var DEFAULT_DB_PATH = join(homedir(), ".brains", "brains.db");
|
|
3760
|
+
function ensureDir(filePath) {
|
|
3761
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
3762
|
+
}
|
|
3763
|
+
function getDb(dbPath) {
|
|
3764
|
+
const resolvedPath = dbPath ?? DEFAULT_DB_PATH;
|
|
3765
|
+
ensureDir(resolvedPath);
|
|
3766
|
+
const sqlite = new Database2(resolvedPath);
|
|
3767
|
+
sqlite.run("PRAGMA journal_mode = WAL");
|
|
3768
|
+
sqlite.run("PRAGMA foreign_keys = ON");
|
|
3769
|
+
const db = drizzle(sqlite, { schema: exports_schema });
|
|
3770
|
+
try {
|
|
3771
|
+
const migrationsFolder = resolve(import.meta.dir, "../../drizzle");
|
|
3772
|
+
migrate(db, { migrationsFolder });
|
|
3773
|
+
} catch {
|
|
3774
|
+
sqlite.exec(`
|
|
3775
|
+
CREATE TABLE IF NOT EXISTS fine_tuned_models (
|
|
3776
|
+
id TEXT PRIMARY KEY,
|
|
3777
|
+
base_model TEXT NOT NULL,
|
|
3778
|
+
name TEXT NOT NULL,
|
|
3779
|
+
provider TEXT NOT NULL,
|
|
3780
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
3781
|
+
fine_tune_job_id TEXT,
|
|
3782
|
+
display_name TEXT,
|
|
3783
|
+
description TEXT,
|
|
3784
|
+
collection TEXT,
|
|
3785
|
+
tags TEXT,
|
|
3786
|
+
created_at INTEGER NOT NULL,
|
|
3787
|
+
updated_at INTEGER NOT NULL
|
|
3788
|
+
);
|
|
3789
|
+
|
|
3790
|
+
CREATE TABLE IF NOT EXISTS training_jobs (
|
|
3791
|
+
id TEXT PRIMARY KEY,
|
|
3792
|
+
model_id TEXT NOT NULL REFERENCES fine_tuned_models(id),
|
|
3793
|
+
provider TEXT NOT NULL,
|
|
3794
|
+
status TEXT NOT NULL,
|
|
3795
|
+
started_at INTEGER NOT NULL,
|
|
3796
|
+
finished_at INTEGER,
|
|
3797
|
+
metrics TEXT,
|
|
3798
|
+
error TEXT
|
|
3799
|
+
);
|
|
3800
|
+
|
|
3801
|
+
CREATE TABLE IF NOT EXISTS training_datasets (
|
|
3802
|
+
id TEXT PRIMARY KEY,
|
|
3803
|
+
source TEXT NOT NULL,
|
|
3804
|
+
file_path TEXT NOT NULL,
|
|
3805
|
+
example_count INTEGER NOT NULL,
|
|
3806
|
+
created_at INTEGER NOT NULL,
|
|
3807
|
+
used_in_job_id TEXT REFERENCES training_jobs(id)
|
|
3808
|
+
);
|
|
3809
|
+
`);
|
|
3810
|
+
}
|
|
3811
|
+
return db;
|
|
3812
|
+
}
|
|
3813
|
+
|
|
3814
|
+
// src/lib/package-metadata.ts
|
|
3815
|
+
import { existsSync, readFileSync } from "fs";
|
|
3816
|
+
import { dirname as dirname2, resolve as resolve2 } from "path";
|
|
3817
|
+
import { fileURLToPath } from "url";
|
|
3818
|
+
var DEFAULT_VERSION = "0.0.0";
|
|
3819
|
+
var cachedVersion;
|
|
3820
|
+
function getPackageJsonPath() {
|
|
3821
|
+
return resolve2(dirname2(fileURLToPath(import.meta.url)), "../../package.json");
|
|
3822
|
+
}
|
|
3823
|
+
function getPackageVersion() {
|
|
3824
|
+
if (cachedVersion) {
|
|
3825
|
+
return cachedVersion;
|
|
3826
|
+
}
|
|
3827
|
+
const packageJsonPath = getPackageJsonPath();
|
|
3828
|
+
if (!existsSync(packageJsonPath)) {
|
|
3829
|
+
cachedVersion = DEFAULT_VERSION;
|
|
3830
|
+
return cachedVersion;
|
|
3831
|
+
}
|
|
3832
|
+
try {
|
|
3833
|
+
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
|
|
3834
|
+
cachedVersion = typeof packageJson.version === "string" ? packageJson.version : DEFAULT_VERSION;
|
|
3835
|
+
} catch {
|
|
3836
|
+
cachedVersion = DEFAULT_VERSION;
|
|
3837
|
+
}
|
|
3838
|
+
return cachedVersion;
|
|
3839
|
+
}
|
|
3840
|
+
|
|
3841
|
+
// src/lib/gatherers/todos.ts
|
|
3842
|
+
import { Database as Database3 } from "bun:sqlite";
|
|
3843
|
+
import { homedir as homedir2 } from "os";
|
|
3844
|
+
import { join as join2 } from "path";
|
|
3845
|
+
var SYSTEM_PROMPT = "You are a task management assistant that helps users create, update, search, and manage tasks and projects.";
|
|
3846
|
+
function taskToCreateExample(task) {
|
|
3847
|
+
const userMsg = `Create a task: ${task.title}${task.description ? `
|
|
3848
|
+
|
|
3849
|
+
Description: ${task.description}` : ""}`;
|
|
3850
|
+
const taskDetails = {
|
|
3851
|
+
id: task.short_id ?? task.id,
|
|
3852
|
+
title: task.title,
|
|
3853
|
+
description: task.description ?? "",
|
|
3854
|
+
status: task.status,
|
|
3855
|
+
priority: task.priority,
|
|
3856
|
+
tags: JSON.parse(task.tags ?? "[]"),
|
|
3857
|
+
created_at: task.created_at
|
|
3858
|
+
};
|
|
3859
|
+
return {
|
|
3860
|
+
messages: [
|
|
3861
|
+
{ role: "system", content: SYSTEM_PROMPT },
|
|
3862
|
+
{ role: "user", content: userMsg },
|
|
3863
|
+
{ role: "assistant", content: `Created task: ${JSON.stringify(taskDetails, null, 2)}` }
|
|
3864
|
+
]
|
|
3865
|
+
};
|
|
3866
|
+
}
|
|
3867
|
+
function taskToStatusUpdateExample(task) {
|
|
3868
|
+
if (!task.completed_at && task.status === "pending")
|
|
3869
|
+
return null;
|
|
3870
|
+
const id = task.short_id ?? task.id;
|
|
3871
|
+
return {
|
|
3872
|
+
messages: [
|
|
3873
|
+
{ role: "system", content: SYSTEM_PROMPT },
|
|
3874
|
+
{ role: "user", content: `Mark task ${id} as ${task.status}` },
|
|
3875
|
+
{ role: "assistant", content: `Task ${id} has been updated to status: ${task.status}. ${task.completed_at ? `Completed at: ${task.completed_at}` : ""}`.trim() }
|
|
3876
|
+
]
|
|
3877
|
+
};
|
|
3878
|
+
}
|
|
3879
|
+
function taskToSearchExample(tasks, query) {
|
|
3880
|
+
const matched = tasks.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())).slice(0, 5);
|
|
3881
|
+
return {
|
|
3882
|
+
messages: [
|
|
3883
|
+
{ role: "system", content: SYSTEM_PROMPT },
|
|
3884
|
+
{ role: "user", content: `Search tasks for: "${query}"` },
|
|
3885
|
+
{
|
|
3886
|
+
role: "assistant",
|
|
3887
|
+
content: matched.length > 0 ? `Found ${matched.length} task(s):
|
|
3888
|
+
${matched.map((t) => `- [${t.short_id ?? t.id}] ${t.title} (${t.status})`).join(`
|
|
3889
|
+
`)}` : `No tasks found matching "${query}".`
|
|
3890
|
+
}
|
|
3891
|
+
]
|
|
3892
|
+
};
|
|
3893
|
+
}
|
|
3894
|
+
async function gatherFromTodos(options = {}) {
|
|
3895
|
+
const dbPath = join2(homedir2(), ".todos", "todos.db");
|
|
3896
|
+
const db = new Database3(dbPath, { readonly: true, create: false });
|
|
3897
|
+
try {
|
|
3898
|
+
let query = "SELECT * FROM tasks WHERE 1=1";
|
|
3899
|
+
const params = [];
|
|
3900
|
+
if (options.since) {
|
|
3901
|
+
query += " AND created_at >= ?";
|
|
3902
|
+
params.push(options.since.toISOString());
|
|
3903
|
+
}
|
|
3904
|
+
query += " ORDER BY created_at DESC";
|
|
3905
|
+
if (options.limit) {
|
|
3906
|
+
query += " LIMIT ?";
|
|
3907
|
+
params.push(options.limit * 2);
|
|
3908
|
+
}
|
|
3909
|
+
const tasks = db.query(query).all(...params);
|
|
3910
|
+
const examples = [];
|
|
3911
|
+
for (const task of tasks) {
|
|
3912
|
+
examples.push(taskToCreateExample(task));
|
|
3913
|
+
const statusEx = taskToStatusUpdateExample(task);
|
|
3914
|
+
if (statusEx)
|
|
3915
|
+
examples.push(statusEx);
|
|
3916
|
+
}
|
|
3917
|
+
const searchTerms = ["urgent", "fix", "implement", "create", "update", "review"];
|
|
3918
|
+
for (const term of searchTerms) {
|
|
3919
|
+
examples.push(taskToSearchExample(tasks, term));
|
|
3920
|
+
}
|
|
3921
|
+
const finalExamples = options.limit ? examples.slice(0, options.limit) : examples;
|
|
3922
|
+
return {
|
|
3923
|
+
source: "todos",
|
|
3924
|
+
examples: finalExamples,
|
|
3925
|
+
count: finalExamples.length
|
|
3926
|
+
};
|
|
3927
|
+
} finally {
|
|
3928
|
+
db.close();
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
// src/lib/gatherers/mementos.ts
|
|
3933
|
+
import { Database as Database4 } from "bun:sqlite";
|
|
3934
|
+
import { homedir as homedir3 } from "os";
|
|
3935
|
+
import { join as join3 } from "path";
|
|
3936
|
+
var SYSTEM_PROMPT2 = "You are an AI assistant with persistent memory. You can remember and recall information across sessions to provide better, more personalized assistance.";
|
|
3937
|
+
function memoryToRecallExample(memory) {
|
|
3938
|
+
return {
|
|
3939
|
+
messages: [
|
|
3940
|
+
{ role: "system", content: SYSTEM_PROMPT2 },
|
|
3941
|
+
{ role: "user", content: `What do you remember about "${memory.key}"?` },
|
|
3942
|
+
{
|
|
3943
|
+
role: "assistant",
|
|
3944
|
+
content: memory.summary ? `${memory.value}
|
|
3945
|
+
|
|
3946
|
+
Summary: ${memory.summary}` : memory.value
|
|
3947
|
+
}
|
|
3948
|
+
]
|
|
3949
|
+
};
|
|
3950
|
+
}
|
|
3951
|
+
function memoryToSaveExample(memory) {
|
|
3952
|
+
const tags = JSON.parse(memory.tags ?? "[]");
|
|
3953
|
+
return {
|
|
3954
|
+
messages: [
|
|
3955
|
+
{ role: "system", content: SYSTEM_PROMPT2 },
|
|
3956
|
+
{
|
|
3957
|
+
role: "user",
|
|
3958
|
+
content: `Remember this for me: ${memory.key} = ${memory.value}${tags.length ? ` (tags: ${tags.join(", ")})` : ""}`
|
|
3959
|
+
},
|
|
3960
|
+
{
|
|
3961
|
+
role: "assistant",
|
|
3962
|
+
content: `Saved to memory: "${memory.key}" with ${memory.category} category, importance ${memory.importance}/10, scope: ${memory.scope}.`
|
|
3963
|
+
}
|
|
3964
|
+
]
|
|
3965
|
+
};
|
|
3966
|
+
}
|
|
3967
|
+
function memoryToSearchExample(memories, category) {
|
|
3968
|
+
const matched = memories.filter((m) => m.category === category && m.status === "active").slice(0, 5);
|
|
3969
|
+
return {
|
|
3970
|
+
messages: [
|
|
3971
|
+
{ role: "system", content: SYSTEM_PROMPT2 },
|
|
3972
|
+
{ role: "user", content: `What ${category} memories do you have?` },
|
|
3973
|
+
{
|
|
3974
|
+
role: "assistant",
|
|
3975
|
+
content: matched.length > 0 ? `Here are my ${category} memories:
|
|
3976
|
+
${matched.map((m) => `- ${m.key}: ${m.value.slice(0, 120)}${m.value.length > 120 ? "..." : ""}`).join(`
|
|
3977
|
+
`)}` : `I don't have any ${category} memories stored yet.`
|
|
3978
|
+
}
|
|
3979
|
+
]
|
|
3980
|
+
};
|
|
3981
|
+
}
|
|
3982
|
+
async function gatherFromMementos(options = {}) {
|
|
3983
|
+
const dbPath = join3(homedir3(), ".mementos", "mementos.db");
|
|
3984
|
+
const db = new Database4(dbPath, { readonly: true, create: false });
|
|
3985
|
+
try {
|
|
3986
|
+
let query = "SELECT * FROM memories WHERE status = 'active'";
|
|
3987
|
+
const params = [];
|
|
3988
|
+
if (options.since) {
|
|
3989
|
+
query += " AND created_at >= ?";
|
|
3990
|
+
params.push(options.since.toISOString());
|
|
3991
|
+
}
|
|
3992
|
+
query += " ORDER BY importance DESC, created_at DESC";
|
|
3993
|
+
if (options.limit) {
|
|
3994
|
+
query += " LIMIT ?";
|
|
3995
|
+
params.push(options.limit * 3);
|
|
3996
|
+
}
|
|
3997
|
+
const memories = db.query(query).all(...params);
|
|
3998
|
+
const examples = [];
|
|
3999
|
+
for (const memory of memories) {
|
|
4000
|
+
examples.push(memoryToRecallExample(memory));
|
|
4001
|
+
examples.push(memoryToSaveExample(memory));
|
|
4002
|
+
}
|
|
4003
|
+
const categories = [...new Set(memories.map((m) => m.category))];
|
|
4004
|
+
for (const category of categories) {
|
|
4005
|
+
examples.push(memoryToSearchExample(memories, category));
|
|
4006
|
+
}
|
|
4007
|
+
const finalExamples = options.limit ? examples.slice(0, options.limit) : examples;
|
|
4008
|
+
return {
|
|
4009
|
+
source: "mementos",
|
|
4010
|
+
examples: finalExamples,
|
|
4011
|
+
count: finalExamples.length
|
|
4012
|
+
};
|
|
4013
|
+
} finally {
|
|
4014
|
+
db.close();
|
|
4015
|
+
}
|
|
4016
|
+
}
|
|
4017
|
+
|
|
4018
|
+
// src/lib/gatherers/conversations.ts
|
|
4019
|
+
import { Database as Database5 } from "bun:sqlite";
|
|
4020
|
+
import { homedir as homedir4 } from "os";
|
|
4021
|
+
import { join as join4 } from "path";
|
|
4022
|
+
var SYSTEM_PROMPT3 = "You are a helpful AI assistant participating in multi-agent conversations. You communicate clearly and collaboratively with other agents and users.";
|
|
4023
|
+
function windowToExample(window) {
|
|
4024
|
+
if (window.length < 2)
|
|
4025
|
+
return null;
|
|
4026
|
+
const messages = [
|
|
4027
|
+
{ role: "system", content: SYSTEM_PROMPT3 }
|
|
4028
|
+
];
|
|
4029
|
+
for (let i = 0;i < window.length - 1; i++) {
|
|
4030
|
+
const msg = window[i];
|
|
4031
|
+
if (!msg)
|
|
4032
|
+
continue;
|
|
4033
|
+
const role = i % 2 === 0 ? "user" : "assistant";
|
|
4034
|
+
messages.push({
|
|
4035
|
+
role,
|
|
4036
|
+
content: `[${msg.from_agent} \u2192 ${msg.to_agent ?? msg.space ?? "all"}]: ${msg.content}`
|
|
4037
|
+
});
|
|
4038
|
+
}
|
|
4039
|
+
const last = window[window.length - 1];
|
|
4040
|
+
if (!last)
|
|
4041
|
+
return null;
|
|
4042
|
+
messages.push({
|
|
4043
|
+
role: "assistant",
|
|
4044
|
+
content: `[${last.from_agent} \u2192 ${last.to_agent ?? last.space ?? "all"}]: ${last.content}`
|
|
4045
|
+
});
|
|
4046
|
+
return { messages };
|
|
4047
|
+
}
|
|
4048
|
+
async function gatherFromConversations(options = {}) {
|
|
4049
|
+
const dbPath = join4(homedir4(), ".conversations", "messages.db");
|
|
4050
|
+
const db = new Database5(dbPath, { readonly: true, create: false });
|
|
4051
|
+
try {
|
|
4052
|
+
let query = "SELECT * FROM messages WHERE 1=1";
|
|
4053
|
+
const params = [];
|
|
4054
|
+
if (options.since) {
|
|
4055
|
+
query += " AND created_at >= ?";
|
|
4056
|
+
params.push(options.since.toISOString());
|
|
4057
|
+
}
|
|
4058
|
+
query += " ORDER BY session_id, created_at ASC";
|
|
4059
|
+
const allMessages = db.query(query).all(...params);
|
|
4060
|
+
const sessions = new Map;
|
|
4061
|
+
for (const msg of allMessages) {
|
|
4062
|
+
const msgs = sessions.get(msg.session_id) ?? [];
|
|
4063
|
+
msgs.push(msg);
|
|
4064
|
+
sessions.set(msg.session_id, msgs);
|
|
4065
|
+
}
|
|
4066
|
+
const examples = [];
|
|
4067
|
+
const windowSize = 4;
|
|
4068
|
+
for (const [, sessionMsgs] of sessions) {
|
|
4069
|
+
if (sessionMsgs.length < 2)
|
|
4070
|
+
continue;
|
|
4071
|
+
for (let start = 0;start <= sessionMsgs.length - 2; start++) {
|
|
4072
|
+
const end = Math.min(start + windowSize, sessionMsgs.length);
|
|
4073
|
+
const window = sessionMsgs.slice(start, end);
|
|
4074
|
+
const example = windowToExample(window);
|
|
4075
|
+
if (example)
|
|
4076
|
+
examples.push(example);
|
|
4077
|
+
}
|
|
4078
|
+
}
|
|
4079
|
+
const finalExamples = options.limit ? examples.slice(0, options.limit) : examples;
|
|
4080
|
+
return {
|
|
4081
|
+
source: "conversations",
|
|
4082
|
+
examples: finalExamples,
|
|
4083
|
+
count: finalExamples.length
|
|
4084
|
+
};
|
|
4085
|
+
} finally {
|
|
4086
|
+
db.close();
|
|
4087
|
+
}
|
|
4088
|
+
}
|
|
4089
|
+
|
|
4090
|
+
// src/lib/gatherers/sessions.ts
|
|
4091
|
+
import { readdir, readFile, stat } from "fs/promises";
|
|
4092
|
+
import { existsSync as existsSync2 } from "fs";
|
|
4093
|
+
import { join as join5 } from "path";
|
|
4094
|
+
import { homedir as homedir5 } from "os";
|
|
4095
|
+
var SYSTEM_PROMPT4 = "You are Claude Code, an AI assistant built by Anthropic that helps developers with coding, architecture, debugging, and software engineering tasks.";
|
|
4096
|
+
function extractText(content) {
|
|
4097
|
+
if (typeof content === "string")
|
|
4098
|
+
return content;
|
|
4099
|
+
return content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join(`
|
|
4100
|
+
`).trim();
|
|
4101
|
+
}
|
|
4102
|
+
async function gatherFromSessions(options = {}) {
|
|
4103
|
+
const { limit = 1000 } = options;
|
|
4104
|
+
const examples = [];
|
|
4105
|
+
const claudeDir = join5(homedir5(), ".claude", "projects");
|
|
4106
|
+
if (!existsSync2(claudeDir)) {
|
|
4107
|
+
return { source: "sessions", examples: [], count: 0 };
|
|
4108
|
+
}
|
|
4109
|
+
const projectDirs = await readdir(claudeDir).catch(() => []);
|
|
4110
|
+
for (const projectDir of projectDirs) {
|
|
4111
|
+
if (examples.length >= limit)
|
|
4112
|
+
break;
|
|
4113
|
+
const projectPath = join5(claudeDir, projectDir);
|
|
4114
|
+
const files = await readdir(projectPath).catch(() => []);
|
|
4115
|
+
for (const file of files) {
|
|
4116
|
+
if (examples.length >= limit)
|
|
4117
|
+
break;
|
|
4118
|
+
if (!file.endsWith(".jsonl"))
|
|
4119
|
+
continue;
|
|
4120
|
+
const filePath = join5(projectPath, file);
|
|
4121
|
+
if (options.since) {
|
|
4122
|
+
const fileStat = await stat(filePath).catch(() => null);
|
|
4123
|
+
if (fileStat && fileStat.mtime < options.since)
|
|
4124
|
+
continue;
|
|
4125
|
+
}
|
|
4126
|
+
const content = await readFile(filePath, "utf-8").catch(() => "");
|
|
4127
|
+
if (!content.trim())
|
|
4128
|
+
continue;
|
|
4129
|
+
const lines = content.trim().split(`
|
|
4130
|
+
`);
|
|
4131
|
+
const turns = [];
|
|
4132
|
+
for (const line of lines) {
|
|
4133
|
+
try {
|
|
4134
|
+
const entry = JSON.parse(line);
|
|
4135
|
+
if ((entry.type === "user" || entry.type === "human") && entry.message?.content) {
|
|
4136
|
+
const text2 = extractText(entry.message.content);
|
|
4137
|
+
if (text2.trim())
|
|
4138
|
+
turns.push({ role: "user", content: text2.trim() });
|
|
4139
|
+
} else if (entry.type === "assistant" && entry.message?.content) {
|
|
4140
|
+
const text2 = extractText(entry.message.content);
|
|
4141
|
+
if (text2.trim())
|
|
4142
|
+
turns.push({ role: "assistant", content: text2.trim() });
|
|
4143
|
+
}
|
|
4144
|
+
} catch {}
|
|
4145
|
+
}
|
|
4146
|
+
const windowSize = 6;
|
|
4147
|
+
for (let start = 0;start < turns.length - 1 && examples.length < limit; start++) {
|
|
4148
|
+
const window = turns.slice(start, start + windowSize);
|
|
4149
|
+
if (!window[0] || window[0].role !== "user")
|
|
4150
|
+
continue;
|
|
4151
|
+
const lastAssistantIdx = window.map((t) => t.role).lastIndexOf("assistant");
|
|
4152
|
+
if (lastAssistantIdx < 1)
|
|
4153
|
+
continue;
|
|
4154
|
+
const usedTurns = window.slice(0, lastAssistantIdx + 1);
|
|
4155
|
+
examples.push({
|
|
4156
|
+
messages: [
|
|
4157
|
+
{ role: "system", content: SYSTEM_PROMPT4 },
|
|
4158
|
+
...usedTurns
|
|
4159
|
+
]
|
|
4160
|
+
});
|
|
4161
|
+
}
|
|
4162
|
+
}
|
|
4163
|
+
}
|
|
4164
|
+
return { source: "sessions", examples, count: examples.length };
|
|
4165
|
+
}
|
|
4166
|
+
|
|
4167
|
+
// src/lib/gatherers/styles.ts
|
|
4168
|
+
var SYSTEM_PROMPT5 = "You are a design-aware AI assistant with knowledge of the user's style preferences, design system, and visual identity. You help apply consistent styling across projects.";
|
|
4169
|
+
async function gatherFromStyles(options = {}) {
|
|
4170
|
+
let sdk;
|
|
4171
|
+
try {
|
|
4172
|
+
sdk = await import("@hasnaxyz/styles");
|
|
4173
|
+
} catch {
|
|
4174
|
+
return { source: "styles", examples: [], count: 0 };
|
|
4175
|
+
}
|
|
4176
|
+
const sdkAny = sdk;
|
|
4177
|
+
if (typeof sdkAny["gatherTrainingData"] === "function") {
|
|
4178
|
+
return sdkAny["gatherTrainingData"](options);
|
|
4179
|
+
}
|
|
4180
|
+
const examples = [];
|
|
4181
|
+
const limit = options.limit ?? 500;
|
|
4182
|
+
try {
|
|
4183
|
+
if (typeof sdk.listProfiles === "function") {
|
|
4184
|
+
const profiles = await sdk.listProfiles();
|
|
4185
|
+
for (const profile of profiles.slice(0, Math.floor(limit / 3))) {
|
|
4186
|
+
const p = profile;
|
|
4187
|
+
examples.push({
|
|
4188
|
+
messages: [
|
|
4189
|
+
{ role: "system", content: SYSTEM_PROMPT5 },
|
|
4190
|
+
{ role: "user", content: `What are the style settings in the "${String(p["name"] ?? "default")}" profile?` },
|
|
4191
|
+
{ role: "assistant", content: `Style profile "${String(p["name"] ?? "default")}": ${JSON.stringify(p, null, 2)}` }
|
|
4192
|
+
]
|
|
4193
|
+
});
|
|
4194
|
+
}
|
|
4195
|
+
}
|
|
4196
|
+
if (typeof sdk.listPrefs === "function") {
|
|
4197
|
+
const prefs = await sdk.listPrefs();
|
|
4198
|
+
for (const pref of prefs.slice(0, Math.floor(limit / 3))) {
|
|
4199
|
+
const pr = pref;
|
|
4200
|
+
examples.push({
|
|
4201
|
+
messages: [
|
|
4202
|
+
{ role: "system", content: SYSTEM_PROMPT5 },
|
|
4203
|
+
{ role: "user", content: `What is my preference for "${String(pr["key"] ?? pr["name"] ?? "style")}"?` },
|
|
4204
|
+
{ role: "assistant", content: `Your preference: ${String(pr["value"] ?? JSON.stringify(pr))}` }
|
|
4205
|
+
]
|
|
4206
|
+
});
|
|
4207
|
+
}
|
|
4208
|
+
}
|
|
4209
|
+
} catch {}
|
|
4210
|
+
const finalExamples = examples.slice(0, limit);
|
|
4211
|
+
return { source: "styles", examples: finalExamples, count: finalExamples.length };
|
|
4212
|
+
}
|
|
4213
|
+
|
|
4214
|
+
// src/lib/gatherers/researcher.ts
|
|
4215
|
+
var SYSTEM_PROMPT6 = "You are a scientific research assistant that helps design experiments, form hypotheses, and interpret results.";
|
|
4216
|
+
async function gatherFromResearcher(options = {}) {
|
|
4217
|
+
let sdk;
|
|
4218
|
+
try {
|
|
4219
|
+
sdk = await import("@hasna/researcher");
|
|
4220
|
+
} catch {
|
|
4221
|
+
return { source: "researcher", examples: [], count: 0 };
|
|
4222
|
+
}
|
|
4223
|
+
if (typeof sdk["gatherTrainingData"] === "function") {
|
|
4224
|
+
return sdk["gatherTrainingData"](options);
|
|
4225
|
+
}
|
|
4226
|
+
const examples = [];
|
|
4227
|
+
const limit = options.limit ?? 500;
|
|
4228
|
+
try {
|
|
4229
|
+
if (typeof sdk["listProjects"] === "function") {
|
|
4230
|
+
const projects = await sdk["listProjects"]();
|
|
4231
|
+
for (const proj of projects.slice(0, Math.floor(limit / 2))) {
|
|
4232
|
+
const p = proj;
|
|
4233
|
+
examples.push({
|
|
4234
|
+
messages: [
|
|
4235
|
+
{ role: "system", content: SYSTEM_PROMPT6 },
|
|
4236
|
+
{ role: "user", content: `Summarize the research project "${String(p["name"] ?? p["id"])}"` },
|
|
4237
|
+
{ role: "assistant", content: `Project "${String(p["name"] ?? p["id"])}": ${String(p["description"] ?? JSON.stringify(p))}` }
|
|
4238
|
+
]
|
|
4239
|
+
});
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
if (typeof sdk["listResults"] === "function") {
|
|
4243
|
+
const results = await sdk["listResults"]();
|
|
4244
|
+
for (const result of results.slice(0, Math.floor(limit / 2))) {
|
|
4245
|
+
const r = result;
|
|
4246
|
+
examples.push({
|
|
4247
|
+
messages: [
|
|
4248
|
+
{ role: "system", content: SYSTEM_PROMPT6 },
|
|
4249
|
+
{ role: "user", content: `What were the results of experiment "${String(r["name"] ?? r["id"])}"?` },
|
|
4250
|
+
{ role: "assistant", content: `Result: ${String(r["summary"] ?? r["output"] ?? JSON.stringify(r))}` }
|
|
4251
|
+
]
|
|
4252
|
+
});
|
|
4253
|
+
}
|
|
4254
|
+
}
|
|
4255
|
+
} catch {}
|
|
4256
|
+
const finalExamples = examples.slice(0, limit);
|
|
4257
|
+
return { source: "researcher", examples: finalExamples, count: finalExamples.length };
|
|
4258
|
+
}
|
|
4259
|
+
|
|
4260
|
+
// src/lib/gatherers/tickets.ts
|
|
4261
|
+
var SYSTEM_PROMPT7 = "You are an issue management assistant that triages bugs, prioritizes features, and tracks incident resolutions.";
|
|
4262
|
+
async function gatherFromTickets(options = {}) {
|
|
4263
|
+
let sdk;
|
|
4264
|
+
try {
|
|
4265
|
+
sdk = await import("@hasna/tickets");
|
|
4266
|
+
} catch {
|
|
4267
|
+
return { source: "tickets", examples: [], count: 0 };
|
|
4268
|
+
}
|
|
4269
|
+
if (typeof sdk["gatherTrainingData"] === "function") {
|
|
4270
|
+
return sdk["gatherTrainingData"](options);
|
|
4271
|
+
}
|
|
4272
|
+
const examples = [];
|
|
4273
|
+
const limit = options.limit ?? 500;
|
|
4274
|
+
try {
|
|
4275
|
+
if (typeof sdk["listTickets"] === "function") {
|
|
4276
|
+
const tickets = await sdk["listTickets"]();
|
|
4277
|
+
for (const ticket of tickets.slice(0, limit)) {
|
|
4278
|
+
const t = ticket;
|
|
4279
|
+
examples.push({
|
|
4280
|
+
messages: [
|
|
4281
|
+
{ role: "system", content: SYSTEM_PROMPT7 },
|
|
4282
|
+
{ role: "user", content: `What is the status of ticket "${String(t["title"] ?? t["id"])}"?` },
|
|
4283
|
+
{ role: "assistant", content: `Ticket "${String(t["title"] ?? t["id"])}" [${String(t["status"] ?? "open")}/${String(t["priority"] ?? "medium")}]: ${String(t["description"] ?? "(no description)")}` }
|
|
4284
|
+
]
|
|
4285
|
+
});
|
|
4286
|
+
}
|
|
4287
|
+
}
|
|
4288
|
+
} catch {}
|
|
4289
|
+
const finalExamples = examples.slice(0, limit);
|
|
4290
|
+
return { source: "tickets", examples: finalExamples, count: finalExamples.length };
|
|
4291
|
+
}
|
|
4292
|
+
|
|
4293
|
+
// src/lib/gatherers/economy.ts
|
|
4294
|
+
var SYSTEM_PROMPT8 = "You are a cost-aware AI assistant that tracks API usage, identifies expensive patterns, and helps optimize AI spending.";
|
|
4295
|
+
async function gatherFromEconomy(options = {}) {
|
|
4296
|
+
let sdk;
|
|
4297
|
+
try {
|
|
4298
|
+
sdk = await import("@hasna/economy");
|
|
4299
|
+
} catch {
|
|
4300
|
+
return { source: "economy", examples: [], count: 0 };
|
|
4301
|
+
}
|
|
4302
|
+
if (typeof sdk["gatherTrainingData"] === "function") {
|
|
4303
|
+
return sdk["gatherTrainingData"](options);
|
|
4304
|
+
}
|
|
4305
|
+
const examples = [];
|
|
4306
|
+
const limit = options.limit ?? 500;
|
|
4307
|
+
try {
|
|
4308
|
+
const listSessions = sdk["listSessions"] ?? sdk["getSessions"] ?? sdk["getCostSummary"];
|
|
4309
|
+
if (typeof listSessions === "function") {
|
|
4310
|
+
const sessions = await listSessions();
|
|
4311
|
+
const items = Array.isArray(sessions) ? sessions : [sessions];
|
|
4312
|
+
for (const session of items.slice(0, Math.floor(limit / 2))) {
|
|
4313
|
+
const s = session;
|
|
4314
|
+
examples.push({
|
|
4315
|
+
messages: [
|
|
4316
|
+
{ role: "system", content: SYSTEM_PROMPT8 },
|
|
4317
|
+
{ role: "user", content: `How much did session "${String(s["session_id"] ?? s["id"] ?? "unknown")}" cost?` },
|
|
4318
|
+
{ role: "assistant", content: `Session cost: $${String(s["total_cost"] ?? s["cost"] ?? "0.00")} \u2014 ${String(s["model"] ?? "unknown model")}, ${String(s["total_tokens"] ?? s["tokens"] ?? "?")} tokens` }
|
|
4319
|
+
]
|
|
4320
|
+
});
|
|
4321
|
+
}
|
|
4322
|
+
}
|
|
4323
|
+
const getModelBreakdown = sdk["getModelBreakdown"];
|
|
4324
|
+
if (typeof getModelBreakdown === "function") {
|
|
4325
|
+
const breakdown = await getModelBreakdown();
|
|
4326
|
+
examples.push({
|
|
4327
|
+
messages: [
|
|
4328
|
+
{ role: "system", content: SYSTEM_PROMPT8 },
|
|
4329
|
+
{ role: "user", content: "Which AI models have I spent the most on?" },
|
|
4330
|
+
{ role: "assistant", content: `Model cost breakdown: ${JSON.stringify(breakdown, null, 2)}` }
|
|
4331
|
+
]
|
|
4332
|
+
});
|
|
4333
|
+
}
|
|
4334
|
+
} catch {}
|
|
4335
|
+
const finalExamples = examples.slice(0, limit);
|
|
4336
|
+
return { source: "economy", examples: finalExamples, count: finalExamples.length };
|
|
4337
|
+
}
|
|
4338
|
+
|
|
4339
|
+
// src/lib/gatherers/recordings.ts
|
|
4340
|
+
var SYSTEM_PROMPT9 = "You are a voice-aware AI assistant that transcribes, searches, and summarizes audio recordings.";
|
|
4341
|
+
async function gatherFromRecordings(options = {}) {
|
|
4342
|
+
let sdk;
|
|
4343
|
+
try {
|
|
4344
|
+
sdk = await import("@hasna/recordings");
|
|
4345
|
+
} catch {
|
|
4346
|
+
return { source: "recordings", examples: [], count: 0 };
|
|
4347
|
+
}
|
|
4348
|
+
if (typeof sdk["gatherTrainingData"] === "function") {
|
|
4349
|
+
return sdk["gatherTrainingData"](options);
|
|
4350
|
+
}
|
|
4351
|
+
const examples = [];
|
|
4352
|
+
const limit = options.limit ?? 500;
|
|
4353
|
+
try {
|
|
4354
|
+
if (typeof sdk["listRecordings"] === "function") {
|
|
4355
|
+
const recordings = await sdk["listRecordings"]();
|
|
4356
|
+
for (const rec of recordings.slice(0, limit)) {
|
|
4357
|
+
const r = rec;
|
|
4358
|
+
if (r["transcription"] || r["transcript"]) {
|
|
4359
|
+
const transcript = String(r["transcription"] ?? r["transcript"]);
|
|
4360
|
+
examples.push({
|
|
4361
|
+
messages: [
|
|
4362
|
+
{ role: "system", content: SYSTEM_PROMPT9 },
|
|
4363
|
+
{ role: "user", content: `Summarize the recording "${String(r["fileName"] ?? r["name"] ?? r["id"])}"` },
|
|
4364
|
+
{ role: "assistant", content: transcript.slice(0, 2000) }
|
|
4365
|
+
]
|
|
4366
|
+
});
|
|
4367
|
+
const words = transcript.split(" ").slice(0, 3).join(" ");
|
|
4368
|
+
examples.push({
|
|
4369
|
+
messages: [
|
|
4370
|
+
{ role: "system", content: SYSTEM_PROMPT9 },
|
|
4371
|
+
{ role: "user", content: `Find recordings mentioning "${words}"` },
|
|
4372
|
+
{ role: "assistant", content: `Found recording: "${String(r["fileName"] ?? r["name"])}" \u2014 ${new Date(Number(r["createdAt"] ?? Date.now())).toLocaleDateString()}` }
|
|
4373
|
+
]
|
|
4374
|
+
});
|
|
4375
|
+
}
|
|
4376
|
+
}
|
|
4377
|
+
}
|
|
4378
|
+
} catch {}
|
|
4379
|
+
const finalExamples = examples.slice(0, limit);
|
|
4380
|
+
return { source: "recordings", examples: finalExamples, count: finalExamples.length };
|
|
4381
|
+
}
|
|
4382
|
+
|
|
4383
|
+
// src/lib/gatherers/assistants.ts
|
|
4384
|
+
var SYSTEM_PROMPT10 = "You are a personal AI assistant with full context of the user's work environment, preferences, ongoing tasks, contacts, and projects.";
|
|
4385
|
+
async function gatherFromAssistants(options = {}) {
|
|
4386
|
+
let sdk;
|
|
4387
|
+
try {
|
|
4388
|
+
sdk = await import("@hasna/assistants");
|
|
4389
|
+
} catch {
|
|
4390
|
+
return { source: "assistants", examples: [], count: 0 };
|
|
4391
|
+
}
|
|
4392
|
+
if (typeof sdk["gatherTrainingData"] === "function") {
|
|
4393
|
+
return sdk["gatherTrainingData"](options);
|
|
4394
|
+
}
|
|
4395
|
+
const examples = [];
|
|
4396
|
+
const limit = options.limit ?? 500;
|
|
4397
|
+
try {
|
|
4398
|
+
const listSessions = sdk["listSessions"] ?? sdk["getSessions"];
|
|
4399
|
+
if (typeof listSessions === "function") {
|
|
4400
|
+
const sessions = await listSessions();
|
|
4401
|
+
for (const session of sessions.slice(0, Math.floor(limit / 2))) {
|
|
4402
|
+
const s = session;
|
|
4403
|
+
const messages = s["messages"];
|
|
4404
|
+
if (messages && messages.length >= 2) {
|
|
4405
|
+
const turns = messages.filter((m) => m["role"] === "user" || m["role"] === "assistant").slice(0, 6).map((m) => ({ role: m["role"], content: String(m["content"] ?? "") }));
|
|
4406
|
+
if (turns.length >= 2) {
|
|
4407
|
+
examples.push({ messages: [{ role: "system", content: SYSTEM_PROMPT10 }, ...turns] });
|
|
4408
|
+
}
|
|
4409
|
+
}
|
|
4410
|
+
}
|
|
4411
|
+
}
|
|
4412
|
+
} catch {}
|
|
4413
|
+
const finalExamples = examples.slice(0, limit);
|
|
4414
|
+
return { source: "assistants", examples: finalExamples, count: finalExamples.length };
|
|
4415
|
+
}
|
|
4416
|
+
|
|
4417
|
+
// src/lib/gatherers/registry.ts
|
|
4418
|
+
var registry = new Map;
|
|
4419
|
+
function registerGatherer(provider) {
|
|
4420
|
+
registry.set(provider.name, provider);
|
|
4421
|
+
}
|
|
4422
|
+
function getRegisteredSources() {
|
|
4423
|
+
return Array.from(registry.keys()).sort();
|
|
4424
|
+
}
|
|
4425
|
+
function getGatherer(name) {
|
|
4426
|
+
return registry.get(name)?.gather;
|
|
4427
|
+
}
|
|
4428
|
+
registerGatherer({
|
|
4429
|
+
name: "todos",
|
|
4430
|
+
gather: gatherFromTodos,
|
|
4431
|
+
description: "Task management data from @hasna/todos",
|
|
4432
|
+
package: "@hasna/todos"
|
|
4433
|
+
});
|
|
4434
|
+
registerGatherer({
|
|
4435
|
+
name: "mementos",
|
|
4436
|
+
gather: gatherFromMementos,
|
|
4437
|
+
description: "Agent memory data from @hasna/mementos",
|
|
4438
|
+
package: "@hasna/mementos"
|
|
4439
|
+
});
|
|
4440
|
+
registerGatherer({
|
|
4441
|
+
name: "conversations",
|
|
4442
|
+
gather: gatherFromConversations,
|
|
4443
|
+
description: "Multi-agent conversation data from @hasna/conversations",
|
|
4444
|
+
package: "@hasna/conversations"
|
|
4445
|
+
});
|
|
4446
|
+
registerGatherer({
|
|
4447
|
+
name: "sessions",
|
|
4448
|
+
gather: gatherFromSessions,
|
|
4449
|
+
description: "Claude Code session transcripts from ~/.claude/projects",
|
|
4450
|
+
package: "@hasna/sessions"
|
|
4451
|
+
});
|
|
4452
|
+
registerGatherer({
|
|
4453
|
+
name: "styles",
|
|
4454
|
+
gather: gatherFromStyles,
|
|
4455
|
+
description: "Style preferences and profiles from @hasnaxyz/styles",
|
|
4456
|
+
package: "@hasnaxyz/styles"
|
|
4457
|
+
});
|
|
4458
|
+
registerGatherer({
|
|
4459
|
+
name: "researcher",
|
|
4460
|
+
gather: gatherFromResearcher,
|
|
4461
|
+
description: "Experiment results and research projects from @hasna/researcher",
|
|
4462
|
+
package: "@hasna/researcher"
|
|
4463
|
+
});
|
|
4464
|
+
registerGatherer({
|
|
4465
|
+
name: "tickets",
|
|
4466
|
+
gather: gatherFromTickets,
|
|
4467
|
+
description: "Bug reports and feature requests from @hasna/tickets",
|
|
4468
|
+
package: "@hasna/tickets"
|
|
4469
|
+
});
|
|
4470
|
+
registerGatherer({
|
|
4471
|
+
name: "economy",
|
|
4472
|
+
gather: gatherFromEconomy,
|
|
4473
|
+
description: "AI cost and usage data from @hasna/economy",
|
|
4474
|
+
package: "@hasna/economy"
|
|
4475
|
+
});
|
|
4476
|
+
registerGatherer({
|
|
4477
|
+
name: "recordings",
|
|
4478
|
+
gather: gatherFromRecordings,
|
|
4479
|
+
description: "Audio transcripts and recordings from @hasna/recordings",
|
|
4480
|
+
package: "@hasna/recordings"
|
|
4481
|
+
});
|
|
4482
|
+
registerGatherer({
|
|
4483
|
+
name: "assistants",
|
|
4484
|
+
gather: gatherFromAssistants,
|
|
4485
|
+
description: "Personal assistant session history from @hasna/assistants",
|
|
4486
|
+
package: "@hasna/assistants"
|
|
4487
|
+
});
|
|
4488
|
+
// src/lib/gatherers/index.ts
|
|
4489
|
+
async function gatherAll(sources, options = {}) {
|
|
4490
|
+
const targets = sources.includes("all") ? getRegisteredSources() : sources;
|
|
4491
|
+
const results = await Promise.allSettled(targets.map((source) => {
|
|
4492
|
+
const fn = getGatherer(source);
|
|
4493
|
+
if (!fn)
|
|
4494
|
+
return Promise.resolve({ source, examples: [], count: 0 });
|
|
4495
|
+
return fn(options);
|
|
4496
|
+
}));
|
|
4497
|
+
return results.filter((r) => r.status === "fulfilled").map((r) => r.value);
|
|
4498
|
+
}
|
|
3
4499
|
|
|
4
4500
|
// src/server/index.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4501
|
+
import { mkdirSync as mkdirSync2, writeFileSync } from "fs";
|
|
4502
|
+
import { join as join6 } from "path";
|
|
4503
|
+
import { homedir as homedir6 } from "os";
|
|
4504
|
+
function json(data, status = 200) {
|
|
4505
|
+
return Response.json(data, { status });
|
|
4506
|
+
}
|
|
4507
|
+
function notFound() {
|
|
4508
|
+
return json({ error: "not found" }, 404);
|
|
4509
|
+
}
|
|
4510
|
+
function badRequest(message) {
|
|
4511
|
+
return json({ error: message }, 400);
|
|
4512
|
+
}
|
|
4513
|
+
function createServerFetchHandler() {
|
|
4514
|
+
return function fetch(req) {
|
|
10
4515
|
const url = new URL(req.url);
|
|
11
|
-
|
|
12
|
-
|
|
4516
|
+
const { pathname } = url;
|
|
4517
|
+
const method = req.method.toUpperCase();
|
|
4518
|
+
if (pathname === "/health" && method === "GET") {
|
|
4519
|
+
return json({ status: "ok", service: "brains", version: getPackageVersion() });
|
|
4520
|
+
}
|
|
4521
|
+
if (pathname === "/models" && method === "GET") {
|
|
4522
|
+
return handleListModels();
|
|
4523
|
+
}
|
|
4524
|
+
const modelMatch = pathname.match(/^\/models\/([^/]+)$/);
|
|
4525
|
+
if (modelMatch?.[1]) {
|
|
4526
|
+
const id = modelMatch[1];
|
|
4527
|
+
if (method === "GET")
|
|
4528
|
+
return handleGetModel(id);
|
|
4529
|
+
if (method === "PATCH")
|
|
4530
|
+
return handleUpdateModel(id, req);
|
|
4531
|
+
}
|
|
4532
|
+
if (pathname === "/jobs" && method === "GET") {
|
|
4533
|
+
return handleListJobs();
|
|
4534
|
+
}
|
|
4535
|
+
const jobMatch = pathname.match(/^\/jobs\/([^/]+)$/);
|
|
4536
|
+
if (jobMatch?.[1] && method === "GET") {
|
|
4537
|
+
return handleGetJob(jobMatch[1]);
|
|
13
4538
|
}
|
|
14
|
-
|
|
4539
|
+
if (pathname === "/datasets" && method === "GET") {
|
|
4540
|
+
return handleListDatasets();
|
|
4541
|
+
}
|
|
4542
|
+
if (pathname === "/datasets/gather" && method === "POST") {
|
|
4543
|
+
return handleGather(req);
|
|
4544
|
+
}
|
|
4545
|
+
return notFound();
|
|
4546
|
+
};
|
|
4547
|
+
}
|
|
4548
|
+
async function handleListModels() {
|
|
4549
|
+
const db = getDb();
|
|
4550
|
+
const models = await db.select().from(fineTunedModels).orderBy(desc(fineTunedModels.createdAt));
|
|
4551
|
+
return json(models);
|
|
4552
|
+
}
|
|
4553
|
+
async function handleGetModel(id) {
|
|
4554
|
+
const db = getDb();
|
|
4555
|
+
const [model] = await db.select().from(fineTunedModels).where(eq(fineTunedModels.id, id));
|
|
4556
|
+
if (!model)
|
|
4557
|
+
return notFound();
|
|
4558
|
+
return json(model);
|
|
4559
|
+
}
|
|
4560
|
+
async function handleUpdateModel(id, req) {
|
|
4561
|
+
const db = getDb();
|
|
4562
|
+
const [existing] = await db.select().from(fineTunedModels).where(eq(fineTunedModels.id, id));
|
|
4563
|
+
if (!existing)
|
|
4564
|
+
return notFound();
|
|
4565
|
+
let body;
|
|
4566
|
+
try {
|
|
4567
|
+
body = await req.json();
|
|
4568
|
+
} catch {
|
|
4569
|
+
return badRequest("Invalid JSON body");
|
|
15
4570
|
}
|
|
16
|
-
|
|
4571
|
+
const allowed = ["displayName", "description", "collection", "tags"];
|
|
4572
|
+
const updates = { updatedAt: Date.now() };
|
|
4573
|
+
for (const key of allowed) {
|
|
4574
|
+
if (key in body) {
|
|
4575
|
+
if (key === "tags" && Array.isArray(body[key])) {
|
|
4576
|
+
updates[key] = JSON.stringify(body[key]);
|
|
4577
|
+
} else if (typeof body[key] === "string") {
|
|
4578
|
+
updates[key] = body[key];
|
|
4579
|
+
}
|
|
4580
|
+
}
|
|
4581
|
+
}
|
|
4582
|
+
await db.update(fineTunedModels).set(updates).where(eq(fineTunedModels.id, id));
|
|
4583
|
+
const [updated] = await db.select().from(fineTunedModels).where(eq(fineTunedModels.id, id));
|
|
4584
|
+
return json(updated);
|
|
4585
|
+
}
|
|
4586
|
+
async function handleListJobs() {
|
|
4587
|
+
const db = getDb();
|
|
4588
|
+
const jobs = await db.select().from(trainingJobs).orderBy(desc(trainingJobs.startedAt));
|
|
4589
|
+
return json(jobs);
|
|
4590
|
+
}
|
|
4591
|
+
async function handleGetJob(id) {
|
|
4592
|
+
const db = getDb();
|
|
4593
|
+
const [job] = await db.select().from(trainingJobs).where(eq(trainingJobs.id, id));
|
|
4594
|
+
if (!job)
|
|
4595
|
+
return notFound();
|
|
4596
|
+
return json(job);
|
|
4597
|
+
}
|
|
4598
|
+
async function handleListDatasets() {
|
|
4599
|
+
const db = getDb();
|
|
4600
|
+
const datasets = await db.select().from(trainingDatasets).orderBy(desc(trainingDatasets.createdAt));
|
|
4601
|
+
return json(datasets);
|
|
4602
|
+
}
|
|
4603
|
+
async function handleGather(req) {
|
|
4604
|
+
let body;
|
|
4605
|
+
try {
|
|
4606
|
+
body = await req.json();
|
|
4607
|
+
} catch {
|
|
4608
|
+
return badRequest("Invalid JSON body");
|
|
4609
|
+
}
|
|
4610
|
+
const sources = body.sources ?? ["todos", "mementos", "conversations", "sessions"];
|
|
4611
|
+
const limit = body.limit ?? 500;
|
|
4612
|
+
const outDir = body.output_dir ?? join6(homedir6(), ".brains", "datasets");
|
|
4613
|
+
mkdirSync2(outDir, { recursive: true });
|
|
4614
|
+
const results = await gatherAll(sources, { limit });
|
|
4615
|
+
const db = getDb();
|
|
4616
|
+
const now = Date.now();
|
|
4617
|
+
const saved = [];
|
|
4618
|
+
for (const result of results) {
|
|
4619
|
+
if (result.count === 0)
|
|
4620
|
+
continue;
|
|
4621
|
+
const fileName = `${result.source}-${now}.jsonl`;
|
|
4622
|
+
const filePath = join6(outDir, fileName);
|
|
4623
|
+
writeFileSync(filePath, result.examples.map((e) => JSON.stringify(e)).join(`
|
|
4624
|
+
`) + `
|
|
4625
|
+
`, "utf8");
|
|
4626
|
+
const id = randomUUID();
|
|
4627
|
+
await db.insert(trainingDatasets).values({
|
|
4628
|
+
id,
|
|
4629
|
+
source: result.source,
|
|
4630
|
+
filePath,
|
|
4631
|
+
exampleCount: result.count,
|
|
4632
|
+
createdAt: now
|
|
4633
|
+
});
|
|
4634
|
+
saved.push({ id, source: result.source, count: result.count, file_path: filePath });
|
|
4635
|
+
}
|
|
4636
|
+
return json({ datasets: saved, total_examples: saved.reduce((s, d) => s + d.count, 0) });
|
|
4637
|
+
}
|
|
4638
|
+
var port = Number(process.env["PORT"] ?? 7020);
|
|
4639
|
+
if (import.meta.main) {
|
|
4640
|
+
console.log(`brains server starting on port ${port}`);
|
|
4641
|
+
Bun.serve({ port, fetch: createServerFetchHandler() });
|
|
4642
|
+
}
|
|
4643
|
+
export {
|
|
4644
|
+
createServerFetchHandler
|
|
4645
|
+
};
|