@m6d/cortex 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/drizzle.d.ts +461 -5
- package/dist/drizzle.js +172 -44
- package/dist/{index-z0594rs3.js → index-jw8cnjqv.js} +159 -124
- package/dist/index.d.ts +1592 -240
- package/dist/index.js +352 -179
- package/package.json +2 -14
package/dist/drizzle.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CortexError,
|
|
3
3
|
FUNCTION_SIGNATURES,
|
|
4
|
+
datasetColumnSchema,
|
|
4
5
|
filterRefs,
|
|
5
6
|
groupKeyName,
|
|
6
7
|
isColumnValue
|
|
7
|
-
} from "./index-
|
|
8
|
+
} from "./index-jw8cnjqv.js";
|
|
8
9
|
|
|
9
10
|
// src/datasets/drizzle.ts
|
|
10
11
|
import {
|
|
@@ -35,7 +36,8 @@ import {
|
|
|
35
36
|
sum,
|
|
36
37
|
Column,
|
|
37
38
|
is,
|
|
38
|
-
SQL
|
|
39
|
+
SQL,
|
|
40
|
+
Subquery
|
|
39
41
|
} from "drizzle-orm";
|
|
40
42
|
import { SQLiteTimestamp } from "drizzle-orm/sqlite-core";
|
|
41
43
|
function columnTypeOf(column) {
|
|
@@ -52,6 +54,27 @@ function columnTypeOf(column) {
|
|
|
52
54
|
return "string";
|
|
53
55
|
return;
|
|
54
56
|
}
|
|
57
|
+
function isInstant(column) {
|
|
58
|
+
return column.dataType === "object date" && /^(timestamp|datetime2?|smalldatetime|integer)\b/.test(column.getSQLType());
|
|
59
|
+
}
|
|
60
|
+
function clockOf(timeZone) {
|
|
61
|
+
if (!timeZone)
|
|
62
|
+
return 0;
|
|
63
|
+
try {
|
|
64
|
+
const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" }).formatToParts().find((part) => part.type === "timeZoneName")?.value;
|
|
65
|
+
const [, sign, hours, minutes] = /([+-])(\d\d):(\d\d)/.exec(name ?? "") ?? [];
|
|
66
|
+
return sign ? (sign === "-" ? -1 : 1) * (Number(hours) * 60 + Number(minutes)) : 0;
|
|
67
|
+
} catch {
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function onClock(instant, clock) {
|
|
72
|
+
const reading = new Date(instant.getTime() + clock * 60000);
|
|
73
|
+
if (Number.isNaN(reading.getTime()))
|
|
74
|
+
return instant;
|
|
75
|
+
const offset = `${clock < 0 ? "-" : "+"}${new Date(Math.abs(clock) * 60000).toISOString().slice(11, 16)}`;
|
|
76
|
+
return reading.toISOString().replace(/(\.000)?Z$/, offset);
|
|
77
|
+
}
|
|
55
78
|
var DATE_TRUNC = {
|
|
56
79
|
postgres: (date, unit) => sql`cast(date_trunc(${sql.raw(`'${unit}'`)}, ${date}) as date)`,
|
|
57
80
|
mssql: (date, unit) => sql`CONVERT(varchar(10), DATETRUNC(${sql.raw(unit === "week" ? "iso_week" : unit)}, ${date}), 23)`,
|
|
@@ -70,23 +93,31 @@ var DATE_TRUNC = {
|
|
|
70
93
|
}
|
|
71
94
|
}
|
|
72
95
|
};
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
return
|
|
83
|
-
|
|
84
|
-
return textual ? sql`cast(${column} as datetime2)` : column;
|
|
85
|
-
case "sqlite":
|
|
86
|
-
if (sqlType !== "integer")
|
|
87
|
-
return column;
|
|
88
|
-
return is(column, SQLiteTimestamp) && column.mode === "timestamp_ms" ? sql`datetime(${column} / 1000.0, 'unixepoch')` : sql`datetime(${column}, 'unixepoch')`;
|
|
96
|
+
var DATE_SOURCE = {
|
|
97
|
+
postgres: (value, stored) => {
|
|
98
|
+
if (columnTypeOf(stored) !== "date")
|
|
99
|
+
return sql`cast(${value} as timestamp)`;
|
|
100
|
+
return stored.getSQLType().includes("with time zone") ? sql`(${value} at time zone 'UTC')` : value;
|
|
101
|
+
},
|
|
102
|
+
mssql: (value, stored) => columnTypeOf(stored) === "date" ? value : sql`cast(${value} as datetime2)`,
|
|
103
|
+
sqlite: (value, stored) => {
|
|
104
|
+
if (stored.getSQLType() !== "integer")
|
|
105
|
+
return value;
|
|
106
|
+
return is(stored, SQLiteTimestamp) && stored.mode === "timestamp_ms" ? sql`datetime(${value} / 1000.0, 'unixepoch')` : sql`datetime(${value}, 'unixepoch')`;
|
|
89
107
|
}
|
|
108
|
+
};
|
|
109
|
+
var ON_CLOCK = {
|
|
110
|
+
postgres: (date, clock) => sql`(${date} + interval '${sql.raw(String(clock))} minutes')`,
|
|
111
|
+
mssql: (date, clock) => {
|
|
112
|
+
const value = sql`cast(${date} as datetime2)`;
|
|
113
|
+
const past = sql.raw(clock > 0 ? `> dateadd(minute, ${-clock}, cast('9999-12-31T23:59:59.9999999' as datetime2))` : `< dateadd(minute, ${-clock}, cast('0001-01-01' as datetime2))`);
|
|
114
|
+
return sql`case when ${value} ${past} then ${value} else dateadd(minute, ${sql.raw(String(clock))}, ${value}) end`;
|
|
115
|
+
},
|
|
116
|
+
sqlite: (date, clock) => sql`coalesce(datetime(${date}, '${sql.raw(String(clock))} minutes'), ${date})`
|
|
117
|
+
};
|
|
118
|
+
function dateSource(dialect, { column, stored, clock }) {
|
|
119
|
+
const date = stored ? DATE_SOURCE[dialect](column, stored) : column;
|
|
120
|
+
return clock ? ON_CLOCK[dialect](date, clock) : date;
|
|
90
121
|
}
|
|
91
122
|
var DATE_PART = {
|
|
92
123
|
postgres: (date, unit) => sql`cast(extract(${sql.raw(unit === "dayOfWeek" ? "isodow" : unit)} from ${date}) as integer)`,
|
|
@@ -123,13 +154,21 @@ function drizzleDataset(options) {
|
|
|
123
154
|
});
|
|
124
155
|
const columns = picked.flatMap(([name, column]) => {
|
|
125
156
|
const type = options.types?.[name] ?? columnTypeOf(column);
|
|
126
|
-
|
|
157
|
+
if (!type)
|
|
158
|
+
return [];
|
|
159
|
+
const declared = options.values?.[name];
|
|
160
|
+
if (declared && type !== "string") {
|
|
161
|
+
throw new Error(`Dataset "${options.name}": only a string column lists its values, and ${name} is a ${type}`);
|
|
162
|
+
}
|
|
163
|
+
const values = declared ?? datasetColumnSchema.shape.values.safeParse(column.enumValues).data;
|
|
164
|
+
return [
|
|
127
165
|
{
|
|
128
166
|
name,
|
|
129
167
|
type,
|
|
130
|
-
description: options.descriptions?.[name] ?? ""
|
|
168
|
+
description: options.descriptions?.[name] ?? "",
|
|
169
|
+
...type === "string" && values && { values: [...values] }
|
|
131
170
|
}
|
|
132
|
-
]
|
|
171
|
+
];
|
|
133
172
|
});
|
|
134
173
|
const columnsByName = new Map(picked.map(([name, column]) => [name, column]));
|
|
135
174
|
let definition;
|
|
@@ -161,9 +200,19 @@ function drizzleDataset(options) {
|
|
|
161
200
|
};
|
|
162
201
|
return definition;
|
|
163
202
|
},
|
|
164
|
-
async run(query, user, signal) {
|
|
165
|
-
const
|
|
203
|
+
async run(query, user, signal, context) {
|
|
204
|
+
const clock = clockOf(context.timeZone);
|
|
205
|
+
const { statement, instants } = compile(dataset, options, query, user, clock);
|
|
206
|
+
refuseOversized(statement.getSQL());
|
|
207
|
+
const rows = await statement.execute();
|
|
166
208
|
signal.throwIfAborted();
|
|
209
|
+
for (const row of rows) {
|
|
210
|
+
for (const key of instants) {
|
|
211
|
+
const value = row[key];
|
|
212
|
+
if (value instanceof Date)
|
|
213
|
+
row[key] = onClock(value, clock);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
167
216
|
return rows;
|
|
168
217
|
}
|
|
169
218
|
};
|
|
@@ -177,7 +226,28 @@ function joinedOf(target, table, columnsByName) {
|
|
|
177
226
|
relations: target.relations()
|
|
178
227
|
};
|
|
179
228
|
}
|
|
180
|
-
|
|
229
|
+
var STATEMENT_MAX_PARTS = 50000;
|
|
230
|
+
function refuseOversized(statement) {
|
|
231
|
+
let left = STATEMENT_MAX_PARTS;
|
|
232
|
+
const walk = (chunk) => {
|
|
233
|
+
if (--left < 0) {
|
|
234
|
+
throw new CortexError("invalid_request", `The query writes out to more than ${STATEMENT_MAX_PARTS} parts of SQL; ask for fewer computed values or simpler ones`);
|
|
235
|
+
}
|
|
236
|
+
for (const part of partsOf(chunk))
|
|
237
|
+
walk(part);
|
|
238
|
+
};
|
|
239
|
+
walk(statement);
|
|
240
|
+
}
|
|
241
|
+
function partsOf(chunk) {
|
|
242
|
+
if (Array.isArray(chunk))
|
|
243
|
+
return chunk;
|
|
244
|
+
if (is(chunk, SQL))
|
|
245
|
+
return chunk.queryChunks;
|
|
246
|
+
if (is(chunk, Subquery))
|
|
247
|
+
return chunk._.isWith ? [] : [chunk._.sql];
|
|
248
|
+
return [];
|
|
249
|
+
}
|
|
250
|
+
function compile(root, options, query, user, clock) {
|
|
181
251
|
const { dialect, db } = options;
|
|
182
252
|
const { joined, joins } = joinRelations(root, query.join, user, db);
|
|
183
253
|
const resolve = (ref) => {
|
|
@@ -186,7 +256,14 @@ function compile(root, options, query, user) {
|
|
|
186
256
|
if (!table)
|
|
187
257
|
throw new CortexError("unsupported", `"${ref}" is not reachable`);
|
|
188
258
|
const name = ref.slice(dot + 1);
|
|
189
|
-
|
|
259
|
+
const column = columnOf(table, name);
|
|
260
|
+
const type = table.types.get(name) ?? "string";
|
|
261
|
+
return {
|
|
262
|
+
column,
|
|
263
|
+
type,
|
|
264
|
+
...type === "date" && { stored: column },
|
|
265
|
+
...isInstant(column) && { clock }
|
|
266
|
+
};
|
|
190
267
|
};
|
|
191
268
|
const shape = shapeOf(root, dialect, query, resolve);
|
|
192
269
|
const conditions = [
|
|
@@ -205,7 +282,10 @@ function compile(root, options, query, user) {
|
|
|
205
282
|
const { chain, target } = query.rank || query.qualify.length ? finished(dialect, db, select, shape, query) : { chain: select(shape.fields), target: (name) => sortTarget(shape, name) };
|
|
206
283
|
const orderings = query.sort.map(({ col, dir }) => ordering(dialect, target(col), dir));
|
|
207
284
|
const ordered = orderings.length ? chain.orderBy(...orderings) : chain;
|
|
208
|
-
return
|
|
285
|
+
return {
|
|
286
|
+
statement: capped(ordered, dialect, query, orderings.length > 0),
|
|
287
|
+
instants: Object.keys(shape.fields).filter((key) => shape.row(key).clock)
|
|
288
|
+
};
|
|
209
289
|
}
|
|
210
290
|
function ordering(dialect, target, dir) {
|
|
211
291
|
const term = dir === "asc" ? asc(target) : desc(target);
|
|
@@ -234,7 +314,7 @@ function finished(dialect, db, select, shape, query) {
|
|
|
234
314
|
if (rank && !layered)
|
|
235
315
|
fields[RANK] = rankSql(dialect, rank, shape.row);
|
|
236
316
|
let inner = select(fields).as("finished");
|
|
237
|
-
const outer = (ref) => ({ column: sql`${inner[ref]}
|
|
317
|
+
const outer = (ref) => ({ ...shape.row(ref), column: sql`${inner[ref]}` });
|
|
238
318
|
const qualified = and(...query.qualify.map((filter) => filterSql(dialect, filter, outer)));
|
|
239
319
|
if (rank && layered) {
|
|
240
320
|
const numbered = Object.fromEntries(Object.keys(fields).map((key) => [key, inner[key]]));
|
|
@@ -313,9 +393,9 @@ function shapeOf(root, dialect, query, resolve) {
|
|
|
313
393
|
const { fields, groupKeys } = grouped ? groupedFields(dialect, query, resolve, named) : plainFields(root, dialect, query, resolve, named);
|
|
314
394
|
for (const entry of query.window) {
|
|
315
395
|
const over = entry.partitionBy.map((col) => row(col).column);
|
|
316
|
-
const { expression,
|
|
396
|
+
const { expression, ...value } = aggregateOf(dialect, entry, row, over);
|
|
317
397
|
fields[entry.as] = expression.as(entry.as);
|
|
318
|
-
named.set(entry.as, { column: expression
|
|
398
|
+
named.set(entry.as, { ...value, column: expression });
|
|
319
399
|
}
|
|
320
400
|
for (const entry of query.compute) {
|
|
321
401
|
const value = operandSql(dialect, entry.expr, row);
|
|
@@ -334,12 +414,12 @@ function groupedFields(dialect, query, resolve, named) {
|
|
|
334
414
|
const key = is(value.column, Column) ? value.column : value.column.inlineParams();
|
|
335
415
|
fields[name] = is(key, Column) ? key : decoded(key, value.type);
|
|
336
416
|
groupKeys.push(key);
|
|
337
|
-
named.set(name, { column: key
|
|
417
|
+
named.set(name, { ...value, column: key });
|
|
338
418
|
}
|
|
339
419
|
for (const aggregate of query.aggregate) {
|
|
340
|
-
const { expression,
|
|
420
|
+
const { expression, ...value } = aggregateOf(dialect, aggregate, resolve);
|
|
341
421
|
fields[aggregate.as] = expression.as(aggregate.as);
|
|
342
|
-
named.set(aggregate.as, { column: expression
|
|
422
|
+
named.set(aggregate.as, { ...value, column: expression });
|
|
343
423
|
}
|
|
344
424
|
return { fields, groupKeys };
|
|
345
425
|
}
|
|
@@ -408,13 +488,14 @@ function operandSql(dialect, operand, resolve) {
|
|
|
408
488
|
return caseSql(dialect, operand, resolve);
|
|
409
489
|
if ("args" in operand) {
|
|
410
490
|
const args = operand.args.map((arg) => operandSql(dialect, arg, resolve));
|
|
491
|
+
const column = functionSql(dialect, operand.fn, args.map((arg) => arg.column));
|
|
411
492
|
return {
|
|
412
|
-
column
|
|
493
|
+
...builtFrom(column, args),
|
|
413
494
|
type: FUNCTION_SIGNATURES[operand.fn].answers ?? args[0].type
|
|
414
495
|
};
|
|
415
496
|
}
|
|
416
|
-
const date = dateSource(dialect, operandSql(dialect, operand.of, resolve)
|
|
417
|
-
return operand.fn === "dateTrunc" ? { column: DATE_TRUNC[dialect](date, operand.unit), type: "
|
|
497
|
+
const date = dateSource(dialect, operandSql(dialect, operand.of, resolve));
|
|
498
|
+
return operand.fn === "dateTrunc" ? { column: DATE_TRUNC[dialect](date, operand.unit), type: "date" } : { column: DATE_PART[dialect](date, operand.unit), type: "number" };
|
|
418
499
|
}
|
|
419
500
|
function literalSql(dialect, value) {
|
|
420
501
|
if (typeof value === "string") {
|
|
@@ -431,11 +512,38 @@ function caseSql(dialect, operand, resolve) {
|
|
|
431
512
|
}));
|
|
432
513
|
const fallback = operand.else === undefined ? undefined : operandSql(dialect, operand.else, resolve);
|
|
433
514
|
const whens = sql.join(branches.map(({ when, then }) => sql`when ${when} then ${then.column}`), sql` `);
|
|
515
|
+
const values = branches.map(({ then }) => then);
|
|
434
516
|
return {
|
|
435
|
-
|
|
517
|
+
...builtFrom(sql`case ${whens}${fallback ? sql` else ${fallback.column}` : sql``} end`, fallback ? [...values, fallback] : values),
|
|
436
518
|
type: fallback?.type ?? branches[0].then.type
|
|
437
519
|
};
|
|
438
520
|
}
|
|
521
|
+
function builtFrom(column, parts) {
|
|
522
|
+
const { stored, clock } = meeting(parts);
|
|
523
|
+
if (!stored)
|
|
524
|
+
return { column };
|
|
525
|
+
return { column: column.mapWith(stored), stored, ...clock !== undefined && { clock } };
|
|
526
|
+
}
|
|
527
|
+
function meeting(parts) {
|
|
528
|
+
const dates = parts.filter((part) => part.type === "date");
|
|
529
|
+
const clock = dates.find((part) => part.clock !== undefined)?.clock;
|
|
530
|
+
if (clock !== undefined && dates.some((part) => part.clock === undefined)) {
|
|
531
|
+
throw new CortexError("unsupported", "an instant cannot meet a calendar or truncated date; compare or combine like with like");
|
|
532
|
+
}
|
|
533
|
+
const kept = dates.flatMap((part) => part.stored ? [part.stored] : []);
|
|
534
|
+
const [stored] = kept;
|
|
535
|
+
if (stored && kept.some((other) => storageOf(other) !== storageOf(stored))) {
|
|
536
|
+
throw new CortexError("unsupported", "dates kept differently (in seconds and in milliseconds, say) cannot meet; compare or combine like with like");
|
|
537
|
+
}
|
|
538
|
+
return { stored, clock };
|
|
539
|
+
}
|
|
540
|
+
function storageOf(column) {
|
|
541
|
+
if (is(column, SQLiteTimestamp))
|
|
542
|
+
return column.mode;
|
|
543
|
+
if (columnTypeOf(column) !== "date")
|
|
544
|
+
return "text";
|
|
545
|
+
return column.getSQLType().includes("with time zone") ? "zoned" : "native";
|
|
546
|
+
}
|
|
439
547
|
function functionSql(dialect, fn, args) {
|
|
440
548
|
const [first, digits] = args;
|
|
441
549
|
switch (fn) {
|
|
@@ -469,7 +577,8 @@ function aggregateOf(dialect, aggregate, resolve, over) {
|
|
|
469
577
|
const partition = over.length ? sql`partition by ${sql.join(over, sql`, `)}` : sql``;
|
|
470
578
|
return sql`${fn} over (${partition})`;
|
|
471
579
|
};
|
|
472
|
-
const
|
|
580
|
+
const decoder = is(column, Column) ? column : operand?.stored;
|
|
581
|
+
const extreme = (expression) => decoder ? expression.mapWith(decoder) : decoded(expression, operand.type);
|
|
473
582
|
switch (aggregate.fn) {
|
|
474
583
|
case "count":
|
|
475
584
|
return {
|
|
@@ -492,15 +601,24 @@ function aggregateOf(dialect, aggregate, resolve, over) {
|
|
|
492
601
|
type: "number"
|
|
493
602
|
};
|
|
494
603
|
case "min":
|
|
495
|
-
return { expression: extreme(windowed(min(filtered)))
|
|
604
|
+
return { ...operand, expression: extreme(windowed(min(filtered))) };
|
|
496
605
|
case "max":
|
|
497
|
-
return { expression: extreme(windowed(max(filtered)))
|
|
606
|
+
return { ...operand, expression: extreme(windowed(max(filtered))) };
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
var OWN_OFFSET = /T[^Zz+-]*(?:[Zz]|[+-]\d{2}:?\d{2})$/;
|
|
610
|
+
function instantOf(text, clock) {
|
|
611
|
+
const iso = text.replace(/^(\d{4}-\d\d-\d\d)[t ](?=\d)/, "$1T");
|
|
612
|
+
const instant = OWN_OFFSET.test(iso) ? new Date(iso) : new Date(new Date(iso.includes("T") ? `${iso}Z` : iso).getTime() - clock * 60000);
|
|
613
|
+
if (!/^[+-]?\d{4}/.test(iso) || Number.isNaN(instant.getTime())) {
|
|
614
|
+
throw new CortexError("invalid_request", `"${text}" is not a date this host can read`);
|
|
498
615
|
}
|
|
616
|
+
return instant;
|
|
499
617
|
}
|
|
500
618
|
function coerce(type, value) {
|
|
501
619
|
switch (type) {
|
|
502
620
|
case "date":
|
|
503
|
-
return
|
|
621
|
+
return value;
|
|
504
622
|
case "number":
|
|
505
623
|
return typeof value === "string" ? Number(value) : value;
|
|
506
624
|
case "boolean":
|
|
@@ -514,13 +632,23 @@ function escapeLike(value) {
|
|
|
514
632
|
}
|
|
515
633
|
function condition(dialect, target, filter, resolve) {
|
|
516
634
|
const column = target.column;
|
|
517
|
-
const
|
|
518
|
-
const type = target.type === "date" && !
|
|
635
|
+
const stored = dialect !== "mssql" && target.stored && columnTypeOf(target.stored) === "date" ? target.stored : undefined;
|
|
636
|
+
const type = target.type === "date" && !stored ? "string" : target.type;
|
|
519
637
|
const literal = (value) => {
|
|
520
|
-
|
|
638
|
+
if (stored && typeof value === "string") {
|
|
639
|
+
const date = instantOf(value, target.clock ?? 0);
|
|
640
|
+
return is(target.column, Column) ? date : stored.mapToDriverValue(date);
|
|
641
|
+
}
|
|
642
|
+
const coerced = target.clock && typeof value === "string" ? instantOf(value, target.clock).toISOString().slice(0, -1) : coerce(type, value);
|
|
521
643
|
return typeof coerced === "string" || typeof coerced === "boolean" ? literalSql(dialect, coerced).column : coerced;
|
|
522
644
|
};
|
|
523
|
-
const scalar = () =>
|
|
645
|
+
const scalar = () => {
|
|
646
|
+
if (!isColumnValue(filter.value))
|
|
647
|
+
return literal(filter.value);
|
|
648
|
+
const right = operandSql(dialect, filter.value.col, resolve);
|
|
649
|
+
meeting([target, right]);
|
|
650
|
+
return right.column;
|
|
651
|
+
};
|
|
524
652
|
const list = () => filter.value.map(literal);
|
|
525
653
|
const text = () => typeof filter.value === "object" ? "" : String(filter.value);
|
|
526
654
|
switch (filter.op) {
|