symmetria 3.0.0 → 3.2.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 +3 -0
- package/dist/better-auth.js +1 -1
- package/dist/binding-CD-0xNaB.js +12 -0
- package/dist/binding-CD-0xNaB.js.map +1 -0
- package/dist/bun.d.ts +2 -2
- package/dist/bun.js +2 -2
- package/dist/cohere.d.ts +1 -1
- package/dist/cohere.js +1 -1
- package/dist/{compile-DBg43TmK.js → compile-DjpujkL0.js} +23 -375
- package/dist/compile-DjpujkL0.js.map +1 -0
- package/dist/{core-CEeH-SdY.js → core-Dp5RH0Yo.js} +40 -18
- package/dist/core-Dp5RH0Yo.js.map +1 -0
- package/dist/driver.d.ts +3 -3
- package/dist/driver.js +2 -2
- package/dist/{binding-jM09pXvJ.js → errors-DNyJuu6e.js} +2 -11
- package/dist/errors-DNyJuu6e.js.map +1 -0
- package/dist/freeze-D2-KMR2m.js +12 -0
- package/dist/freeze-D2-KMR2m.js.map +1 -0
- package/dist/google.d.ts +1 -1
- package/dist/google.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +287 -142
- package/dist/index.js.map +1 -1
- package/dist/{inspection-BpyRXQq2.js → inspection-EEYZ-Vum.js} +4 -3
- package/dist/{inspection-BpyRXQq2.js.map → inspection-EEYZ-Vum.js.map} +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +3 -3
- package/dist/jina.d.ts +1 -1
- package/dist/jina.js +1 -1
- package/dist/mistral.d.ts +1 -1
- package/dist/mistral.js +1 -1
- package/dist/ollama.d.ts +1 -1
- package/dist/ollama.js +1 -1
- package/dist/openai.d.ts +1 -1
- package/dist/openai.js +1 -1
- package/dist/opentelemetry.d.ts +41 -0
- package/dist/opentelemetry.js +119 -0
- package/dist/opentelemetry.js.map +1 -0
- package/dist/{pg-bSZhdk23.js → pg-CJrfdDU1.js} +25 -6
- package/dist/pg-CJrfdDU1.js.map +1 -0
- package/dist/{pg-B5rodRoT.d.ts → pg-DW0unCVP.d.ts} +9 -3
- package/dist/pg.d.ts +3 -3
- package/dist/pg.js +2 -2
- package/dist/{pool-BeY6o4Jw.js → pool-B1yUnKG2.js} +4 -4
- package/dist/{pool-BeY6o4Jw.js.map → pool-B1yUnKG2.js.map} +1 -1
- package/dist/{pool-XG_sgock.d.ts → pool-DBKtIrFz.d.ts} +2 -2
- package/dist/profiling-DsSQZPAk.js +381 -0
- package/dist/profiling-DsSQZPAk.js.map +1 -0
- package/dist/{search-pds-R0Yv.js → search-oHusY4j0.js} +3 -3
- package/dist/{search-pds-R0Yv.js.map → search-oHusY4j0.js.map} +1 -1
- package/dist/search-uCUvhR3s.js +49 -0
- package/dist/search-uCUvhR3s.js.map +1 -0
- package/dist/search.d.ts +1 -1
- package/dist/search.js +1 -1
- package/dist/{table-BtbqIgVL.js → table-CKBAYEu5.js} +37 -67
- package/dist/table-CKBAYEu5.js.map +1 -0
- package/dist/{types-C2s_w1LW.d.ts → types-DciQOtiw.d.ts} +6 -2
- package/dist/{types-y3lUm7aI.js → types-NVB9dmsW.js} +37 -4
- package/dist/types-NVB9dmsW.js.map +1 -0
- package/dist/{values-DX74earC.js → values-CnN8eqP3.js} +2 -2
- package/dist/{values-DX74earC.js.map → values-CnN8eqP3.js.map} +1 -1
- package/dist/vector.d.ts +1 -1
- package/dist/vector.js +1 -1
- package/dist/voyage.d.ts +1 -1
- package/dist/voyage.js +1 -1
- package/package.json +5 -1
- package/dist/binding-jM09pXvJ.js.map +0 -1
- package/dist/compile-DBg43TmK.js.map +0 -1
- package/dist/core-CEeH-SdY.js.map +0 -1
- package/dist/pg-bSZhdk23.js.map +0 -1
- package/dist/table-BtbqIgVL.js.map +0 -1
- package/dist/types-y3lUm7aI.js.map +0 -1
package/README.md
CHANGED
|
@@ -361,6 +361,9 @@ decode timings. Pass it to `postgres({ url, profiler })`, wrap requests with
|
|
|
361
361
|
`SYMMETRIA_PROFILE_TOKEN` for the application and the CLI, then open
|
|
362
362
|
`bunx --package symmetria-kit symmetria profile`.
|
|
363
363
|
|
|
364
|
+
`traced(driver, { tracer })` from `symmetria/opentelemetry` reports every
|
|
365
|
+
statement and transaction as an OpenTelemetry span.
|
|
366
|
+
|
|
364
367
|
## Drivers
|
|
365
368
|
|
|
366
369
|
Official drivers ship with `symmetria` and are maintained and released together:
|
package/dist/better-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { u as and, v as not, x as or } from "./core-Dp5RH0Yo.js";
|
|
2
2
|
import { createAdapterFactory } from "better-auth/adapters";
|
|
3
3
|
//#region src/entries/better-auth.ts
|
|
4
4
|
const escapeLike = (value) => String(value).replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/schema/binding.ts
|
|
2
|
+
/** Rebind compiled schema metadata without evaluating declaration callbacks again. */
|
|
3
|
+
const SCHEMA_BIND = Symbol("symmetria.schema.bind");
|
|
4
|
+
/** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */
|
|
5
|
+
const createDatabase = ({ schema: model, driver }) => {
|
|
6
|
+
if (!model || typeof model[SCHEMA_BIND] !== "function") throw new Error("symmetria: createDatabase() expects a schema() declaration");
|
|
7
|
+
return model[SCHEMA_BIND](driver);
|
|
8
|
+
};
|
|
9
|
+
//#endregion
|
|
10
|
+
export { createDatabase as n, SCHEMA_BIND as t };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=binding-CD-0xNaB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"binding-CD-0xNaB.js","names":[],"sources":["../src/schema/binding.ts"],"sourcesContent":["import type { Driver } from \"../query/plan/types\";\n\n/** Rebind compiled schema metadata without evaluating declaration callbacks again. */\nexport const SCHEMA_BIND = Symbol(\"symmetria.schema.bind\");\nexport type BindableSchema = {\n readonly [SCHEMA_BIND]: (driver: Driver) => unknown;\n};\n\nexport type DatabaseOptions<Model extends BindableSchema> = {\n readonly schema: Model;\n readonly driver: Driver;\n};\n\n/** Bind a reusable schema to a driver, retaining its inferred query API and scopes. */\nexport const createDatabase = <Model extends BindableSchema>({\n schema: model,\n driver,\n}: DatabaseOptions<Model>): ReturnType<Model[typeof SCHEMA_BIND]> => {\n if (!model || typeof model[SCHEMA_BIND] !== \"function\") {\n throw new Error(\n \"symmetria: createDatabase() expects a schema() declaration\",\n );\n }\n\n return model[SCHEMA_BIND](driver) as ReturnType<Model[typeof SCHEMA_BIND]>;\n};\n"],"mappings":";;AAGA,MAAa,cAAc,OAAO,uBAAuB;;AAWzD,MAAa,kBAAgD,EAC3D,QAAQ,OACR,aACmE;CACnE,IAAI,CAAC,SAAS,OAAO,MAAM,iBAAiB,YAC1C,MAAM,IAAI,MACR,4DACF;CAGF,OAAO,MAAM,YAAY,CAAC,MAAM;AAClC"}
|
package/dist/bun.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-
|
|
2
|
-
import { t as PostgresDriver } from "./pool-
|
|
1
|
+
import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-DciQOtiw.js";
|
|
2
|
+
import { t as PostgresDriver } from "./pool-DBKtIrFz.js";
|
|
3
3
|
import { SQL } from "bun";
|
|
4
4
|
//#region src/driver/bun.d.ts
|
|
5
5
|
type PostgresOptions = Omit<SQL.PostgresOrMySQLOptions, "adapter" | "bigint"> & {
|
package/dist/bun.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as SCHEMA_BIND } from "./binding-
|
|
2
|
-
import { n as postgresParameters, t as createPostgresDriver } from "./pool-
|
|
1
|
+
import { t as SCHEMA_BIND } from "./binding-CD-0xNaB.js";
|
|
2
|
+
import { n as postgresParameters, t as createPostgresDriver } from "./pool-B1yUnKG2.js";
|
|
3
3
|
import { SQL } from "bun";
|
|
4
4
|
//#region src/driver/bun.ts
|
|
5
5
|
/**
|
package/dist/cohere.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-
|
|
1
|
+
import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-DciQOtiw.js";
|
|
2
2
|
//#region src/entries/cohere.d.ts
|
|
3
3
|
export type CohereOptions = {
|
|
4
4
|
readonly apiKey?: string;
|
package/dist/cohere.js
CHANGED
|
@@ -1,375 +1,11 @@
|
|
|
1
|
-
import { a as containsBinding, c as numberedAlias, f as cloneParameter, g as createRowDecoder, o as mergeBindings, s as normalizeResult, t as DEFAULT_VALUE, u as bigintCodec, w as throwDataErrors, y as numericCodec } from "./types-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
1
|
+
import { a as containsBinding, c as numberedAlias, f as cloneParameter, g as createRowDecoder, o as mergeBindings, s as normalizeResult, t as DEFAULT_VALUE, u as bigintCodec, w as throwDataErrors, y as numericCodec } from "./types-NVB9dmsW.js";
|
|
2
|
+
import { G as createCompilation, J as renderContext, K as parameter, W as aliasSql, q as quoteIdentifier } from "./table-CKBAYEu5.js";
|
|
3
|
+
import { o as scopeViolationText } from "./errors-DNyJuu6e.js";
|
|
4
|
+
import { F as containsNode, N as expressionSqlType, P as childNodes } from "./core-Dp5RH0Yo.js";
|
|
5
|
+
import { t as freeze } from "./freeze-D2-KMR2m.js";
|
|
6
|
+
import { a as unconstrained, i as postgresRenderer, n as executorProfiling } from "./profiling-DsSQZPAk.js";
|
|
7
|
+
import { a as tsquerySql, n as searchRankSql, o as tsvectorSql, r as searchVectorSql, t as searchHeadlineSql } from "./search-uCUvhR3s.js";
|
|
8
8
|
import { isDeepStrictEqual } from "node:util";
|
|
9
|
-
//#region src/observability/http.ts
|
|
10
|
-
/** Small, portable HTTP listener for the opt-in profiler. */
|
|
11
|
-
const serveProfiler = async (options) => {
|
|
12
|
-
let port = options.port;
|
|
13
|
-
const hostname = options.hostname.includes(":") ? `[${options.hostname}]` : options.hostname;
|
|
14
|
-
const server = createServer(async (incoming, outgoing) => {
|
|
15
|
-
try {
|
|
16
|
-
const headers = new Headers();
|
|
17
|
-
for (const [name, value] of Object.entries(incoming.headers)) if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
18
|
-
const target = incoming.url ?? "/";
|
|
19
|
-
const request = new Request(new URL(`http://${hostname}:${port}${target.startsWith("/") ? target : `/${target}`}`).href, {
|
|
20
|
-
method: incoming.method ?? "GET",
|
|
21
|
-
headers
|
|
22
|
-
});
|
|
23
|
-
const response = await options.fetch(request, { port });
|
|
24
|
-
outgoing.writeHead(response.status, Object.fromEntries(response.headers));
|
|
25
|
-
outgoing.end(Buffer.from(await response.arrayBuffer()));
|
|
26
|
-
} catch {
|
|
27
|
-
outgoing.writeHead(500);
|
|
28
|
-
outgoing.end();
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
await new Promise((resolve, reject) => {
|
|
32
|
-
server.once("error", reject);
|
|
33
|
-
server.listen(options.port, options.hostname, () => {
|
|
34
|
-
server.off("error", reject);
|
|
35
|
-
resolve();
|
|
36
|
-
});
|
|
37
|
-
});
|
|
38
|
-
port = server.address().port;
|
|
39
|
-
let closing;
|
|
40
|
-
return Object.freeze({
|
|
41
|
-
port,
|
|
42
|
-
url: new URL(`http://${hostname}:${port}`),
|
|
43
|
-
stop: (force = false) => closing ??= new Promise((resolve, reject) => {
|
|
44
|
-
server.close((error) => error ? reject(error) : resolve());
|
|
45
|
-
if (force) server.closeAllConnections();
|
|
46
|
-
})
|
|
47
|
-
});
|
|
48
|
-
};
|
|
49
|
-
//#endregion
|
|
50
|
-
//#region src/query/compile/postgres/render.ts
|
|
51
|
-
/**
|
|
52
|
-
* PostgreSQL renderer: dialect-specific SQL for casts, JSON aggregation, arrays and operators.
|
|
53
|
-
*/
|
|
54
|
-
const jsonArray = (value) => `NULLIF((${value})::jsonb, 'null'::jsonb)`;
|
|
55
|
-
const jsonObject = (entries, jsonOutput) => {
|
|
56
|
-
const fields = entries.map(({ key, value }) => `${sqlString(key)}, ${value}`);
|
|
57
|
-
if (entries.length <= 50) return `${jsonOutput ? "json_build_object" : "jsonb_build_object"}(${fields.join(", ")})`;
|
|
58
|
-
const chunks = [];
|
|
59
|
-
for (let position = 0; position < entries.length; position += 50) chunks.push(`jsonb_build_object(${fields.slice(position, position + 50).join(", ")})`);
|
|
60
|
-
return `(${chunks.join(" || ")})${jsonOutput ? "::json" : ""}`;
|
|
61
|
-
};
|
|
62
|
-
/**
|
|
63
|
-
* An explicit cast to `varchar(5)` or `numeric(10,2)` silently cuts or rounds
|
|
64
|
-
* the value, so a bound value compared with such a column would match rows it
|
|
65
|
-
* does not equal. Casts state the base type only; assignment to a column still
|
|
66
|
-
* applies the column's own length and scale. `char(5)` becomes `bpchar`, the
|
|
67
|
-
* same type without a length: plain `char` would mean `char(1)` and cut the
|
|
68
|
-
* value to one character.
|
|
69
|
-
*/
|
|
70
|
-
const unconstrained = (type) => type.replace(/^(?:char|character|bpchar)\s*\([^)]*\)/i, "bpchar").replace(/^(varchar|character varying|numeric|decimal)\s*\([^)]*\)/i, "$1");
|
|
71
|
-
/** PostgreSQL SQL rendering, shared by every execution adapter. */
|
|
72
|
-
const postgresRenderer = {
|
|
73
|
-
placeholder: (position) => `$${position}`,
|
|
74
|
-
cast: (value, target) => {
|
|
75
|
-
switch (target.kind) {
|
|
76
|
-
case "parameter": return `${value}::text::${unconstrained(target.type)}`;
|
|
77
|
-
case "numeric": return `${value}::numeric`;
|
|
78
|
-
case "text": return target.array ? `(${value})::text[]` : `(${value})::text`;
|
|
79
|
-
case "typed": return `(${value})::${unconstrained(target.type)}`;
|
|
80
|
-
}
|
|
81
|
-
},
|
|
82
|
-
limitOffset: (limit, offset) => [...limit === void 0 ? [] : [`LIMIT ${limit}`], ...offset === void 0 ? [] : [`OFFSET ${offset}`]],
|
|
83
|
-
rowLock: (lock) => `FOR ${lock.mode}${lock.of ? ` OF ${lock.of.join(", ")}` : ""}${lock.noWait ? " NOWAIT" : lock.skipLocked ? " SKIP LOCKED" : ""}`,
|
|
84
|
-
textCast: {
|
|
85
|
-
prefix: "",
|
|
86
|
-
suffix: "::text"
|
|
87
|
-
},
|
|
88
|
-
jsonObject,
|
|
89
|
-
jsonRows: (nested, many, jsonOutput) => {
|
|
90
|
-
return many ? `(SELECT COALESCE(${jsonOutput ? "json_agg" : "jsonb_agg"}("__symmetria_row"), '[]'::${jsonOutput ? "json" : "jsonb"}) FROM (${nested}) AS "__symmetria_row")` : `(SELECT ${jsonOutput ? "row_to_json" : "to_jsonb"}("__symmetria_row") FROM (${nested}) AS "__symmetria_row")`;
|
|
91
|
-
},
|
|
92
|
-
jsonPath: (value, path, options, context) => `(${value} ${options.scalarType ? "#>>" : "#>"} ARRAY[${path.map((part) => `${context.parameter(String(part))}::text`).join(", ")}])${options.scalarType ? `::${options.scalarType}` : ""}`,
|
|
93
|
-
arrayIndex: (value, position, context) => {
|
|
94
|
-
const parameter = context.parameter(position);
|
|
95
|
-
return `(${value})[(CASE WHEN ${parameter}::bigint < cardinality(${value}) THEN array_lower(${value}, 1)::bigint + ${parameter}::bigint END)::integer]`;
|
|
96
|
-
},
|
|
97
|
-
arrayLength: (value, json) => json ? `jsonb_array_length(${jsonArray(value)})` : `cardinality(${value})`,
|
|
98
|
-
jsonHas: (value, element, options, context) => {
|
|
99
|
-
const array = jsonArray(value);
|
|
100
|
-
const elementAlias = context.nestedAlias("__symmetria_element");
|
|
101
|
-
const other = context.nestedAlias("__symmetria_element_other");
|
|
102
|
-
if (options.overlap) {
|
|
103
|
-
const operand = options.elementArray ? `to_jsonb(${options.operand})` : element;
|
|
104
|
-
return `EXISTS (SELECT 1 FROM jsonb_array_elements(${array}) AS ${elementAlias}("value") CROSS JOIN jsonb_array_elements(${jsonArray(operand)}) AS ${other}("value") WHERE ${elementAlias}."value" = ${other}."value")`;
|
|
105
|
-
}
|
|
106
|
-
return `EXISTS (SELECT 1 FROM jsonb_array_elements(${array}) AS ${elementAlias}("value") WHERE ${elementAlias}."value" = COALESCE(${options.encoded ? element : `to_jsonb(${element})`}, 'null'::jsonb))`;
|
|
107
|
-
},
|
|
108
|
-
arrayHas: (value, element) => `${element} = ANY(${value})`,
|
|
109
|
-
search: (vector, query) => `${vector} @@ ${query}`,
|
|
110
|
-
recursiveUnion: (anchor, recursive, options) => `(${anchor})\nUNION${options.unionAll ? " ALL" : ""}\n(${recursive})`,
|
|
111
|
-
explain: (sql, analyze) => ({
|
|
112
|
-
sql: `EXPLAIN (FORMAT JSON${analyze ? ", ANALYZE, BUFFERS" : ""}) ${sql}`,
|
|
113
|
-
analyzed: analyze,
|
|
114
|
-
plan: (rows) => {
|
|
115
|
-
const value = rows[0]?.["QUERY PLAN"];
|
|
116
|
-
const explanation = typeof value === "string" ? JSON.parse(value) : value;
|
|
117
|
-
if (!Array.isArray(explanation) || !explanation.length || explanation.some((entry) => !entry || typeof entry !== "object" || Array.isArray(entry))) throw new Error("symmetria: EXPLAIN did not return a PostgreSQL JSON plan");
|
|
118
|
-
return explanation;
|
|
119
|
-
}
|
|
120
|
-
}),
|
|
121
|
-
nullsDefault: (direction) => direction === "ASC" ? "LAST" : "FIRST"
|
|
122
|
-
};
|
|
123
|
-
freeze(postgresRenderer.textCast);
|
|
124
|
-
freeze(postgresRenderer);
|
|
125
|
-
//#endregion
|
|
126
|
-
//#region src/observability/profiling.ts
|
|
127
|
-
/**
|
|
128
|
-
* Query profiler: records per-request query timings through AsyncLocalStorage and serves them over HTTP with a token.
|
|
129
|
-
*/
|
|
130
|
-
const executorProfiles = /* @__PURE__ */ new WeakMap();
|
|
131
|
-
const executorProfiling = (executor) => executor ? executorProfiles.get(executor) : void 0;
|
|
132
|
-
const serialize = (value) => JSON.stringify(value, (_name, entry) => typeof entry === "bigint" ? entry.toString() : entry);
|
|
133
|
-
const constantTimeEqual = (candidate, expected) => {
|
|
134
|
-
if (candidate === null) return false;
|
|
135
|
-
const left = Buffer.from(candidate);
|
|
136
|
-
const right = Buffer.from(expected);
|
|
137
|
-
return left.length === right.length && timingSafeEqual(left, right);
|
|
138
|
-
};
|
|
139
|
-
/** Opt-in profiling; async contexts isolate simultaneous named traces and HTTP requests. */
|
|
140
|
-
const createProfiler = (options = {}) => {
|
|
141
|
-
const capacity = options.capacity ?? 200;
|
|
142
|
-
const queryCapacity = options.queryCapacity ?? 1e3;
|
|
143
|
-
if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Error("symmetria: profiler capacity must be a positive integer");
|
|
144
|
-
if (!Number.isSafeInteger(queryCapacity) || queryCapacity < 1) throw new Error("symmetria: profiler queryCapacity must be a positive integer");
|
|
145
|
-
const context = new AsyncLocalStorage();
|
|
146
|
-
const requests = [];
|
|
147
|
-
const queryRecords = /* @__PURE__ */ new WeakMap();
|
|
148
|
-
const queryExecutors = /* @__PURE__ */ new Map();
|
|
149
|
-
const wrappedBuilders = /* @__PURE__ */ new WeakSet();
|
|
150
|
-
const excluded = /* @__PURE__ */ new Set([
|
|
151
|
-
"execute",
|
|
152
|
-
"then",
|
|
153
|
-
"catch",
|
|
154
|
-
"finally",
|
|
155
|
-
"toSQL",
|
|
156
|
-
"one",
|
|
157
|
-
"maybeOne",
|
|
158
|
-
"first",
|
|
159
|
-
"aggregate",
|
|
160
|
-
"get",
|
|
161
|
-
"find",
|
|
162
|
-
"page",
|
|
163
|
-
"pages",
|
|
164
|
-
"stream",
|
|
165
|
-
"inspect",
|
|
166
|
-
"$transaction",
|
|
167
|
-
"$close",
|
|
168
|
-
"$snapshot"
|
|
169
|
-
]);
|
|
170
|
-
let nextRequestId = 1;
|
|
171
|
-
let nextQueryId = 1;
|
|
172
|
-
let building = 0;
|
|
173
|
-
const remember = (request) => {
|
|
174
|
-
requests.push(request);
|
|
175
|
-
while (requests.length > capacity) {
|
|
176
|
-
const removed = requests.shift();
|
|
177
|
-
for (const query of removed.queries) queryExecutors.delete(query.id);
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
const trace = async (label, operation) => {
|
|
181
|
-
const request = {
|
|
182
|
-
id: nextRequestId++,
|
|
183
|
-
label,
|
|
184
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
185
|
-
durationMs: 0,
|
|
186
|
-
buildMs: 0,
|
|
187
|
-
queries: []
|
|
188
|
-
};
|
|
189
|
-
const started = performance.now();
|
|
190
|
-
try {
|
|
191
|
-
return await context.run(request, operation);
|
|
192
|
-
} catch (error) {
|
|
193
|
-
request.error = error instanceof Error ? error.message : String(error);
|
|
194
|
-
throw error;
|
|
195
|
-
} finally {
|
|
196
|
-
request.durationMs = performance.now() - started;
|
|
197
|
-
remember(request);
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
const trackBuilder = (builder) => {
|
|
201
|
-
if (wrappedBuilders.has(builder)) return builder;
|
|
202
|
-
const methods = /* @__PURE__ */ new Map();
|
|
203
|
-
const measure = (operation) => {
|
|
204
|
-
const request = context.getStore();
|
|
205
|
-
const outermost = building++ === 0;
|
|
206
|
-
const started = request && outermost ? performance.now() : 0;
|
|
207
|
-
try {
|
|
208
|
-
return operation();
|
|
209
|
-
} finally {
|
|
210
|
-
building--;
|
|
211
|
-
if (request && outermost) request.buildMs += performance.now() - started;
|
|
212
|
-
}
|
|
213
|
-
};
|
|
214
|
-
const proxy = new Proxy(typeof builder === "function" ? (..._argumentsList) => void 0 : {}, {
|
|
215
|
-
apply: (_target, receiver, argumentsList) => measure(() => Reflect.apply(builder, receiver, argumentsList)),
|
|
216
|
-
get: (_target, key) => {
|
|
217
|
-
const value = Reflect.get(builder, key);
|
|
218
|
-
if (typeof value !== "function" || typeof key !== "string" || excluded.has(key)) {
|
|
219
|
-
if (key === "by" && value && typeof value === "object") {
|
|
220
|
-
if (!methods.has(key)) methods.set(key, trackBuilder(value));
|
|
221
|
-
return methods.get(key);
|
|
222
|
-
}
|
|
223
|
-
return value;
|
|
224
|
-
}
|
|
225
|
-
if (!methods.has(key)) methods.set(key, (...argumentsList) => {
|
|
226
|
-
return measure(() => Reflect.apply(value, builder, argumentsList));
|
|
227
|
-
});
|
|
228
|
-
return methods.get(key);
|
|
229
|
-
},
|
|
230
|
-
has: (_target, key) => key in builder,
|
|
231
|
-
getPrototypeOf: () => Object.getPrototypeOf(builder),
|
|
232
|
-
ownKeys: () => Reflect.ownKeys(builder),
|
|
233
|
-
getOwnPropertyDescriptor: (_target, key) => {
|
|
234
|
-
const descriptor = Object.getOwnPropertyDescriptor(builder, key);
|
|
235
|
-
return descriptor ? {
|
|
236
|
-
...descriptor,
|
|
237
|
-
configurable: true
|
|
238
|
-
} : void 0;
|
|
239
|
-
},
|
|
240
|
-
set: () => false,
|
|
241
|
-
defineProperty: () => false,
|
|
242
|
-
deleteProperty: () => false
|
|
243
|
-
});
|
|
244
|
-
wrappedBuilders.add(proxy);
|
|
245
|
-
return proxy;
|
|
246
|
-
};
|
|
247
|
-
const wrapExecutor = (executor, explainExecutor = executor) => {
|
|
248
|
-
const execute = async (query) => {
|
|
249
|
-
const request = context.getStore();
|
|
250
|
-
if (!request) return trace("background query", () => execute(query));
|
|
251
|
-
const started = performance.now();
|
|
252
|
-
const record = {
|
|
253
|
-
id: nextQueryId++,
|
|
254
|
-
sql: query.sql,
|
|
255
|
-
parameters: [],
|
|
256
|
-
kind: "raw",
|
|
257
|
-
compileMs: 0,
|
|
258
|
-
databaseMs: 0,
|
|
259
|
-
decodeMs: 0,
|
|
260
|
-
rows: 0
|
|
261
|
-
};
|
|
262
|
-
try {
|
|
263
|
-
const result = await executor(query);
|
|
264
|
-
record.rows = normalizeResult(result).affectedRows;
|
|
265
|
-
return result;
|
|
266
|
-
} catch (error) {
|
|
267
|
-
record.error = error instanceof Error ? error.message : String(error);
|
|
268
|
-
throw error;
|
|
269
|
-
} finally {
|
|
270
|
-
record.databaseMs = performance.now() - started;
|
|
271
|
-
record.parameters = query.parameters.map(cloneParameter);
|
|
272
|
-
request.queries.push(record);
|
|
273
|
-
queryRecords.set(query, record);
|
|
274
|
-
queryExecutors.set(record.id, {
|
|
275
|
-
query: {
|
|
276
|
-
sql: query.sql,
|
|
277
|
-
parameters: record.parameters
|
|
278
|
-
},
|
|
279
|
-
executor: explainExecutor,
|
|
280
|
-
record
|
|
281
|
-
});
|
|
282
|
-
while (request.queries.length > queryCapacity) {
|
|
283
|
-
const dropped = request.queries.shift();
|
|
284
|
-
queryExecutors.delete(dropped.id);
|
|
285
|
-
request.droppedQueries = (request.droppedQueries ?? 0) + 1;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
|
-
executorProfiles.set(execute, {
|
|
290
|
-
trackBuilder,
|
|
291
|
-
annotate: (query, details) => {
|
|
292
|
-
const record = queryRecords.get(query);
|
|
293
|
-
if (record) Object.assign(record, details);
|
|
294
|
-
}
|
|
295
|
-
});
|
|
296
|
-
return execute;
|
|
297
|
-
};
|
|
298
|
-
const transactionDriver = (driver, explainExecutor) => Object.freeze({
|
|
299
|
-
execute: wrapExecutor(driver.execute, explainExecutor),
|
|
300
|
-
transaction: (callback) => driver.transaction((nested) => callback(transactionDriver(nested, explainExecutor)))
|
|
301
|
-
});
|
|
302
|
-
const wrapDriver = (driver) => Object.freeze({
|
|
303
|
-
execute: wrapExecutor(driver.execute, driver.execute),
|
|
304
|
-
close: driver.close,
|
|
305
|
-
...driver.session ? { session: driver.session } : {},
|
|
306
|
-
...driver.transaction ? { transaction: (callback, settings) => driver.transaction((scoped) => callback(transactionDriver(scoped, driver.execute)), settings) } : {}
|
|
307
|
-
});
|
|
308
|
-
const snapshot = () => structuredClone(requests);
|
|
309
|
-
const explain = async (identifier, analyze = false) => {
|
|
310
|
-
const entry = queryExecutors.get(identifier);
|
|
311
|
-
if (!entry || entry.record.kind !== "select") throw new Error("symmetria: EXPLAIN requires a retained SELECT query");
|
|
312
|
-
const statement = postgresRenderer.explain(entry.query.sql, analyze);
|
|
313
|
-
const result = normalizeResult(await entry.executor({
|
|
314
|
-
sql: statement.sql,
|
|
315
|
-
parameters: entry.query.parameters.map(cloneParameter)
|
|
316
|
-
}));
|
|
317
|
-
return statement.plan(result.rows);
|
|
318
|
-
};
|
|
319
|
-
const fetchHandler = (handler) => (request) => trace(`${request.method} ${new URL(request.url).pathname}`, () => handler(request));
|
|
320
|
-
const serve = async (settings = {}) => {
|
|
321
|
-
const hostname = settings.hostname ?? "127.0.0.1";
|
|
322
|
-
if (hostname !== "127.0.0.1" && hostname !== "::1") throw new Error("symmetria: profiler HTTP server requires a loopback address");
|
|
323
|
-
const token = settings.token ?? process.env.SYMMETRIA_PROFILE_TOKEN ?? randomUUID();
|
|
324
|
-
if (typeof token !== "string" || token.length < 16 || !/^[\x21-\x7e]+$/.test(token)) throw new Error("symmetria: profiler token must be at least 16 printable ASCII characters");
|
|
325
|
-
const headers = {
|
|
326
|
-
"content-type": "application/json",
|
|
327
|
-
"cache-control": "no-store",
|
|
328
|
-
"x-content-type-options": "nosniff"
|
|
329
|
-
};
|
|
330
|
-
const server = await serveProfiler({
|
|
331
|
-
hostname,
|
|
332
|
-
port: settings.port ?? 7331,
|
|
333
|
-
fetch: async (request, server) => {
|
|
334
|
-
const url = new URL(request.url);
|
|
335
|
-
const hosts = [hostname === "::1" ? "[::1]" : hostname, "localhost"].flatMap((name) => server.port === 80 ? [name, `${name}:80`] : [`${name}:${server.port}`]);
|
|
336
|
-
const origin = request.headers.get("origin");
|
|
337
|
-
const site = request.headers.get("sec-fetch-site");
|
|
338
|
-
if (url.protocol !== "http:" || !hosts.includes(url.host) || !hosts.includes(request.headers.get("host")?.toLowerCase() ?? "") || origin !== null && origin !== url.origin || site !== null && site !== "same-origin" && site !== "none" || !constantTimeEqual(request.headers.get("x-symmetria-token"), token)) return Response.json({ error: "Forbidden" }, {
|
|
339
|
-
status: 403,
|
|
340
|
-
headers
|
|
341
|
-
});
|
|
342
|
-
if (request.method === "GET" && url.pathname === "/requests") return new Response(serialize(snapshot()), { headers });
|
|
343
|
-
if (request.method === "POST" && url.pathname === "/explain") try {
|
|
344
|
-
const result = await explain(Number(url.searchParams.get("id")), url.searchParams.get("analyze") === "true");
|
|
345
|
-
return new Response(serialize(result), { headers });
|
|
346
|
-
} catch (error) {
|
|
347
|
-
return Response.json({ error: error instanceof Error ? error.message : String(error) }, {
|
|
348
|
-
status: 400,
|
|
349
|
-
headers
|
|
350
|
-
});
|
|
351
|
-
}
|
|
352
|
-
return Response.json({ error: "Not found" }, {
|
|
353
|
-
status: 404,
|
|
354
|
-
headers
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
});
|
|
358
|
-
return Object.freeze({
|
|
359
|
-
...server,
|
|
360
|
-
token
|
|
361
|
-
});
|
|
362
|
-
};
|
|
363
|
-
return Object.freeze({
|
|
364
|
-
trace,
|
|
365
|
-
fetch: fetchHandler,
|
|
366
|
-
driver: wrapDriver,
|
|
367
|
-
snapshot,
|
|
368
|
-
explain,
|
|
369
|
-
serve
|
|
370
|
-
});
|
|
371
|
-
};
|
|
372
|
-
//#endregion
|
|
373
9
|
//#region src/query/plan/batching.ts
|
|
374
10
|
const batchCollectors = /* @__PURE__ */ new WeakMap();
|
|
375
11
|
//#endregion
|
|
@@ -447,7 +83,7 @@ const valueSql = (compilation, node, bindings, jsonOutput = false) => {
|
|
|
447
83
|
const existing = cache?.find((entry) => sameExpression(entry.node, node) && (entry.jsonOutput === jsonOutput || !compilation.shapeOnly && !containsNode(node, buildsJson)));
|
|
448
84
|
if (existing) return existing.sql;
|
|
449
85
|
const sql = renderValue(compilation, node, bindings, jsonOutput);
|
|
450
|
-
if (!BARE_PARAMETER.test(sql)) cache
|
|
86
|
+
if (cache && !BARE_PARAMETER.test(sql)) cache.push({
|
|
451
87
|
node,
|
|
452
88
|
sql,
|
|
453
89
|
jsonOutput
|
|
@@ -1091,6 +727,18 @@ const ordersThroughIvfflat = (query) => {
|
|
|
1091
727
|
const column = node?.kind === "binary" && node.left.kind === "column" ? node.left.description : void 0;
|
|
1092
728
|
return !!column && !query.locking && !query.distinct && !query.grouping.length && (column.binding.table.indexes ?? []).some((definition) => definition.method === "ivfflat" && definition.keys[0]?.startsWith(quoteIdentifier(column.column.sqlName)));
|
|
1093
729
|
};
|
|
730
|
+
const carriedLists = /* @__PURE__ */ new WeakMap();
|
|
731
|
+
/** Every column of the root under its own name, for a page taken before its nested rows. */
|
|
732
|
+
const carriedColumns = (root, alias) => {
|
|
733
|
+
let lists = carriedLists.get(root.table);
|
|
734
|
+
if (!lists) carriedLists.set(root.table, lists = /* @__PURE__ */ new Map());
|
|
735
|
+
let list = lists.get(alias);
|
|
736
|
+
if (list === void 0) {
|
|
737
|
+
list = root.table.columns.map((column) => `${alias}.${quoteIdentifier(column.sqlName)} AS ${quoteIdentifier(column.sqlName)}`).join(", ");
|
|
738
|
+
if (lists.size < 64) lists.set(alias, list);
|
|
739
|
+
}
|
|
740
|
+
return list;
|
|
741
|
+
};
|
|
1094
742
|
const NO_SHARED_AGGREGATES = {
|
|
1095
743
|
inner: [],
|
|
1096
744
|
outer: []
|
|
@@ -1182,7 +830,7 @@ const renderSelect = (compilation, query, outerBindings, jsonValues, jsonOutput)
|
|
|
1182
830
|
return [
|
|
1183
831
|
projection,
|
|
1184
832
|
`FROM (${[
|
|
1185
|
-
`SELECT ${query.root
|
|
833
|
+
`SELECT ${carriedColumns(query.root, aliasSql(compilation, query.root))}`,
|
|
1186
834
|
source,
|
|
1187
835
|
...body,
|
|
1188
836
|
...fragments
|
|
@@ -1592,6 +1240,6 @@ const rowDecoder = (plan) => {
|
|
|
1592
1240
|
return decode;
|
|
1593
1241
|
};
|
|
1594
1242
|
//#endregion
|
|
1595
|
-
export { currentScopes as a, rowDecoder as c,
|
|
1243
|
+
export { currentScopes as a, rowDecoder as c, compileTemplate as i, queryOccurrence as l, compileQuery as n, executeCompiled as o, compileShape as r, executePlan as s, compilePlan as t, batchCollectors as u };
|
|
1596
1244
|
|
|
1597
|
-
//# sourceMappingURL=compile-
|
|
1245
|
+
//# sourceMappingURL=compile-DjpujkL0.js.map
|