@keystrokehq/snowflake 0.0.16 → 0.0.18

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.
Files changed (82) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +9 -233
  3. package/package.json +39 -171
  4. package/dist/accounts/index.d.mts +0 -40
  5. package/dist/accounts/index.mjs +0 -51
  6. package/dist/bulk/index.d.mts +0 -71
  7. package/dist/bulk/index.mjs +0 -65
  8. package/dist/catalog/index.d.mts +0 -144
  9. package/dist/catalog/index.mjs +0 -158
  10. package/dist/client/index.d.mts +0 -44
  11. package/dist/client/index.mjs +0 -273
  12. package/dist/common-DfpCwJx5.mjs +0 -92
  13. package/dist/credential-sets/index.d.mts +0 -3
  14. package/dist/credential-sets/index.mjs +0 -4
  15. package/dist/databases/index.d.mts +0 -2
  16. package/dist/databases/index.mjs +0 -3
  17. package/dist/errors-60AsF7Su.mjs +0 -95
  18. package/dist/events/index.d.mts +0 -382
  19. package/dist/events/index.mjs +0 -291
  20. package/dist/file-formats/index.d.mts +0 -39
  21. package/dist/file-formats/index.mjs +0 -48
  22. package/dist/functions/index.d.mts +0 -53
  23. package/dist/functions/index.mjs +0 -56
  24. package/dist/grants/index.d.mts +0 -93
  25. package/dist/grants/index.mjs +0 -102
  26. package/dist/index.d.mts +0 -4
  27. package/dist/index.mjs +0 -6
  28. package/dist/operations/index.d.mts +0 -1
  29. package/dist/operations/index.mjs +0 -1
  30. package/dist/org-admin/index.d.mts +0 -80
  31. package/dist/org-admin/index.mjs +0 -79
  32. package/dist/pipes/index.d.mts +0 -119
  33. package/dist/pipes/index.mjs +0 -106
  34. package/dist/procedures/index.d.mts +0 -61
  35. package/dist/procedures/index.mjs +0 -79
  36. package/dist/results/index.d.mts +0 -16
  37. package/dist/results/index.mjs +0 -64
  38. package/dist/retry-B4-9MZIp.mjs +0 -164
  39. package/dist/retry-w7cTp1QL.d.mts +0 -10
  40. package/dist/roles/index.d.mts +0 -60
  41. package/dist/roles/index.mjs +0 -74
  42. package/dist/rows/index.d.mts +0 -106
  43. package/dist/rows/index.mjs +0 -223
  44. package/dist/schemas/index.d.mts +0 -2
  45. package/dist/schemas/index.mjs +0 -4
  46. package/dist/schemas-catalog/index.d.mts +0 -2
  47. package/dist/schemas-catalog/index.mjs +0 -3
  48. package/dist/shares/index.d.mts +0 -56
  49. package/dist/shares/index.mjs +0 -77
  50. package/dist/snowflake-s3-sns-webhook.credential-set-D6bLAWy5.d.mts +0 -50
  51. package/dist/snowflake-s3-sns-webhook.credential-set-DzR7oWNK.mjs +0 -44
  52. package/dist/snowflake.credential-set-BxT7Gf3A.d.mts +0 -114
  53. package/dist/snowflake.credential-set-DE3gXf-a.mjs +0 -106
  54. package/dist/sql/index.d.mts +0 -84
  55. package/dist/sql/index.mjs +0 -209
  56. package/dist/sql-options-2k5xQ-oS.d.mts +0 -32
  57. package/dist/sql-options-D6GEa21F.mjs +0 -79
  58. package/dist/sql-safety-BZpAPsq6.mjs +0 -56
  59. package/dist/stages/index.d.mts +0 -64
  60. package/dist/stages/index.mjs +0 -81
  61. package/dist/statements-BumhMhN4.mjs +0 -81
  62. package/dist/statements-DJL0qVNA.d.mts +0 -238
  63. package/dist/status-page/index.d.mts +0 -510
  64. package/dist/status-page/index.mjs +0 -261
  65. package/dist/streaming/index.d.mts +0 -70
  66. package/dist/streaming/index.mjs +0 -56
  67. package/dist/streams/index.d.mts +0 -71
  68. package/dist/streams/index.mjs +0 -78
  69. package/dist/tables/index.d.mts +0 -2
  70. package/dist/tables/index.mjs +0 -3
  71. package/dist/tasks/index.d.mts +0 -79
  72. package/dist/tasks/index.mjs +0 -104
  73. package/dist/triggers/index.d.mts +0 -381
  74. package/dist/triggers/index.mjs +0 -1100
  75. package/dist/users/index.d.mts +0 -61
  76. package/dist/users/index.mjs +0 -67
  77. package/dist/verification/index.d.mts +0 -201
  78. package/dist/verification/index.mjs +0 -512
  79. package/dist/views/index.d.mts +0 -2
  80. package/dist/views/index.mjs +0 -3
  81. package/dist/warehouses/index.d.mts +0 -68
  82. package/dist/warehouses/index.mjs +0 -101
