@lunora/bindings 0.0.0 → 1.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +105 -0
- package/README.md +39 -1
- package/__assets__/package-og.svg +14 -0
- package/dist/analytics/index.d.mts +148 -0
- package/dist/analytics/index.d.ts +148 -0
- package/dist/analytics/index.mjs +2 -0
- package/dist/images/index.d.mts +338 -0
- package/dist/images/index.d.ts +338 -0
- package/dist/images/index.mjs +3 -0
- package/dist/kv/index.d.mts +177 -0
- package/dist/kv/index.d.ts +177 -0
- package/dist/kv/index.mjs +1 -0
- package/dist/packem_shared/AnalyticsSqlError-CGTdsi4H.mjs +42 -0
- package/dist/packem_shared/R2SqlError-DlDd_SrE.mjs +67 -0
- package/dist/packem_shared/SelectBuilder-DHaXZwn_.mjs +167 -0
- package/dist/packem_shared/SetOperation-RDHcxccj.mjs +80 -0
- package/dist/packem_shared/Sql-DceGtcUd.mjs +68 -0
- package/dist/packem_shared/WindowExpression-Cg9s2xcr.mjs +44 -0
- package/dist/packem_shared/WindowFunction-DA3pGC3N.mjs +82 -0
- package/dist/packem_shared/asc-Cur-xO8v.mjs +16 -0
- package/dist/packem_shared/buildImageDeliveryUrl-D1sVfIOP.mjs +30 -0
- package/dist/packem_shared/buildSignedImageUrl-Otdgc_jO.mjs +113 -0
- package/dist/packem_shared/concurrent-Dj5sOibv.mjs +23 -0
- package/dist/packem_shared/createAnalytics-CEEI69o9.mjs +57 -0
- package/dist/packem_shared/createContextVectors-BSizpmu5.mjs +140 -0
- package/dist/packem_shared/createImages-CJrvqX0u.mjs +80 -0
- package/dist/packem_shared/createKv-DTiSt216.mjs +141 -0
- package/dist/packem_shared/createPipelines-CfyJ6VGu.mjs +10 -0
- package/dist/packem_shared/createVectorAdminIntrospector-BJUOM6VW.mjs +51 -0
- package/dist/packem_shared/createVectors-LSpGoKCd.mjs +91 -0
- package/dist/pipelines/index.d.mts +41 -0
- package/dist/pipelines/index.d.ts +41 -0
- package/dist/pipelines/index.mjs +1 -0
- package/dist/r2sql/index.d.mts +383 -0
- package/dist/r2sql/index.d.ts +383 -0
- package/dist/r2sql/index.mjs +7 -0
- package/dist/vectors/index.d.mts +285 -0
- package/dist/vectors/index.d.ts +285 -0
- package/dist/vectors/index.mjs +3 -0
- package/package.json +54 -4
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The value types Workers KV can store / return. Mirrors Cloudflare's
|
|
3
|
+
* `KVNamespace` `get`/`put` body unions; declared here so the package stays
|
|
4
|
+
* runtime-agnostic and the `*Like` interfaces don't pull in
|
|
5
|
+
* `@cloudflare/workers-types` at runtime.
|
|
6
|
+
*/
|
|
7
|
+
type KvValue = ReadableStream | ArrayBuffer | ArrayBufferView | string;
|
|
8
|
+
/** How a raw KV read should decode the stored value. Mirrors KV's `type` option. */
|
|
9
|
+
type KvValueType = "text" | "json" | "arrayBuffer" | "stream";
|
|
10
|
+
/**
|
|
11
|
+
* Per-read options forwarded to the binding. `cacheTtl` is KV's edge-cache TTL
|
|
12
|
+
* (seconds, min 60); `type` selects the decode mode for {@link Kv.getRaw}.
|
|
13
|
+
*/
|
|
14
|
+
interface KvGetOptions {
|
|
15
|
+
/** KV edge-cache TTL in seconds (minimum 60). Forwarded verbatim. */
|
|
16
|
+
cacheTtl?: number;
|
|
17
|
+
/** Decode mode for a raw read. {@link Kv.get} always uses `"json"`. */
|
|
18
|
+
type?: KvValueType;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Minimal projection of Cloudflare's `KVNamespace`. Declared structurally so
|
|
22
|
+
* unit tests can pass a plain `Map`-backed double; the real binding satisfies
|
|
23
|
+
* the same shape. Mirrors `R2BucketLike` in `@lunora/storage`.
|
|
24
|
+
*/
|
|
25
|
+
interface KVNamespaceLike {
|
|
26
|
+
/** Delete a key. No-op if the key is absent. */
|
|
27
|
+
delete: (key: string) => Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Read a value. The real binding overloads on `options.type`; declared here
|
|
30
|
+
* as the broad union so a structural double need only return the value (or
|
|
31
|
+
* `null` when absent).
|
|
32
|
+
*/
|
|
33
|
+
get: (key: string, options?: KvGetOptions | KvValueType) => Promise<unknown>;
|
|
34
|
+
/**
|
|
35
|
+
* Read a value together with its associated metadata. Returns
|
|
36
|
+
* `{ value: null, metadata: null }` when the key is absent.
|
|
37
|
+
*/
|
|
38
|
+
getWithMetadata: (key: string, options?: KvGetOptions | KvValueType) => Promise<{
|
|
39
|
+
metadata: unknown;
|
|
40
|
+
value: unknown;
|
|
41
|
+
}>;
|
|
42
|
+
/** List keys, optionally filtered by `prefix` and paginated via `cursor`. */
|
|
43
|
+
list: (options?: {
|
|
44
|
+
cursor?: string;
|
|
45
|
+
limit?: number;
|
|
46
|
+
prefix?: string;
|
|
47
|
+
}) => Promise<KvNamespaceListResult>;
|
|
48
|
+
/** Write a value, optionally with TTL/expiration and metadata. */
|
|
49
|
+
put: (key: string, value: KvValue, options?: KvNamespacePutOptions) => Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/** The raw put options the KV binding accepts (mirrors `KVNamespacePutOptions`). */
|
|
52
|
+
interface KvNamespacePutOptions {
|
|
53
|
+
/** Absolute expiration as a Unix timestamp (seconds). Mutually exclusive with `expirationTtl`. */
|
|
54
|
+
expiration?: number;
|
|
55
|
+
/** Relative expiration in seconds from now (minimum 60). Mutually exclusive with `expiration`. */
|
|
56
|
+
expirationTtl?: number;
|
|
57
|
+
/** Arbitrary JSON metadata stored alongside the value, returned by `getWithMetadata`/`list`. */
|
|
58
|
+
metadata?: unknown;
|
|
59
|
+
}
|
|
60
|
+
/** One key entry as returned by the KV binding's `list`. */
|
|
61
|
+
interface KvListKey<Metadata = unknown> {
|
|
62
|
+
/** Absolute expiration (Unix seconds), when the key has one. */
|
|
63
|
+
expiration?: number;
|
|
64
|
+
/** The key's metadata, when set at write time. */
|
|
65
|
+
metadata?: Metadata;
|
|
66
|
+
/** The key name. */
|
|
67
|
+
name: string;
|
|
68
|
+
}
|
|
69
|
+
/** The raw `list` result shape returned by the KV binding. */
|
|
70
|
+
type KvNamespaceListResult<Metadata = unknown> = {
|
|
71
|
+
cacheStatus?: string | null;
|
|
72
|
+
cursor: string;
|
|
73
|
+
keys: KvListKey<Metadata>[];
|
|
74
|
+
list_complete: false;
|
|
75
|
+
} | {
|
|
76
|
+
cacheStatus?: string | null;
|
|
77
|
+
keys: KvListKey<Metadata>[];
|
|
78
|
+
list_complete: true;
|
|
79
|
+
};
|
|
80
|
+
/** Construction options for the `createKv` factory. */
|
|
81
|
+
interface LunoraKvOptions {
|
|
82
|
+
/**
|
|
83
|
+
* Optional per-instance key prefix applied to every operation (get/put/
|
|
84
|
+
* delete/list). Use for multi-tenant key namespacing — equivalent to
|
|
85
|
+
* calling the `scopeKey` helper on every key. Combined via `scopeKey`, so a
|
|
86
|
+
* `..` or NUL in the prefix is rejected.
|
|
87
|
+
*/
|
|
88
|
+
keyPrefix?: string;
|
|
89
|
+
/** The bound KV namespace (`env.<BINDING>`). */
|
|
90
|
+
namespace: KVNamespaceLike;
|
|
91
|
+
}
|
|
92
|
+
/** Options for {@link Kv.put}. JSON-stringifies the value unless `raw` is set. */
|
|
93
|
+
interface KvPutOptions {
|
|
94
|
+
/** Absolute expiration as a Unix timestamp (seconds). Mutually exclusive with `expirationTtl`. */
|
|
95
|
+
expiration?: number;
|
|
96
|
+
/** Relative expiration in seconds from now (minimum 60). Mutually exclusive with `expiration`. */
|
|
97
|
+
expirationTtl?: number;
|
|
98
|
+
/** Arbitrary metadata stored alongside the value (returned by `getWithMetadata`/`list`). */
|
|
99
|
+
metadata?: unknown;
|
|
100
|
+
/**
|
|
101
|
+
* When true, write `value` to KV verbatim (no `JSON.stringify`). `value`
|
|
102
|
+
* must already be a KV-writable type (string/ArrayBuffer/stream).
|
|
103
|
+
*/
|
|
104
|
+
raw?: boolean;
|
|
105
|
+
}
|
|
106
|
+
/** Options for {@link Kv.list}. */
|
|
107
|
+
interface KvListOptions {
|
|
108
|
+
/** Opaque cursor from a previous truncated page. */
|
|
109
|
+
cursor?: string;
|
|
110
|
+
/** Max keys per page (KV caps at 1000). */
|
|
111
|
+
limit?: number;
|
|
112
|
+
/** Restrict to keys starting with this prefix (combined with any `keyPrefix`). */
|
|
113
|
+
prefix?: string;
|
|
114
|
+
}
|
|
115
|
+
/** A single page of {@link Kv.list} results. */
|
|
116
|
+
interface KvListResult<Metadata = unknown> {
|
|
117
|
+
/** Cursor for the next page; `undefined` when the listing is complete. */
|
|
118
|
+
cursor?: string;
|
|
119
|
+
/**
|
|
120
|
+
* The key names, with any instance `keyPrefix` stripped back off so callers
|
|
121
|
+
* see the same keys they wrote.
|
|
122
|
+
*/
|
|
123
|
+
keys: KvListKey<Metadata>[];
|
|
124
|
+
/** True when this is the final page (no further `cursor`). */
|
|
125
|
+
listComplete: boolean;
|
|
126
|
+
}
|
|
127
|
+
/** A value together with its stored metadata (from {@link Kv.getWithMetadata}). */
|
|
128
|
+
interface KvValueWithMetadata<Value, Metadata> {
|
|
129
|
+
/** The stored metadata, or `null` when none was set / the key is absent. */
|
|
130
|
+
metadata: Metadata | null;
|
|
131
|
+
/** The decoded value, or `null` when the key is absent. */
|
|
132
|
+
value: Value | null;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The typed Workers KV client bound to `ctx.kv`. JSON-decodes/encodes by
|
|
136
|
+
* default; a raw escape hatch ({@link Kv.getRaw} / `put(..., { raw: true })`)
|
|
137
|
+
* handles text/binary/stream values.
|
|
138
|
+
*/
|
|
139
|
+
interface Kv {
|
|
140
|
+
/** Delete a key. No-op if absent. */
|
|
141
|
+
delete: (key: string) => Promise<void>;
|
|
142
|
+
/**
|
|
143
|
+
* Read a key and `JSON.parse` it into `T`. Returns `null` when the key is
|
|
144
|
+
* absent. Throws if the stored value isn't valid JSON — use
|
|
145
|
+
* {@link Kv.getRaw} for non-JSON values.
|
|
146
|
+
*/
|
|
147
|
+
get: <T = unknown>(key: string, options?: {
|
|
148
|
+
cacheTtl?: number;
|
|
149
|
+
}) => Promise<T | null>;
|
|
150
|
+
/** Read a raw value with an explicit decode `type` (default `"text"`). Returns `null` when absent. */
|
|
151
|
+
getRaw: <T = string>(key: string, options?: KvGetOptions) => Promise<T | null>;
|
|
152
|
+
/**
|
|
153
|
+
* Read a key's JSON value together with its metadata. Returns
|
|
154
|
+
* `{ value: null, metadata: null }` when the key is absent.
|
|
155
|
+
*/
|
|
156
|
+
getWithMetadata: <T = unknown, M = unknown>(key: string, options?: {
|
|
157
|
+
cacheTtl?: number;
|
|
158
|
+
}) => Promise<KvValueWithMetadata<T, M>>;
|
|
159
|
+
/** List keys (optionally `prefix`-filtered, paginated via `cursor`). */
|
|
160
|
+
list: <M = unknown>(options?: KvListOptions) => Promise<KvListResult<M>>;
|
|
161
|
+
/**
|
|
162
|
+
* Write `value` to `key`. JSON-stringifies `value` unless `options.raw` is
|
|
163
|
+
* set (in which case `value` must be a KV-writable type). Forwards
|
|
164
|
+
* `expirationTtl`/`expiration`/`metadata` to the binding.
|
|
165
|
+
*/
|
|
166
|
+
put: <T = unknown>(key: string, value: T, options?: KvPutOptions) => Promise<void>;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Compose a per-tenant key from a scope prefix and a caller-supplied key. Both
|
|
170
|
+
* halves are validated — the prefix may not contain `..` or NUL either, and the
|
|
171
|
+
* resulting key must stay under KV's length ceiling. Recommended for any
|
|
172
|
+
* multi-tenant deployment so client-supplied keys can't address peer data.
|
|
173
|
+
* Mirrors `scopeKey` from `@lunora/storage`.
|
|
174
|
+
*/
|
|
175
|
+
declare const scopeKey: (prefix: string, key: string) => string;
|
|
176
|
+
declare const createKv: (options: LunoraKvOptions) => Kv;
|
|
177
|
+
export { type KVNamespaceLike, type Kv, type KvGetOptions, type KvListKey, type KvListOptions, type KvListResult, type KvNamespaceListResult, type KvNamespacePutOptions, type KvPutOptions, type KvValue, type KvValueType, type KvValueWithMetadata, type LunoraKvOptions, createKv, scopeKey };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createKv, scopeKey } from '../packem_shared/createKv-DTiSt216.mjs';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const SQL_API_BASE = "https://api.cloudflare.com/client/v4/accounts";
|
|
2
|
+
class AnalyticsSqlError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
constructor(status, body) {
|
|
5
|
+
super(`Analytics Engine SQL API returned ${String(status)}: ${body}`);
|
|
6
|
+
this.name = "AnalyticsSqlError";
|
|
7
|
+
this.status = status;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const createAnalyticsSqlClient = (config) => {
|
|
11
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
12
|
+
const endpoint = `${SQL_API_BASE}/${encodeURIComponent(config.accountId)}/analytics_engine/sql`;
|
|
13
|
+
const query = async (sql) => {
|
|
14
|
+
const response = await fetchImpl(endpoint, {
|
|
15
|
+
body: sql,
|
|
16
|
+
headers: {
|
|
17
|
+
Authorization: `Bearer ${config.apiToken}`,
|
|
18
|
+
"Content-Type": "text/plain"
|
|
19
|
+
},
|
|
20
|
+
method: "POST"
|
|
21
|
+
});
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
throw new AnalyticsSqlError(response.status, await response.text());
|
|
24
|
+
}
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = await response.json();
|
|
28
|
+
} catch {
|
|
29
|
+
throw new AnalyticsSqlError(response.status, "Analytics Engine SQL API returned a non-JSON body.");
|
|
30
|
+
}
|
|
31
|
+
const body = raw;
|
|
32
|
+
const rows = body.data ?? [];
|
|
33
|
+
return {
|
|
34
|
+
columns: body.meta ?? [],
|
|
35
|
+
rowCount: body.rows ?? rows.length,
|
|
36
|
+
rows
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
return { query };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export { AnalyticsSqlError, createAnalyticsSqlClient };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import SelectBuilder from './SelectBuilder-DHaXZwn_.mjs';
|
|
2
|
+
import { ident, toText } from './Sql-DceGtcUd.mjs';
|
|
3
|
+
|
|
4
|
+
const API_BASE = "https://api.sql.cloudflarestorage.com/api/v1/accounts";
|
|
5
|
+
const inferColumns = (rows) => {
|
|
6
|
+
if (rows[0] === void 0) {
|
|
7
|
+
return [];
|
|
8
|
+
}
|
|
9
|
+
return Object.keys(rows[0]).map((name) => {
|
|
10
|
+
return { name };
|
|
11
|
+
});
|
|
12
|
+
};
|
|
13
|
+
class R2SqlError extends Error {
|
|
14
|
+
status;
|
|
15
|
+
constructor(status, body) {
|
|
16
|
+
super(`R2 SQL query failed (${String(status)}): ${body}`);
|
|
17
|
+
this.name = "R2SqlError";
|
|
18
|
+
this.status = status;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const createR2Sql = (config) => {
|
|
22
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
23
|
+
const base = config.endpoint ?? API_BASE;
|
|
24
|
+
const endpoint = `${base}/${encodeURIComponent(config.accountId)}/r2-sql/query/${encodeURIComponent(config.bucket)}`;
|
|
25
|
+
const warehouse = `${config.accountId}_${config.bucket}`;
|
|
26
|
+
const exec = async (statement) => {
|
|
27
|
+
const response = await fetchImpl(endpoint, {
|
|
28
|
+
body: JSON.stringify({ query: statement, warehouse }),
|
|
29
|
+
headers: {
|
|
30
|
+
Authorization: `Bearer ${config.apiToken}`,
|
|
31
|
+
"Content-Type": "application/json"
|
|
32
|
+
},
|
|
33
|
+
method: "POST"
|
|
34
|
+
});
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
throw new R2SqlError(response.status, await response.text());
|
|
37
|
+
}
|
|
38
|
+
let raw;
|
|
39
|
+
try {
|
|
40
|
+
raw = await response.json();
|
|
41
|
+
} catch {
|
|
42
|
+
throw new R2SqlError(response.status, "R2 SQL returned a non-JSON body.");
|
|
43
|
+
}
|
|
44
|
+
const body = raw;
|
|
45
|
+
if (body.success === false || body.errors !== void 0 && body.errors.length > 0) {
|
|
46
|
+
throw new R2SqlError(response.status, JSON.stringify(body.errors ?? body));
|
|
47
|
+
}
|
|
48
|
+
const rows = body.result?.rows ?? [];
|
|
49
|
+
return {
|
|
50
|
+
columns: body.result?.schema ?? inferColumns(rows),
|
|
51
|
+
rowCount: rows.length,
|
|
52
|
+
rows
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
describe: async (table) => exec(`DESCRIBE ${ident(table)}`),
|
|
57
|
+
explain: async (statement, options) => exec(`EXPLAIN ${options?.format === "json" ? "FORMAT JSON " : ""}${toText(statement)}`),
|
|
58
|
+
// `SelectBuilder`'s constructor validates the table reference (allowing an
|
|
59
|
+
// optional `[AS] alias`), so no pre-validation here.
|
|
60
|
+
from: (table) => new SelectBuilder(exec, table),
|
|
61
|
+
query: async (statement) => exec(toText(statement)),
|
|
62
|
+
showDatabases: async () => exec("SHOW DATABASES"),
|
|
63
|
+
showTables: async (namespace) => exec(`SHOW TABLES IN ${ident(namespace)}`)
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export { R2SqlError, createR2Sql };
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { renderOrderTerm } from './asc-Cur-xO8v.mjs';
|
|
2
|
+
import SetOperation from './SetOperation-RDHcxccj.mjs';
|
|
3
|
+
import { tableRef, toText, lit } from './Sql-DceGtcUd.mjs';
|
|
4
|
+
|
|
5
|
+
const JOIN_KEYWORDS = {
|
|
6
|
+
cross: "CROSS JOIN",
|
|
7
|
+
full: "FULL OUTER JOIN",
|
|
8
|
+
inner: "INNER JOIN",
|
|
9
|
+
left: "LEFT JOIN",
|
|
10
|
+
right: "RIGHT JOIN"
|
|
11
|
+
};
|
|
12
|
+
class SelectBuilder {
|
|
13
|
+
exec;
|
|
14
|
+
table;
|
|
15
|
+
selectItems = [];
|
|
16
|
+
distinctFlag = false;
|
|
17
|
+
distinctOnItems = [];
|
|
18
|
+
joins = [];
|
|
19
|
+
whereConditions = [];
|
|
20
|
+
groupByItems = [];
|
|
21
|
+
havingConditions = [];
|
|
22
|
+
qualifyCondition;
|
|
23
|
+
orderByItems = [];
|
|
24
|
+
limitValue;
|
|
25
|
+
constructor(exec, table) {
|
|
26
|
+
this.exec = exec;
|
|
27
|
+
this.table = tableRef(table);
|
|
28
|
+
}
|
|
29
|
+
/** The `SELECT` list. Omit/empty for `SELECT *`. Items are columns, expressions, or aliased window fragments (`fn.rowNumber().over(...).as("rk")`). */
|
|
30
|
+
select(...items) {
|
|
31
|
+
this.selectItems.push(...items.map((item) => toText(item)));
|
|
32
|
+
return this;
|
|
33
|
+
}
|
|
34
|
+
/** `SELECT DISTINCT` — unique rows. */
|
|
35
|
+
distinct() {
|
|
36
|
+
this.distinctFlag = true;
|
|
37
|
+
return this;
|
|
38
|
+
}
|
|
39
|
+
/** `DISTINCT ON (cols)` — the first row per distinct combination, ordered by {@link orderBy}. */
|
|
40
|
+
distinctOn(...columns) {
|
|
41
|
+
this.distinctOnItems.push(...columns.map((column) => toText(column)));
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
/** `INNER JOIN table ON condition`. */
|
|
45
|
+
innerJoin(table, on) {
|
|
46
|
+
return this.addJoin("inner", table, on);
|
|
47
|
+
}
|
|
48
|
+
/** `LEFT JOIN table ON condition`. */
|
|
49
|
+
leftJoin(table, on) {
|
|
50
|
+
return this.addJoin("left", table, on);
|
|
51
|
+
}
|
|
52
|
+
/** `RIGHT JOIN table ON condition`. */
|
|
53
|
+
rightJoin(table, on) {
|
|
54
|
+
return this.addJoin("right", table, on);
|
|
55
|
+
}
|
|
56
|
+
/** `FULL OUTER JOIN table ON condition`. */
|
|
57
|
+
fullJoin(table, on) {
|
|
58
|
+
return this.addJoin("full", table, on);
|
|
59
|
+
}
|
|
60
|
+
/** `CROSS JOIN table` (no `ON`). */
|
|
61
|
+
crossJoin(table) {
|
|
62
|
+
return this.addJoin("cross", table);
|
|
63
|
+
}
|
|
64
|
+
/** Add `WHERE` condition(s). Multiple calls (and multiple args) are `AND`-ed. Bind values with the `sql` tag. */
|
|
65
|
+
where(...conditions) {
|
|
66
|
+
this.whereConditions.push(...conditions.map((condition) => toText(condition)));
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
/** `GROUP BY` column(s)/expression(s). */
|
|
70
|
+
groupBy(...columns) {
|
|
71
|
+
this.groupByItems.push(...columns.map((column) => toText(column)));
|
|
72
|
+
return this;
|
|
73
|
+
}
|
|
74
|
+
/** Add `HAVING` condition(s) over aggregates; multiple are `AND`-ed. */
|
|
75
|
+
having(...conditions) {
|
|
76
|
+
this.havingConditions.push(...conditions.map((condition) => toText(condition)));
|
|
77
|
+
return this;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* `QUALIFY` — filter on a window function without a subquery, e.g.
|
|
81
|
+
* `.qualify(fn.rowNumber().over({ partitionBy: "region", orderBy: desc("total") }).lte(3))`.
|
|
82
|
+
*/
|
|
83
|
+
qualify(condition) {
|
|
84
|
+
this.qualifyCondition = toText(condition);
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
/** `ORDER BY` term(s) — bare strings (ASC) or {@link import("./order").asc | asc}/{@link import("./order").desc | desc} tags. */
|
|
88
|
+
orderBy(...terms) {
|
|
89
|
+
this.orderByItems.push(...terms.map((term) => renderOrderTerm(term)));
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
/** `LIMIT n` (R2 SQL: 1–10,000, default 500). */
|
|
93
|
+
limit(n) {
|
|
94
|
+
this.limitValue = n;
|
|
95
|
+
return this;
|
|
96
|
+
}
|
|
97
|
+
/** Re-type the result rows without changing the query (the builder carries no schema of its own). */
|
|
98
|
+
returns() {
|
|
99
|
+
return this;
|
|
100
|
+
}
|
|
101
|
+
/** `this UNION other` — all rows from both, duplicates removed. */
|
|
102
|
+
union(other) {
|
|
103
|
+
return this.setOperation("UNION", other);
|
|
104
|
+
}
|
|
105
|
+
/** `this UNION ALL other` — all rows from both, duplicates kept. */
|
|
106
|
+
unionAll(other) {
|
|
107
|
+
return this.setOperation("UNION ALL", other);
|
|
108
|
+
}
|
|
109
|
+
/** `this INTERSECT other` — rows present in both. */
|
|
110
|
+
intersect(other) {
|
|
111
|
+
return this.setOperation("INTERSECT", other);
|
|
112
|
+
}
|
|
113
|
+
/** `this EXCEPT other` — rows in `this` but not `other`. */
|
|
114
|
+
except(other) {
|
|
115
|
+
return this.setOperation("EXCEPT", other);
|
|
116
|
+
}
|
|
117
|
+
/** True when this query carries its own `ORDER BY`/`LIMIT` — so a set operation must parenthesise it. */
|
|
118
|
+
get needsWrapForSetOperation() {
|
|
119
|
+
return this.orderByItems.length > 0 || this.limitValue !== void 0;
|
|
120
|
+
}
|
|
121
|
+
/** Render the `SELECT` statement (no trailing semicolon). */
|
|
122
|
+
toSQL() {
|
|
123
|
+
const parts = [`${this.renderHead()} ${this.selectItems.length > 0 ? this.selectItems.join(", ") : "*"}`, `FROM ${this.table}`];
|
|
124
|
+
for (const join of this.joins) {
|
|
125
|
+
parts.push(join.on === void 0 ? `${JOIN_KEYWORDS[join.kind]} ${join.table}` : `${JOIN_KEYWORDS[join.kind]} ${join.table} ON ${toText(join.on)}`);
|
|
126
|
+
}
|
|
127
|
+
if (this.whereConditions.length > 0) {
|
|
128
|
+
parts.push(`WHERE ${this.whereConditions.join(" AND ")}`);
|
|
129
|
+
}
|
|
130
|
+
if (this.groupByItems.length > 0) {
|
|
131
|
+
parts.push(`GROUP BY ${this.groupByItems.join(", ")}`);
|
|
132
|
+
}
|
|
133
|
+
if (this.havingConditions.length > 0) {
|
|
134
|
+
parts.push(`HAVING ${this.havingConditions.join(" AND ")}`);
|
|
135
|
+
}
|
|
136
|
+
if (this.qualifyCondition !== void 0) {
|
|
137
|
+
parts.push(`QUALIFY ${this.qualifyCondition}`);
|
|
138
|
+
}
|
|
139
|
+
if (this.orderByItems.length > 0) {
|
|
140
|
+
parts.push(`ORDER BY ${this.orderByItems.join(", ")}`);
|
|
141
|
+
}
|
|
142
|
+
if (this.limitValue !== void 0) {
|
|
143
|
+
parts.push(`LIMIT ${lit(this.limitValue)}`);
|
|
144
|
+
}
|
|
145
|
+
return parts.join(" ");
|
|
146
|
+
}
|
|
147
|
+
/** Execute the query and return the typed result. */
|
|
148
|
+
async run() {
|
|
149
|
+
return this.exec(this.toSQL());
|
|
150
|
+
}
|
|
151
|
+
/** The `SELECT [DISTINCT [ON (...)]]` head. */
|
|
152
|
+
renderHead() {
|
|
153
|
+
if (this.distinctOnItems.length > 0) {
|
|
154
|
+
return `SELECT DISTINCT ON (${this.distinctOnItems.join(", ")})`;
|
|
155
|
+
}
|
|
156
|
+
return this.distinctFlag ? "SELECT DISTINCT" : "SELECT";
|
|
157
|
+
}
|
|
158
|
+
addJoin(kind, table, on) {
|
|
159
|
+
this.joins.push({ kind, on, table: tableRef(table) });
|
|
160
|
+
return this;
|
|
161
|
+
}
|
|
162
|
+
setOperation(operator, other) {
|
|
163
|
+
return new SetOperation(this.exec, [{ query: this }, { operator, query: other }]);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export { SelectBuilder as default };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { renderOrderTerm } from './asc-Cur-xO8v.mjs';
|
|
2
|
+
import { lit } from './Sql-DceGtcUd.mjs';
|
|
3
|
+
|
|
4
|
+
const renderMember = (query) => {
|
|
5
|
+
const text = query.toSQL();
|
|
6
|
+
return query.needsWrapForSetOperation === true ? `(${text})` : text;
|
|
7
|
+
};
|
|
8
|
+
class SetOperation {
|
|
9
|
+
/**
|
|
10
|
+
* Always `true`: a nested set operation must be parenthesised when it is a
|
|
11
|
+
* member of another set operation, or mixed operators mis-associate — e.g.
|
|
12
|
+
* `a.union(b.except(c))` must render `a UNION (b EXCEPT c)`, not the flat
|
|
13
|
+
* `a UNION b EXCEPT c`.
|
|
14
|
+
*/
|
|
15
|
+
needsWrapForSetOperation = true;
|
|
16
|
+
exec;
|
|
17
|
+
members;
|
|
18
|
+
orderByItems = [];
|
|
19
|
+
limitValue;
|
|
20
|
+
constructor(exec, members) {
|
|
21
|
+
this.exec = exec;
|
|
22
|
+
this.members = members;
|
|
23
|
+
}
|
|
24
|
+
/** Append `UNION other`. */
|
|
25
|
+
union(other) {
|
|
26
|
+
return this.add("UNION", other);
|
|
27
|
+
}
|
|
28
|
+
/** Append `UNION ALL other`. */
|
|
29
|
+
unionAll(other) {
|
|
30
|
+
return this.add("UNION ALL", other);
|
|
31
|
+
}
|
|
32
|
+
/** Append `INTERSECT other`. */
|
|
33
|
+
intersect(other) {
|
|
34
|
+
return this.add("INTERSECT", other);
|
|
35
|
+
}
|
|
36
|
+
/** Append `EXCEPT other`. */
|
|
37
|
+
except(other) {
|
|
38
|
+
return this.add("EXCEPT", other);
|
|
39
|
+
}
|
|
40
|
+
/** `ORDER BY` applied to the combined result. */
|
|
41
|
+
orderBy(...terms) {
|
|
42
|
+
this.orderByItems.push(...terms.map((term) => renderOrderTerm(term)));
|
|
43
|
+
return this;
|
|
44
|
+
}
|
|
45
|
+
/** `LIMIT` applied to the combined result. */
|
|
46
|
+
limit(n) {
|
|
47
|
+
this.limitValue = n;
|
|
48
|
+
return this;
|
|
49
|
+
}
|
|
50
|
+
/** Re-type the combined result rows. */
|
|
51
|
+
returns() {
|
|
52
|
+
return this;
|
|
53
|
+
}
|
|
54
|
+
/** Render the combined statement. */
|
|
55
|
+
toSQL() {
|
|
56
|
+
const parts = this.members.map((member) => {
|
|
57
|
+
const text = renderMember(member.query);
|
|
58
|
+
return member.operator === void 0 ? text : `${member.operator} ${text}`;
|
|
59
|
+
});
|
|
60
|
+
const combined = parts.join(" ");
|
|
61
|
+
const tail = [];
|
|
62
|
+
if (this.orderByItems.length > 0) {
|
|
63
|
+
tail.push(`ORDER BY ${this.orderByItems.join(", ")}`);
|
|
64
|
+
}
|
|
65
|
+
if (this.limitValue !== void 0) {
|
|
66
|
+
tail.push(`LIMIT ${lit(this.limitValue)}`);
|
|
67
|
+
}
|
|
68
|
+
return tail.length > 0 ? `${combined} ${tail.join(" ")}` : combined;
|
|
69
|
+
}
|
|
70
|
+
/** Execute the combined query and return the typed result. */
|
|
71
|
+
async run() {
|
|
72
|
+
return this.exec(this.toSQL());
|
|
73
|
+
}
|
|
74
|
+
add(operator, other) {
|
|
75
|
+
this.members.push({ operator, query: other });
|
|
76
|
+
return this;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export { SetOperation as default };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const quoteString = (value) => `'${value.replaceAll("'", "''")}'`;
|
|
2
|
+
const IDENTIFIER_RE = /^\w+(?:\.\w+)*$/;
|
|
3
|
+
const TABLE_REF_RE = /^\w+(?:\.\w+)*(?:\s+(?:as\s+)?\w+)?$/i;
|
|
4
|
+
class Sql {
|
|
5
|
+
text;
|
|
6
|
+
constructor(text) {
|
|
7
|
+
this.text = text;
|
|
8
|
+
}
|
|
9
|
+
toString() {
|
|
10
|
+
return this.text;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const isSql = (value) => value instanceof Sql;
|
|
14
|
+
const raw = (text) => new Sql(text);
|
|
15
|
+
const toText = (value) => isSql(value) ? value.text : value;
|
|
16
|
+
const ident = (name) => {
|
|
17
|
+
if (typeof name !== "string" || !IDENTIFIER_RE.test(name)) {
|
|
18
|
+
throw new TypeError(`r2sql: invalid identifier ${JSON.stringify(name)} — expected dotted [A-Za-z0-9_] segments (e.g. "namespace.table").`);
|
|
19
|
+
}
|
|
20
|
+
return name;
|
|
21
|
+
};
|
|
22
|
+
const tableRef = (ref) => {
|
|
23
|
+
if (typeof ref !== "string" || !TABLE_REF_RE.test(ref)) {
|
|
24
|
+
throw new TypeError(`r2sql: invalid table reference ${JSON.stringify(ref)} — expected "namespace.table" with an optional "[AS] alias".`);
|
|
25
|
+
}
|
|
26
|
+
return ref;
|
|
27
|
+
};
|
|
28
|
+
const lit = (value) => {
|
|
29
|
+
if (value === null || value === void 0) {
|
|
30
|
+
return "NULL";
|
|
31
|
+
}
|
|
32
|
+
if (typeof value === "boolean") {
|
|
33
|
+
return value ? "true" : "false";
|
|
34
|
+
}
|
|
35
|
+
if (typeof value === "bigint") {
|
|
36
|
+
return value.toString();
|
|
37
|
+
}
|
|
38
|
+
if (typeof value === "number") {
|
|
39
|
+
if (!Number.isFinite(value)) {
|
|
40
|
+
throw new TypeError(`r2sql: cannot inline a non-finite number (${String(value)}) as a SQL literal.`);
|
|
41
|
+
}
|
|
42
|
+
return String(value);
|
|
43
|
+
}
|
|
44
|
+
if (typeof value === "string") {
|
|
45
|
+
return quoteString(value);
|
|
46
|
+
}
|
|
47
|
+
if (value instanceof Date) {
|
|
48
|
+
return quoteString(value.toISOString());
|
|
49
|
+
}
|
|
50
|
+
if (Array.isArray(value)) {
|
|
51
|
+
if (value.length === 0) {
|
|
52
|
+
throw new TypeError("r2sql: cannot inline an empty array — `IN ()` is not valid SQL. Guard the empty case before building the query.");
|
|
53
|
+
}
|
|
54
|
+
return `(${value.map((element) => lit(element)).join(", ")})`;
|
|
55
|
+
}
|
|
56
|
+
throw new TypeError(`r2sql: cannot inline a value of type ${typeof value} as a SQL literal. Wrap trusted SQL with raw(), or pass a primitive/Date/array.`);
|
|
57
|
+
};
|
|
58
|
+
const sql = (strings, ...values) => {
|
|
59
|
+
let out = strings[0] ?? "";
|
|
60
|
+
for (const [index, value] of values.entries()) {
|
|
61
|
+
out += isSql(value) ? value.text : lit(value);
|
|
62
|
+
out += strings[index + 1] ?? "";
|
|
63
|
+
}
|
|
64
|
+
return new Sql(out);
|
|
65
|
+
};
|
|
66
|
+
const joinSql = (parts, separator) => new Sql(parts.map((part) => toText(part)).join(separator));
|
|
67
|
+
|
|
68
|
+
export { Sql, ident, isSql, joinSql, lit, raw, sql, tableRef, toText };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Sql, lit } from './Sql-DceGtcUd.mjs';
|
|
2
|
+
|
|
3
|
+
const IDENTIFIER = /^[A-Z_][\w$]*$/i;
|
|
4
|
+
const assertIdent = (name) => {
|
|
5
|
+
if (!IDENTIFIER.test(name)) {
|
|
6
|
+
throw new TypeError(`r2sql: invalid identifier ${JSON.stringify(name)} — expected a simple SQL name (letters, digits, underscore).`);
|
|
7
|
+
}
|
|
8
|
+
return name;
|
|
9
|
+
};
|
|
10
|
+
class WindowExpression extends Sql {
|
|
11
|
+
/** Alias the expression — `... AS alias` — for use in a `SELECT` list. */
|
|
12
|
+
as(alias) {
|
|
13
|
+
return new Sql(`${this.text} AS ${assertIdent(alias)}`);
|
|
14
|
+
}
|
|
15
|
+
/** `expr BETWEEN low AND high`. */
|
|
16
|
+
between(low, high) {
|
|
17
|
+
return new Sql(`${this.text} BETWEEN ${lit(low)} AND ${lit(high)}`);
|
|
18
|
+
}
|
|
19
|
+
/** `expr = value`. */
|
|
20
|
+
eq(value) {
|
|
21
|
+
return this.compare("=", value);
|
|
22
|
+
}
|
|
23
|
+
/** `expr > value`. */
|
|
24
|
+
gt(value) {
|
|
25
|
+
return this.compare(">", value);
|
|
26
|
+
}
|
|
27
|
+
/** `expr >= value`. */
|
|
28
|
+
gte(value) {
|
|
29
|
+
return this.compare(">=", value);
|
|
30
|
+
}
|
|
31
|
+
/** `expr < value`. */
|
|
32
|
+
lt(value) {
|
|
33
|
+
return this.compare("<", value);
|
|
34
|
+
}
|
|
35
|
+
/** `expr <= value`. */
|
|
36
|
+
lte(value) {
|
|
37
|
+
return this.compare("<=", value);
|
|
38
|
+
}
|
|
39
|
+
compare(operator, value) {
|
|
40
|
+
return new Sql(`${this.text} ${operator} ${lit(value)}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { WindowExpression as default };
|