@@ -1,164 +0,0 @@
1
- //#region src/jwt.ts
2
- /**
3
- * Snowflake JWT signing + public-key fingerprint (RS256, key-pair auth).
4
- *
5
- * Isolate-safe — built on `globalThis.crypto.subtle`, no Node `crypto`
6
- * imports, no native SDKs. Works in Cloudflare Workers, Node 19+,
7
- * and any modern V8/JSC isolate.
8
- *
9
- * Reference: https://docs.snowflake.com/en/user-guide/key-pair-auth
10
- */
11
- const DEFAULT_JWT_LIFETIME_SECONDS = 3300;
12
- async function createSnowflakeJwt(input) {
13
- const now = Math.floor((input.now?.() ?? Date.now()) / 1e3);
14
- const exp = now + (input.lifetimeSeconds ?? DEFAULT_JWT_LIFETIME_SECONDS);
15
- const account = normalizeAccountForJwt(input.account).toUpperCase();
16
- const user = input.user.toUpperCase();
17
- const privateKey = await importRsaPrivateKey(input.privateKeyPem);
18
- const fingerprint = input.publicKeyFingerprint ?? await derivePublicKeyFingerprint(privateKey);
19
- const issuer = `${account}.${user}.${fingerprint}`;
20
- const subject = `${account}.${user}`;
21
- const header = {
22
- alg: "RS256",
23
- typ: "JWT"
24
- };
25
- const payload = {
26
- iss: issuer,
27
- sub: subject,
28
- iat: now,
29
- exp
30
- };
31
- const signingInput = `${base64UrlEncode(JSON.stringify(header))}.${base64UrlEncode(JSON.stringify(payload))}`;
32
- const signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, privateKey, new TextEncoder().encode(signingInput));
33
- return {
34
- token: `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`,
35
- expiresAt: exp,
36
- fingerprint,
37
- issuer,
38
- subject
39
- };
40
- }
41
- /**
42
- * Compute `SHA256:<base64>` fingerprint over the DER-encoded SPKI public key
43
- * derived from the PKCS#8 private key. Matches Snowflake's
44
- * `RSA_PUBLIC_KEY_FP` value shown by `DESC USER`.
45
- */
46
- async function derivePublicKeyFingerprint(privateKey) {
47
- const publicKey = await extractPublicKey(privateKey);
48
- const spkiDer = await crypto.subtle.exportKey("spki", publicKey);
49
- const digest = await crypto.subtle.digest("SHA-256", spkiDer);
50
- return `SHA256:${base64Encode(new Uint8Array(digest))}`;
51
- }
52
- async function extractPublicKey(privateKey) {
53
- const jwk = await crypto.subtle.exportKey("jwk", privateKey);
54
- const publicJwk = {
55
- kty: jwk.kty,
56
- n: jwk.n,
57
- e: jwk.e,
58
- alg: jwk.alg,
59
- ext: true
60
- };
61
- return crypto.subtle.importKey("jwk", publicJwk, {
62
- name: "RSASSA-PKCS1-v1_5",
63
- hash: "SHA-256"
64
- }, true, ["verify"]);
65
- }
66
- async function importRsaPrivateKey(pem) {
67
- const armor = peekPemArmor(pem);
68
- if (!armor) throw new TypeError("SNOWFLAKE_PRIVATE_KEY is not a PEM-encoded key.");
69
- if (armor.type !== "PRIVATE KEY") throw new TypeError(`Unsupported PEM type "${armor.type}". Expected PKCS#8 PEM ("-----BEGIN PRIVATE KEY-----"). Convert PKCS#1 keys with \`openssl pkcs8 -topk8 -nocrypt\`.`);
70
- return crypto.subtle.importKey("pkcs8", toArrayBuffer(base64Decode(armor.body)), {
71
- name: "RSASSA-PKCS1-v1_5",
72
- hash: "SHA-256"
73
- }, true, ["sign"]);
74
- }
75
- function toArrayBuffer(view) {
76
- const copy = new Uint8Array(view.byteLength);
77
- copy.set(view);
78
- return copy.buffer;
79
- }
80
- function peekPemArmor(pem) {
81
- const match = pem.match(/-----BEGIN ([A-Z ]+)-----([\s\S]*?)-----END \1-----/u);
82
- if (!match) return void 0;
83
- const type = match[1]?.trim();
84
- const body = match[2]?.replace(/\s+/gu, "");
85
- if (!type || !body) return void 0;
86
- return {
87
- type,
88
- body
89
- };
90
- }
91
- /**
92
- * Account identifiers accepted by Snowflake take one of these shapes:
93
- * - `orgname-accountname` (preferred)
94
- * - `account_locator.region`
95
- * - `account_locator.region.aws`
96
- * - `account_locator` (legacy single-region)
97
- *
98
- * The JWT `iss`/`sub` require just the account segment (everything before the
99
- * first dot for locator-form identifiers) — the org-account hyphen form is
100
- * passed through as-is.
101
- */
102
- function normalizeAccountForJwt(account) {
103
- const trimmed = account.trim();
104
- const firstDot = trimmed.indexOf(".");
105
- return firstDot === -1 ? trimmed : trimmed.slice(0, firstDot);
106
- }
107
- function base64UrlEncode(input) {
108
- return base64Encode(typeof input === "string" ? new TextEncoder().encode(input) : input).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
109
- }
110
- function base64Encode(bytes) {
111
- let binary = "";
112
- for (let i = 0; i < bytes.byteLength; i += 1) binary += String.fromCharCode(bytes[i] ?? 0);
113
- if (typeof btoa === "function") return btoa(binary);
114
- /* c8 ignore next */
115
- return Buffer.from(bytes).toString("base64");
116
- }
117
- function base64Decode(input) {
118
- if (typeof atob === "function") {
119
- const binary = atob(input);
120
- const bytes = new Uint8Array(binary.length);
121
- for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
122
- return bytes;
123
- }
124
- /* c8 ignore next */
125
- return new Uint8Array(Buffer.from(input, "base64"));
126
- }
127
-
128
- //#endregion
129
- //#region src/retry.ts
130
- const DEFAULT_RETRY_POLICY = {
131
- maxRetries: 4,
132
- baseDelayMs: 500,
133
- maxDelayMs: 2e4,
134
- jitterMs: 250
135
- };
136
- const RETRYABLE_KINDS = new Set([
137
- "rate_limit",
138
- "server_error",
139
- "timeout",
140
- "network"
141
- ]);
142
- function shouldRetry(kind, attempt, policy = DEFAULT_RETRY_POLICY) {
143
- if (attempt >= policy.maxRetries) return false;
144
- return RETRYABLE_KINDS.has(kind);
145
- }
146
- /**
147
- * Compute the delay (ms) before the next retry. If the server provided a
148
- * `Retry-After` header we respect it (clamped to `maxDelayMs`). Otherwise we
149
- * use `baseDelayMs * 2^attempt` with additive jitter, capped at `maxDelayMs`.
150
- */
151
- function computeBackoffMs({ attempt, retryAfterMs, policy = DEFAULT_RETRY_POLICY, random = Math.random }) {
152
- if (retryAfterMs !== void 0 && retryAfterMs >= 0) return Math.min(retryAfterMs, policy.maxDelayMs);
153
- const exponent = Math.max(0, attempt - 1);
154
- const base = policy.baseDelayMs * 2 ** exponent;
155
- const jitter = policy.jitterMs > 0 ? random() * policy.jitterMs : 0;
156
- return Math.min(policy.maxDelayMs, Math.floor(base + jitter));
157
- }
158
- async function defaultSleep(ms) {
159
- if (ms <= 0) return;
160
- await new Promise((resolve) => setTimeout(resolve, ms));
161
- }
162
-
163
- //#endregion
164
- export { createSnowflakeJwt as a, shouldRetry as i, computeBackoffMs as n, defaultSleep as r, DEFAULT_RETRY_POLICY as t };
@@ -1,10 +0,0 @@
1
- //#region src/retry.d.ts
2
- interface RetryPolicy {
3
- readonly maxRetries: number;
4
- readonly baseDelayMs: number;
5
- readonly maxDelayMs: number;
6
- /** Adds up to `jitterMs` random ms on top of each backoff. */
7
- readonly jitterMs: number;
8
- }
9
- //#endregion
10
- export { RetryPolicy as t };
@@ -1,60 +0,0 @@
1
- import { SnowflakeClient } from "../client/index.mjs";
2
- import { t as OptionMap } from "../sql-options-2k5xQ-oS.mjs";
3
- import { CatalogResult, ShowOptions, showRoles } from "../catalog/index.mjs";
4
-
5
- //#region src/roles/index.d.ts
6
- interface RoleContext {
7
- readonly warehouse?: string;
8
- readonly sessionRole?: string;
9
- }
10
- interface CreateRoleOptions extends RoleContext {
11
- readonly name: string;
12
- readonly orReplace?: boolean;
13
- readonly ifNotExists?: boolean;
14
- readonly comment?: string;
15
- readonly options?: OptionMap;
16
- }
17
- declare function createRole(client: SnowflakeClient, options: CreateRoleOptions): Promise<void>;
18
- interface AlterRoleOptions extends RoleContext {
19
- readonly name: string;
20
- readonly rename?: string;
21
- readonly set?: OptionMap;
22
- readonly unset?: readonly string[];
23
- readonly comment?: string;
24
- readonly ifExists?: boolean;
25
- }
26
- declare function alterRole(client: SnowflakeClient, options: AlterRoleOptions): Promise<void>;
27
- interface DropRoleOptions extends RoleContext {
28
- readonly name: string;
29
- readonly ifExists?: boolean;
30
- }
31
- declare function dropRole(client: SnowflakeClient, options: DropRoleOptions): Promise<void>;
32
- interface UseRoleOptions extends RoleContext {
33
- readonly name: string;
34
- }
35
- declare function useRole(client: SnowflakeClient, options: UseRoleOptions): Promise<void>;
36
- interface GrantRoleToUserOptions extends RoleContext {
37
- /** Role being granted. */
38
- readonly role: string;
39
- readonly user: string;
40
- }
41
- declare function grantRoleToUser(client: SnowflakeClient, options: GrantRoleToUserOptions): Promise<void>;
42
- interface RevokeRoleFromUserOptions extends RoleContext {
43
- readonly role: string;
44
- readonly user: string;
45
- }
46
- declare function revokeRoleFromUser(client: SnowflakeClient, options: RevokeRoleFromUserOptions): Promise<void>;
47
- interface GrantRoleToRoleOptions extends RoleContext {
48
- /** The child role being granted. */
49
- readonly role: string;
50
- /** The parent role that will inherit `role`. */
51
- readonly parentRole: string;
52
- }
53
- declare function grantRoleToRole(client: SnowflakeClient, options: GrantRoleToRoleOptions): Promise<void>;
54
- interface RevokeRoleFromRoleOptions extends RoleContext {
55
- readonly role: string;
56
- readonly parentRole: string;
57
- }
58
- declare function revokeRoleFromRole(client: SnowflakeClient, options: RevokeRoleFromRoleOptions): Promise<void>;
59
- //#endregion
60
- export { AlterRoleOptions, type CatalogResult, CreateRoleOptions, DropRoleOptions, GrantRoleToRoleOptions, GrantRoleToUserOptions, RevokeRoleFromRoleOptions, RevokeRoleFromUserOptions, RoleContext, type ShowOptions, UseRoleOptions, alterRole, createRole, dropRole, grantRoleToRole, grantRoleToUser, revokeRoleFromRole, revokeRoleFromUser, showRoles, useRole };
@@ -1,74 +0,0 @@
1
- import { executeSql } from "../sql/index.mjs";
2
- import { a as quoteLiteral, i as quoteIdentifier } from "../sql-safety-BZpAPsq6.mjs";
3
- import { t as formatOptions } from "../sql-options-D6GEa21F.mjs";
4
- import { showRoles } from "../catalog/index.mjs";
5
-
6
- //#region src/roles/index.ts
7
- async function createRole(client, options) {
8
- const prefix = `CREATE${options.orReplace ? " OR REPLACE" : ""} ROLE${options.ifNotExists ? " IF NOT EXISTS" : ""}`;
9
- const body = options.options && Object.keys(options.options).length > 0 ? ` ${formatOptions(options.options)}` : "";
10
- const comment = options.comment ? ` COMMENT = ${quoteLiteral(options.comment)}` : "";
11
- await executeSql(client, {
12
- statement: `${prefix} ${quoteIdentifier(options.name)}${body}${comment}`,
13
- warehouse: options.warehouse,
14
- role: options.sessionRole
15
- });
16
- }
17
- async function alterRole(client, options) {
18
- let tail;
19
- if (options.rename) tail = `RENAME TO ${quoteIdentifier(options.rename)}`;
20
- else if (options.set && Object.keys(options.set).length > 0) tail = `SET ${formatOptions(options.set)}`;
21
- else if (options.unset && options.unset.length > 0) tail = `UNSET ${options.unset.map((k) => k.toUpperCase()).join(", ")}`;
22
- else if (options.comment !== void 0) tail = `SET COMMENT = ${quoteLiteral(options.comment)}`;
23
- else throw new Error("alterRole requires one of: rename / set / unset / comment");
24
- await executeSql(client, {
25
- statement: `ALTER ROLE${options.ifExists ? " IF EXISTS" : ""} ${quoteIdentifier(options.name)} ${tail}`,
26
- warehouse: options.warehouse,
27
- role: options.sessionRole
28
- });
29
- }
30
- async function dropRole(client, options) {
31
- await executeSql(client, {
32
- statement: `DROP ROLE${options.ifExists ? " IF EXISTS" : ""} ${quoteIdentifier(options.name)}`,
33
- warehouse: options.warehouse,
34
- role: options.sessionRole
35
- });
36
- }
37
- async function useRole(client, options) {
38
- await executeSql(client, {
39
- statement: `USE ROLE ${quoteIdentifier(options.name)}`,
40
- warehouse: options.warehouse,
41
- role: options.sessionRole
42
- });
43
- }
44
- async function grantRoleToUser(client, options) {
45
- await executeSql(client, {
46
- statement: `GRANT ROLE ${quoteIdentifier(options.role)} TO USER ${quoteIdentifier(options.user)}`,
47
- warehouse: options.warehouse,
48
- role: options.sessionRole
49
- });
50
- }
51
- async function revokeRoleFromUser(client, options) {
52
- await executeSql(client, {
53
- statement: `REVOKE ROLE ${quoteIdentifier(options.role)} FROM USER ${quoteIdentifier(options.user)}`,
54
- warehouse: options.warehouse,
55
- role: options.sessionRole
56
- });
57
- }
58
- async function grantRoleToRole(client, options) {
59
- await executeSql(client, {
60
- statement: `GRANT ROLE ${quoteIdentifier(options.role)} TO ROLE ${quoteIdentifier(options.parentRole)}`,
61
- warehouse: options.warehouse,
62
- role: options.sessionRole
63
- });
64
- }
65
- async function revokeRoleFromRole(client, options) {
66
- await executeSql(client, {
67
- statement: `REVOKE ROLE ${quoteIdentifier(options.role)} FROM ROLE ${quoteIdentifier(options.parentRole)}`,
68
- warehouse: options.warehouse,
69
- role: options.sessionRole
70
- });
71
- }
72
-
73
- //#endregion
74
- export { alterRole, createRole, dropRole, grantRoleToRole, grantRoleToUser, revokeRoleFromRole, revokeRoleFromUser, showRoles, useRole };
@@ -1,106 +0,0 @@
1
- import { SnowflakeClient } from "../client/index.mjs";
2
- import { d as HydratedRow, v as SqlBinding } from "../statements-DJL0qVNA.mjs";
3
- //#region src/rows/index.d.ts
4
- /**
5
- * A value a caller can pass into an `insert` / `update` / `where` map. The
6
- * binding helper below maps each JS primitive onto a Snowflake type (`TEXT`,
7
- * `FIXED`, `REAL`, `BOOLEAN`, `TIMESTAMP_LTZ`) so the SQL API receives a
8
- * faithful typed value. Callers needing a specific Snowflake type can pass a
9
- * pre-built `SqlBinding` directly.
10
- */
11
- type RowValue = string | number | bigint | boolean | Date | null | undefined | SqlBinding;
12
- type RowRecord = Readonly<Record<string, RowValue>>;
13
- interface RowTableRef {
14
- readonly database?: string;
15
- readonly schema?: string;
16
- readonly table: string;
17
- }
18
- interface RowContext {
19
- readonly warehouse?: string;
20
- readonly role?: string;
21
- }
22
- /**
23
- * Map a JS value to its Snowflake typed binding. Callers who need full
24
- * control can pre-build a `{type, value}` object and pass it through.
25
- */
26
- declare function inferBinding(value: RowValue): SqlBinding;
27
- /**
28
- * Mutable binding builder. Internally indexes bindings starting at 1 and
29
- * returns the `?` placeholder for each append so callers can weave them into
30
- * their SQL composition.
31
- */
32
- declare class BindingBuilder {
33
- private readonly map;
34
- private counter;
35
- add(value: RowValue): string;
36
- toRecord(): Readonly<Record<string, SqlBinding>>;
37
- size(): number;
38
- }
39
- type OrderDirection = 'ASC' | 'DESC';
40
- interface FindRowsOptions extends RowTableRef, RowContext {
41
- readonly where?: RowRecord;
42
- readonly columns?: readonly string[];
43
- readonly orderBy?: readonly {
44
- readonly column: string;
45
- readonly direction?: OrderDirection;
46
- }[];
47
- readonly limit?: number;
48
- readonly offset?: number;
49
- }
50
- interface FindRowOptions extends RowTableRef, RowContext {
51
- readonly where: RowRecord;
52
- readonly columns?: readonly string[];
53
- }
54
- declare function findRows(client: SnowflakeClient, options: FindRowsOptions): Promise<readonly HydratedRow[]>;
55
- declare function findRow(client: SnowflakeClient, options: FindRowOptions): Promise<HydratedRow | undefined>;
56
- interface InsertRowOptions extends RowTableRef, RowContext {
57
- readonly row: RowRecord;
58
- }
59
- declare function insertRow(client: SnowflakeClient, options: InsertRowOptions): Promise<number>;
60
- interface BatchInsertOptions extends RowTableRef, RowContext {
61
- readonly rows: readonly RowRecord[];
62
- /**
63
- * When provided, use this explicit column list and look up each row's
64
- * value by column; when missing, use the union of keys from the first
65
- * row (all subsequent rows must share the same shape).
66
- */
67
- readonly columns?: readonly string[];
68
- }
69
- declare function batchInsert(client: SnowflakeClient, options: BatchInsertOptions): Promise<number>;
70
- interface UpdateRowOptions extends RowTableRef, RowContext {
71
- readonly where: RowRecord;
72
- readonly set: RowRecord;
73
- }
74
- declare function updateRow(client: SnowflakeClient, options: UpdateRowOptions): Promise<number>;
75
- interface DeleteRowOptions extends RowTableRef, RowContext {
76
- readonly where: RowRecord;
77
- }
78
- declare function deleteRow(client: SnowflakeClient, options: DeleteRowOptions): Promise<number>;
79
- interface UpsertRowOptions extends RowTableRef, RowContext {
80
- readonly row: RowRecord;
81
- /** Columns whose equality defines the MATCH condition. */
82
- readonly matchColumns: readonly string[];
83
- /**
84
- * Columns to write on UPDATE (defaults to every column in `row` except the
85
- * match columns, which are left untouched on match).
86
- */
87
- readonly updateColumns?: readonly string[];
88
- }
89
- interface UpsertRowResult {
90
- readonly inserted: number;
91
- readonly updated: number;
92
- }
93
- declare function upsertRow(client: SnowflakeClient, options: UpsertRowOptions): Promise<UpsertRowResult>;
94
- interface MergeRowsOptions extends RowTableRef, RowContext {
95
- /**
96
- * Raw MERGE statement source. Useful when callers want full control over
97
- * a merge and just want the client/context/binding infra. `statement`
98
- * should already reference the resolved FQN from
99
- * {@link buildFqn}/{@link quoteIdentifier}.
100
- */
101
- readonly statement: string;
102
- readonly bindings?: Readonly<Record<string, SqlBinding>>;
103
- }
104
- declare function mergeRows(client: SnowflakeClient, options: MergeRowsOptions): Promise<UpsertRowResult>;
105
- //#endregion
106
- export { BatchInsertOptions, BindingBuilder, DeleteRowOptions, FindRowOptions, FindRowsOptions, InsertRowOptions, MergeRowsOptions, OrderDirection, RowContext, RowRecord, RowTableRef, RowValue, UpdateRowOptions, UpsertRowOptions, UpsertRowResult, batchInsert, deleteRow, findRow, findRows, inferBinding, insertRow, mergeRows, updateRow, upsertRow };
@@ -1,223 +0,0 @@
1
- import { executeSql } from "../sql/index.mjs";
2
- import { i as quoteIdentifier, t as buildFqn } from "../sql-safety-BZpAPsq6.mjs";
3
-
4
- //#region src/rows/index.ts
5
- function isSqlBinding(value) {
6
- return typeof value === "object" && value !== null && "type" in value && "value" in value && typeof value.type === "string";
7
- }
8
- /**
9
- * Map a JS value to its Snowflake typed binding. Callers who need full
10
- * control can pre-build a `{type, value}` object and pass it through.
11
- */
12
- function inferBinding(value) {
13
- if (isSqlBinding(value)) return value;
14
- if (value === null || value === void 0) return {
15
- type: "TEXT",
16
- value: null
17
- };
18
- if (typeof value === "string") return {
19
- type: "TEXT",
20
- value
21
- };
22
- if (typeof value === "boolean") return {
23
- type: "BOOLEAN",
24
- value: value ? "true" : "false"
25
- };
26
- if (typeof value === "bigint") return {
27
- type: "FIXED",
28
- value: value.toString()
29
- };
30
- if (typeof value === "number") {
31
- if (Number.isNaN(value) || !Number.isFinite(value)) throw new TypeError("Cannot bind NaN or Infinity as a Snowflake value");
32
- return Number.isInteger(value) ? {
33
- type: "FIXED",
34
- value: value.toString()
35
- } : {
36
- type: "REAL",
37
- value: value.toString()
38
- };
39
- }
40
- if (value instanceof Date) return {
41
- type: "TIMESTAMP_LTZ",
42
- value: value.toISOString()
43
- };
44
- const unreachable = value;
45
- throw new TypeError(`Unsupported binding type: ${typeof unreachable}`);
46
- }
47
- /**
48
- * Mutable binding builder. Internally indexes bindings starting at 1 and
49
- * returns the `?` placeholder for each append so callers can weave them into
50
- * their SQL composition.
51
- */
52
- var BindingBuilder = class {
53
- map = {};
54
- counter = 0;
55
- add(value) {
56
- this.counter += 1;
57
- this.map[String(this.counter)] = inferBinding(value);
58
- return "?";
59
- }
60
- toRecord() {
61
- return this.map;
62
- }
63
- size() {
64
- return this.counter;
65
- }
66
- };
67
- function composeWhere(where, bindings) {
68
- const clauses = [];
69
- for (const [column, value] of Object.entries(where)) {
70
- if (value === null || value === void 0) {
71
- clauses.push(`${quoteIdentifier(column)} IS NULL`);
72
- continue;
73
- }
74
- clauses.push(`${quoteIdentifier(column)} = ${bindings.add(value)}`);
75
- }
76
- return clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
77
- }
78
- function composeSet(set, bindings) {
79
- const fragments = Object.entries(set).map(([column, value]) => `${quoteIdentifier(column)} = ${bindings.add(value)}`);
80
- if (fragments.length === 0) throw new Error("updateRow requires at least one column in `set`");
81
- return fragments.join(", ");
82
- }
83
- function executeRowStatement(client, sql, bindings, ctx) {
84
- return executeSql(client, {
85
- statement: sql,
86
- warehouse: ctx.warehouse,
87
- role: ctx.role,
88
- database: ctx.database,
89
- schema: ctx.schema,
90
- bindings: bindings.size() > 0 ? bindings.toRecord() : void 0
91
- });
92
- }
93
- /**
94
- * Read the first numeric value from the first row of a DML result.
95
- * Snowflake returns INSERT/UPDATE/DELETE stats as a single row with a
96
- * column like `"number of rows inserted"`.
97
- */
98
- function readAffectedRows(result) {
99
- if (result.rows.length === 0) return 0;
100
- const firstRow = result.rows[0];
101
- if (!firstRow) return 0;
102
- const values = Array.isArray(firstRow) ? firstRow : Object.values(firstRow);
103
- for (const value of values) {
104
- if (typeof value === "number") return value;
105
- if (typeof value === "bigint") return Number(value);
106
- if (typeof value === "string") {
107
- const parsed = Number(value);
108
- if (!Number.isNaN(parsed)) return parsed;
109
- }
110
- }
111
- return 0;
112
- }
113
- function composeColumnList(columns) {
114
- if (!columns || columns.length === 0) return "*";
115
- return columns.map((c) => quoteIdentifier(c)).join(", ");
116
- }
117
- function composeOrderBy(orderBy) {
118
- if (!orderBy || orderBy.length === 0) return "";
119
- return ` ORDER BY ${orderBy.map(({ column, direction }) => {
120
- const dir = direction === "DESC" ? " DESC" : " ASC";
121
- return `${quoteIdentifier(column)}${dir}`;
122
- }).join(", ")}`;
123
- }
124
- function composeLimitOffset(limit, offset) {
125
- let out = "";
126
- if (typeof limit === "number" && limit >= 0) out += ` LIMIT ${Math.floor(limit)}`;
127
- if (typeof offset === "number" && offset > 0) out += ` OFFSET ${Math.floor(offset)}`;
128
- return out;
129
- }
130
- async function findRows(client, options) {
131
- const bindings = new BindingBuilder();
132
- return (await executeRowStatement(client, `SELECT ${composeColumnList(options.columns)} FROM ${buildFqn(options.database, options.schema, options.table)}` + composeWhere(options.where ?? {}, bindings) + composeOrderBy(options.orderBy) + composeLimitOffset(options.limit, options.offset), bindings, options)).rows;
133
- }
134
- async function findRow(client, options) {
135
- return (await findRows(client, {
136
- ...options,
137
- limit: 1
138
- }))[0];
139
- }
140
- async function insertRow(client, options) {
141
- const columns = Object.keys(options.row);
142
- if (columns.length === 0) throw new Error("insertRow requires at least one column in `row`");
143
- const bindings = new BindingBuilder();
144
- const placeholders = columns.map((column) => bindings.add(options.row[column]));
145
- return readAffectedRows(await executeRowStatement(client, `INSERT INTO ${buildFqn(options.database, options.schema, options.table)} (${columns.map((c) => quoteIdentifier(c)).join(", ")}) VALUES (${placeholders.join(", ")})`, bindings, options));
146
- }
147
- async function batchInsert(client, options) {
148
- if (options.rows.length === 0) return 0;
149
- const first = options.rows[0];
150
- if (!first) return 0;
151
- const columns = options.columns ?? Object.keys(first);
152
- if (columns.length === 0) throw new Error("batchInsert requires at least one column");
153
- const bindings = new BindingBuilder();
154
- const valueTuples = options.rows.map((row) => {
155
- return `(${columns.map((column) => bindings.add(row[column])).join(", ")})`;
156
- });
157
- return readAffectedRows(await executeRowStatement(client, `INSERT INTO ${buildFqn(options.database, options.schema, options.table)} (${columns.map((c) => quoteIdentifier(c)).join(", ")}) VALUES ${valueTuples.join(", ")}`, bindings, options));
158
- }
159
- async function updateRow(client, options) {
160
- const bindings = new BindingBuilder();
161
- const setClause = composeSet(options.set, bindings);
162
- const whereClause = composeWhere(options.where, bindings);
163
- return readAffectedRows(await executeRowStatement(client, `UPDATE ${buildFqn(options.database, options.schema, options.table)} SET ${setClause}${whereClause}`, bindings, options));
164
- }
165
- async function deleteRow(client, options) {
166
- if (Object.keys(options.where).length === 0) throw new Error("deleteRow refuses an empty where filter; call executeSql to truncate intentionally");
167
- const bindings = new BindingBuilder();
168
- const whereClause = composeWhere(options.where, bindings);
169
- return readAffectedRows(await executeRowStatement(client, `DELETE FROM ${buildFqn(options.database, options.schema, options.table)}${whereClause}`, bindings, options));
170
- }
171
- function readMergeStats(result) {
172
- if (result.rows.length === 0) return {
173
- inserted: 0,
174
- updated: 0
175
- };
176
- const firstRow = result.rows[0];
177
- if (!firstRow) return {
178
- inserted: 0,
179
- updated: 0
180
- };
181
- const entries = Array.isArray(firstRow) ? result.columns.map((col, idx) => [col.name, firstRow[idx]]) : Object.entries(firstRow);
182
- let inserted = 0;
183
- let updated = 0;
184
- for (const [name, value] of entries) {
185
- const numeric = typeof value === "number" ? value : Number(value);
186
- if (!Number.isFinite(numeric)) continue;
187
- const key = name.toLowerCase();
188
- if (key.includes("insert")) inserted = numeric;
189
- else if (key.includes("update")) updated = numeric;
190
- }
191
- return {
192
- inserted,
193
- updated
194
- };
195
- }
196
- async function upsertRow(client, options) {
197
- const rowColumns = Object.keys(options.row);
198
- if (rowColumns.length === 0) throw new Error("upsertRow requires at least one column in `row`");
199
- if (options.matchColumns.length === 0) throw new Error("upsertRow requires at least one match column");
200
- for (const column of options.matchColumns) if (!rowColumns.includes(column)) throw new Error(`upsertRow match column "${column}" is missing from row`);
201
- const bindings = new BindingBuilder();
202
- const srcTuples = rowColumns.map((column) => bindings.add(options.row[column]));
203
- const fqn = buildFqn(options.database, options.schema, options.table);
204
- rowColumns.map((c) => quoteIdentifier(c)).join(", ");
205
- const matchPredicate = options.matchColumns.map((column) => `t.${quoteIdentifier(column)} = s.${quoteIdentifier(column)}`).join(" AND ");
206
- const updateSet = (options.updateColumns ?? rowColumns.filter((c) => !options.matchColumns.includes(c))).map((column) => `${quoteIdentifier(column)} = s.${quoteIdentifier(column)}`).join(", ");
207
- const insertCols = rowColumns.map((c) => quoteIdentifier(c)).join(", ");
208
- const insertVals = rowColumns.map((c) => `s.${quoteIdentifier(c)}`).join(", ");
209
- return readMergeStats(await executeRowStatement(client, `MERGE INTO ${fqn} t USING (SELECT ${srcTuples.map((placeholder, idx) => `${placeholder} AS ${quoteIdentifier(rowColumns[idx] ?? "")}`).join(", ")}) s ON ${matchPredicate}` + (updateSet ? ` WHEN MATCHED THEN UPDATE SET ${updateSet}` : "") + ` WHEN NOT MATCHED THEN INSERT (${insertCols}) VALUES (${insertVals})`, bindings, options));
210
- }
211
- async function mergeRows(client, options) {
212
- return readMergeStats(await executeSql(client, {
213
- statement: options.statement,
214
- warehouse: options.warehouse,
215
- role: options.role,
216
- database: options.database,
217
- schema: options.schema,
218
- bindings: options.bindings
219
- }));
220
- }
221
-
222
- //#endregion
223
- export { BindingBuilder, batchInsert, deleteRow, findRow, findRows, inferBinding, insertRow, mergeRows, updateRow, upsertRow };
@@ -1,2 +0,0 @@
1
- import { C as resultSetMetaDataSchema, D as sqlBindingValueSchema, E as snowflakeObjectRowSchema, O as sqlBindingsSchema, S as partitionInfoSchema, T as snowflakeIdentifier, _ as SnowflakeObjectRow, a as SubmitStatementInput, b as StatementContext, c as statementStatus, d as HydratedRow, f as PartitionResponse, g as ResultSetMetaData, h as PartitionInfo, i as StatementTerminalStatus, k as statementContextSchema, l as statementStatusCodeSchema, m as ColumnMeta, n as StatementResponse, o as cancelStatementResponseSchema, p as partitionResponseSchema, r as StatementStatus, s as statementResponseSchema, t as CancelStatementResponse, u as submitStatementInputSchema, v as SqlBinding, w as snowflakeFqn, x as columnMetaSchema, y as SqlBindings } from "../statements-DJL0qVNA.mjs";
2
- export { CancelStatementResponse, ColumnMeta, HydratedRow, PartitionInfo, PartitionResponse, ResultSetMetaData, SnowflakeObjectRow, SqlBinding, SqlBindings, StatementContext, StatementResponse, StatementStatus, StatementTerminalStatus, SubmitStatementInput, cancelStatementResponseSchema, columnMetaSchema, partitionInfoSchema, partitionResponseSchema, resultSetMetaDataSchema, snowflakeFqn, snowflakeIdentifier, snowflakeObjectRowSchema, sqlBindingValueSchema, sqlBindingsSchema, statementContextSchema, statementResponseSchema, statementStatus, statementStatusCodeSchema, submitStatementInputSchema };
@@ -1,4 +0,0 @@
1
- import { a as snowflakeIdentifier, c as sqlBindingsSchema, i as snowflakeFqn, l as statementContextSchema, n as partitionInfoSchema, o as snowflakeObjectRowSchema, r as resultSetMetaDataSchema, s as sqlBindingValueSchema, t as columnMetaSchema } from "../common-DfpCwJx5.mjs";
2
- import { a as submitStatementInputSchema, i as statementStatusCodeSchema, n as statementResponseSchema, o as partitionResponseSchema, r as statementStatus, t as cancelStatementResponseSchema } from "../statements-BumhMhN4.mjs";
3
-
4
- export { cancelStatementResponseSchema, columnMetaSchema, partitionInfoSchema, partitionResponseSchema, resultSetMetaDataSchema, snowflakeFqn, snowflakeIdentifier, snowflakeObjectRowSchema, sqlBindingValueSchema, sqlBindingsSchema, statementContextSchema, statementResponseSchema, statementStatus, statementStatusCodeSchema, submitStatementInputSchema };
@@ -1,2 +0,0 @@
1
- import { CatalogResult, FindSchemasOptions, ShowSchemasOptions, findSchemas, showSchemas } from "../catalog/index.mjs";
2
- export { type CatalogResult, type FindSchemasOptions, type ShowSchemasOptions, findSchemas, showSchemas };
@@ -1,3 +0,0 @@
1
- import { findSchemas, showSchemas } from "../catalog/index.mjs";
2
-
3
- export { findSchemas, showSchemas };