@peridotvault/peridotbase-sdk 0.0.0-stage → 0.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.
@@ -0,0 +1,1149 @@
1
+ import type { DdlEvent } from "./ddl";
2
+ import { PublicKey, Connection, Keypair } from "@solana/web3.js";
3
+ import { Program } from "@coral-xyz/anchor";
4
+ import { ColumnSpec, ColumnTypeName, OverflowValue, SqlValue, type TableGuardKind } from "./values";
5
+ import { ExprNode } from "./expr";
6
+ /** Page bytes a data page can hold before a new page is created. */
7
+ export declare const DEFAULT_PAGE_INITIAL_SPACE = 256;
8
+ /** Mirrors `DEFAULT_PK_BUCKETS` in the Rust program. */
9
+ export declare const DEFAULT_PK_BUCKETS = 256;
10
+ /** Mirrors `LAYOUT_VERSION` in the Rust program. */
11
+ export declare const LAYOUT_VERSION = 5;
12
+ export declare const DEFAULT_INDEX_BUCKET_INITIAL_SPACE = 256;
13
+ export declare const DEFAULT_MAX_PAGE_BYTES = 8192;
14
+ /** Mirrors `MAX_BATCH_ROWS` in the Rust program. */
15
+ export declare const MAX_BATCH_ROWS = 8;
16
+ /** Mirrors `MAX_BATCH_OPS` in the Rust program. One batch is one transaction. */
17
+ export declare const MAX_BATCH_OPS = 16;
18
+ /** Mirrors `MAX_OVERFLOW_CHUNK_BYTES` in the Rust program. */
19
+ export declare const MAX_OVERFLOW_CHUNK_BYTES = 700;
20
+ /** Mirrors `MAX_OVERFLOW_CHUNKS` in the Rust program. */
21
+ export declare const MAX_OVERFLOW_CHUNKS = 16;
22
+ /** Attempts (initial + retries) for contention-safe re-sends. */
23
+ export declare const MAX_SEND_ATTEMPTS = 4;
24
+ /** Solana packet ceiling; preflight rejects anything at or above it. */
25
+ export declare const MAX_TRANSACTION_BYTES = 1232;
26
+ /**
27
+ * Transactions handed to the wallet per approval when a batch is flushed.
28
+ *
29
+ * One approval for the whole batch: a single blockhash covers every packed
30
+ * transaction, so splitting the signing call would only add wallet prompts.
31
+ * Wallets that reject very large arrays can pass a smaller `signSize` to
32
+ * `flushBatch` explicitly.
33
+ */
34
+ export declare const DEFAULT_BATCH_SIGN_SIZE: number;
35
+ /** Signature placeholder for a write that is queued but not sent yet. */
36
+ export declare const PENDING_SIGNATURE = "";
37
+ /**
38
+ * One row mutation for `Table.executeBatch`. Every op in a call must target the
39
+ * same `(shardId, pageNo)` and carries at most `MAX_BATCH_ROWS` rows/keys.
40
+ */
41
+ export type BatchInputOp = {
42
+ kind: "insert";
43
+ rows: Record<string, any>[];
44
+ } | {
45
+ kind: "update";
46
+ key: SqlValue;
47
+ assignments: {
48
+ column: number;
49
+ value: SqlValue;
50
+ }[];
51
+ } | {
52
+ kind: "delete";
53
+ key: SqlValue;
54
+ };
55
+ export interface RpcStats {
56
+ /** Every instrumented `Connection` method invocation since the last reset. */
57
+ total: number;
58
+ byMethod: Record<string, number>;
59
+ }
60
+ export declare function rpcStats(): RpcStats;
61
+ /** Zeroes the counters so a test can measure a single operation. */
62
+ export declare function resetRpcStats(): void;
63
+ /**
64
+ * Rejects a transaction that cannot fit a Solana packet.
65
+ *
66
+ * Anchor calls `sendAndConfirm` before the transaction has a blockhash or fee
67
+ * payer, so the probe fills the missing fields, measures, and restores every
68
+ * mutated field (including `signatures`, which `compileMessage` rebuilds from
69
+ * the probe fee payer). Message size does not depend on the blockhash value,
70
+ * and web3.js writes each missing signature as 64 zero bytes, so the measured
71
+ * length already includes every signature the send path will attach.
72
+ */
73
+ export declare function assertTransactionFits(transaction: {
74
+ serialize: (options?: any) => Uint8Array;
75
+ }, maxBytes?: number, feePayerHint?: PublicKey): number;
76
+ export interface PeridotBaseOptions {
77
+ program: Program;
78
+ connection?: Connection;
79
+ /** Database namespace this client instance targets. */
80
+ databaseId?: number | bigint;
81
+ /** Organization scope for every project/database operation. */
82
+ organization?: PublicKey;
83
+ /** Project catalog address; owner of the targeted database. */
84
+ project?: PublicKey;
85
+ /** Project id used when only an organization is scoped; defaults to `databaseId`. */
86
+ projectId?: number | bigint;
87
+ /** Pubkey used in the organization PDA seeds; defaults to the wallet. */
88
+ organizationCreator?: PublicKey;
89
+ /** Default schema namespace for table operations; defaults to `public`. */
90
+ schema?: string;
91
+ /** Ordered schemas used to resolve unqualified table names. */
92
+ searchPath?: string[];
93
+ /**
94
+ * Optional fee payer distinct from the signing authority. The payer must be
95
+ * funded and, for an externally held key, supplied as `feePayerSigner`.
96
+ */
97
+ feePayer?: PublicKey;
98
+ /** Local keypair that signs as `feePayer` (delegated sponsorship). */
99
+ feePayerSigner?: Keypair;
100
+ /**
101
+ * Sponsor allowance PDA (`sponsorAllowancePda`) that pays mutation fees for
102
+ * this wallet. Create it with `createSponsorAllowance`; pass it here and every
103
+ * v3 insert/update/reinsert charges fees from the allowance until it is empty,
104
+ * expired, or revoked.
105
+ */
106
+ sponsorAllowance?: PublicKey;
107
+ /** Max serialized size of one data page before a new page is created. */
108
+ maxPageBytes?: number;
109
+ /**
110
+ * How long decoded table catalogs and role grants stay cached, in ms.
111
+ * `0` (the default) disables the cache so every read is authoritative;
112
+ * enable it for read-heavy workloads and accept bounded staleness across
113
+ * clients for up to the TTL. Local writes always invalidate their own keys.
114
+ */
115
+ metadataTtlMs?: number;
116
+ }
117
+ export interface ColumnModel extends ColumnSpec {
118
+ /** ENUM/DOMAIN catalog PDA, when present. */
119
+ typeRef?: PublicKey;
120
+ }
121
+ export interface ConstraintModel {
122
+ kind: "notNull" | "primaryKey" | "unique" | "check" | "appendOnly" | "denyDelete" | "denyUpdate" | "immutable" | "foreignKey" | "hasInboundForeignKeys" | "generatedStored" | "generatedVirtual" | "freezePolicies" | "policyTimelock" | "compositePrimaryKey" | "compositeIndex" | "coveringIndex" | "policyMultisig";
123
+ column: number;
124
+ expr: Buffer;
125
+ }
126
+ export interface IndexModel {
127
+ indexId: bigint;
128
+ name: string;
129
+ column: number;
130
+ /** Ordered index columns; `[column]` for single-column indexes. */
131
+ columns: number[];
132
+ /** Non-key columns covered by the index. */
133
+ includes: number[];
134
+ unique: boolean;
135
+ bucketCount: number;
136
+ nullsNotDistinct: boolean;
137
+ /** Number of chained pages behind each bucket (on-chain catalog). */
138
+ bucketChains: number[];
139
+ }
140
+ export interface PolicyModel {
141
+ policyId: bigint;
142
+ role: string;
143
+ ops: number;
144
+ predicate: Buffer;
145
+ }
146
+ export type AuditAction = "insert" | "update" | "delete" | "ddl" | "custom";
147
+ export interface AuditTrailModel {
148
+ address: PublicKey;
149
+ database: PublicKey;
150
+ sequence: bigint;
151
+ chainHash: Uint8Array;
152
+ /** Append-only Merkle accumulator root over every event hash. */
153
+ merkleRoot: Uint8Array;
154
+ merkleFrontier: Uint8Array[];
155
+ createdAt: bigint;
156
+ }
157
+ export interface AuditEventModel {
158
+ address: PublicKey;
159
+ database: PublicKey;
160
+ sequence: bigint;
161
+ tableId: bigint;
162
+ actor: PublicKey;
163
+ action: number;
164
+ subject: Uint8Array;
165
+ prevHash: Uint8Array;
166
+ eventHash: Uint8Array;
167
+ payload: Uint8Array;
168
+ createdAt: bigint;
169
+ }
170
+ export interface TableModel {
171
+ address: PublicKey;
172
+ tableId: bigint;
173
+ name: string;
174
+ /** Schema namespace PDA. */
175
+ schema?: PublicKey;
176
+ /** SHA-256 of the lowercased name; identifies the name-registry PDA. */
177
+ nameHash?: Uint8Array;
178
+ schemaVersion: number;
179
+ status: "active" | "dropped";
180
+ primaryKey: number;
181
+ /** Ordered PK columns; `[primaryKey]` for legacy single-column tables. */
182
+ primaryKeyColumns: number[];
183
+ columns: ColumnModel[];
184
+ constraints: ConstraintModel[];
185
+ indexes: IndexModel[];
186
+ policies: PolicyModel[];
187
+ shardCount: number;
188
+ rowCount: bigint;
189
+ /** Table-global primary-key bucket count. */
190
+ pkBucketCount: number;
191
+ }
192
+ /** Decoded `ShardDirectory`: data pages per shard and PK chain lengths. */
193
+ export interface DirectoryModel {
194
+ address: PublicKey;
195
+ table: PublicKey;
196
+ shardCount: number;
197
+ pages: PublicKey[][];
198
+ pkChains: number[];
199
+ }
200
+ /** Location of a live row, as stored in the primary-key index. */
201
+ export interface RowLocator {
202
+ shardId: number;
203
+ pageNo: number;
204
+ slot: number;
205
+ }
206
+ /** A query plan produced by the SDK planner (`where(...).explain()`). */
207
+ export interface QueryPlan {
208
+ strategy: "PRIMARY_KEY_LOOKUP" | "SECONDARY_INDEX_LOOKUP" | "TABLE_SCAN";
209
+ column: string;
210
+ operator: "=";
211
+ index?: string;
212
+ bucket?: number;
213
+ chainLength?: number;
214
+ requiresTableScan: boolean;
215
+ reason?: string;
216
+ }
217
+ export interface RowRecord {
218
+ values: SqlValue[];
219
+ live: boolean;
220
+ schemaVersion: number;
221
+ page: PublicKey;
222
+ pageNo: number;
223
+ shardId: number;
224
+ slot: number;
225
+ }
226
+ export interface CreateTableOptions {
227
+ tableId: number | bigint;
228
+ name: string;
229
+ columns: ColumnSpec[];
230
+ constraints?: ({
231
+ kind: "primaryKey";
232
+ column: string;
233
+ } | {
234
+ kind: "notNull";
235
+ column: string;
236
+ } | {
237
+ kind: "unique";
238
+ column: string;
239
+ } | {
240
+ kind: "check";
241
+ expr: ExprNode;
242
+ } | {
243
+ kind: "generatedStored";
244
+ column: string;
245
+ expr: ExprNode;
246
+ } | {
247
+ kind: "generatedVirtual";
248
+ column: string;
249
+ expr: ExprNode;
250
+ } | {
251
+ kind: "compositePrimaryKey";
252
+ columns: string[];
253
+ } | {
254
+ kind: "compositeUnique";
255
+ columns: string[];
256
+ })[];
257
+ indexes?: {
258
+ indexId?: number | bigint;
259
+ name: string;
260
+ /** Single-column shorthand. */
261
+ column?: string;
262
+ /** Ordered columns for a composite index. */
263
+ columns?: string[];
264
+ /** Non-key columns covered by the index. */
265
+ include?: string[];
266
+ unique?: boolean;
267
+ bucketCount?: number;
268
+ }[];
269
+ policies?: {
270
+ policyId: number | bigint;
271
+ role: "member" | "admin" | "owner";
272
+ ops: number;
273
+ predicate?: ExprNode;
274
+ }[];
275
+ shardCount?: number;
276
+ /** Table-global primary-key bucket count; 0 uses the program default. */
277
+ pkBucketCount?: number;
278
+ /** Number of shards to provision a page 0 for. Defaults to 1. */
279
+ provisionPages?: number;
280
+ /**
281
+ * Irreversible on-chain table guards. They are stored as schema constraints
282
+ * and enforced for every role, including the database owner.
283
+ */
284
+ guards?: Partial<Record<TableGuardKind, boolean>>;
285
+ /**
286
+ * Advanced: pre-compiled constraints whose bytecode must be preserved exactly
287
+ * (used by `createTableLike`). When present, `constraints` is ignored.
288
+ */
289
+ constraintDefs?: {
290
+ kind: string;
291
+ column: number;
292
+ expr: Buffer;
293
+ }[];
294
+ }
295
+ export interface InsertEstimate {
296
+ rows: number;
297
+ newPageRequired: boolean;
298
+ /** Top-up for the writable data page (REF payload for oversized TEXT). */
299
+ rentTopUpLamports: bigint;
300
+ /** Rent for overflow blob + chunk accounts created ahead of the write. */
301
+ overflowRentLamports: bigint;
302
+ networkFeeLamports: bigint;
303
+ protocolFeeLamports: bigint;
304
+ totalLamports: bigint;
305
+ }
306
+ export declare class PeridotBase {
307
+ readonly program: Program;
308
+ readonly programId: PublicKey;
309
+ readonly connection: Connection;
310
+ readonly wallet: PublicKey;
311
+ readonly databaseId: bigint;
312
+ readonly organization: PublicKey;
313
+ readonly organizationCreator: PublicKey;
314
+ readonly project: PublicKey;
315
+ readonly projectId: bigint;
316
+ readonly maxPageBytes: number;
317
+ readonly schemaName: string;
318
+ readonly searchPath: string[];
319
+ readonly feePayer: PublicKey;
320
+ /** Sponsor allowance that covers mutation fees for this wallet, if any. */
321
+ readonly sponsorAllowance?: PublicKey;
322
+ private readonly feePayerSigner?;
323
+ private views?;
324
+ private viewDepth;
325
+ private ensuredSchemas;
326
+ private protocolCache?;
327
+ private tableIds;
328
+ private pageCache;
329
+ /** Decoded table catalogs, valid for `metadataTtlMs` (0 disables). */
330
+ private tableCache;
331
+ /** Table models and directories a batch has planned but not sent yet. */
332
+ private readonly stagedModels;
333
+ private readonly stagedDirectories;
334
+ /** Organization staged per database while its `createDatabase` has not landed. */
335
+ private readonly stagedDatabases;
336
+ /** Role-grant helpers keyed by `database:principal`. */
337
+ private grantCache;
338
+ private readonly metadataTtlMs;
339
+ /**
340
+ * Writes already planned during the current batch but not sent yet, keyed
341
+ * by `tableId:page/bkt/index/pageNo`. Read paths consult this overlay so a
342
+ * second statement in the same batch does not provision the same account
343
+ * twice before the first transaction lands.
344
+ */
345
+ readonly batchOverlay: {
346
+ active: boolean;
347
+ /** Pages created/planned this batch: `tableId:shardId:pageNo`. */
348
+ pages: Set<string>;
349
+ /** PK bucket heads created/planned this batch: `tableId:bucket:chain`. */
350
+ pkPages: Set<string>;
351
+ /** Index bucket heads created/planned this batch: `tableId:indexId:bucket:pageNo`. */
352
+ indexPages: Set<string>;
353
+ /** Tables catalog-created during this batch: `tableId`. */
354
+ tables: Set<string>;
355
+ /** Synthetic page byte counts per `tableId:shardId:pageNo` for capacity picks. */
356
+ pageBytes: Map<string, number>;
357
+ };
358
+ constructor(options: PeridotBaseOptions);
359
+ /**
360
+ * Bounded, safe retry for shared-writable-account contention.
361
+ *
362
+ * Every mutation locks the table catalog, so parallel writers can lose the
363
+ * race before their transaction lands. `AccountInUse` means the runtime
364
+ * rejected the transaction without executing it, so re-sending the exact same
365
+ * signed transaction is safe. Confirmation timeouts are deliberately *not*
366
+ * retried: the transaction may already have landed.
367
+ *
368
+ * Every send is preflighted against the 1232-byte packet limit first, so an
369
+ * oversized transaction fails locally instead of on the wire.
370
+ */
371
+ private installContentionRetry;
372
+ private cacheKey;
373
+ /** Drops the cached catalog for one table (row count / schema changed). */
374
+ invalidateTableModel(tableId: number | bigint): void;
375
+ /** Stores a freshly decoded catalog so reads can reuse it within the TTL. */
376
+ cacheTableModel(model: TableModel): void;
377
+ /** Drops the cached role grants for `principal` in this database. */
378
+ invalidateGrant(principal: PublicKey): void;
379
+ get protocolAddress(): PublicKey;
380
+ organizationAddress(organizationId: number | bigint, creator?: PublicKey): PublicKey;
381
+ organizationMembershipAddress(organization: PublicKey, principal: PublicKey): PublicKey;
382
+ organizationPolicyAddress(organization: PublicKey): PublicKey;
383
+ extensionPolicyAddress(table: PublicKey): PublicKey;
384
+ organizationProposalAddress(organization: PublicKey, proposalId: number | bigint): PublicKey;
385
+ /** Optional policy accounts are always forwarded; uninitialized policy passes. */
386
+ private orgGovernanceAccounts;
387
+ projectAddress(projectId: number | bigint, organization?: PublicKey): PublicKey;
388
+ /**
389
+ * ponytail: an organization-only scope derives its project from `projectId`
390
+ * (default `databaseId`). Studio passes an explicit project; the fallback only
391
+ * keeps older callers/tests working without a second required argument.
392
+ */
393
+ databaseAddress(databaseId?: number | bigint, project?: PublicKey, organization?: PublicKey): PublicKey;
394
+ /** Schema catalog address for a name in the targeted database. */
395
+ schemaAddress(schemaName?: string): Promise<PublicKey>;
396
+ createSchema(name: string): Promise<string>;
397
+ /** Creates the schema on first use; safe to call repeatedly. */
398
+ ensureSchema(name?: string): Promise<PublicKey>;
399
+ typeAddress(name: string): Promise<PublicKey>;
400
+ createEnum(name: string, values: string[]): Promise<string>;
401
+ createDomain(name: string, options: {
402
+ base: ColumnTypeName;
403
+ scale?: number;
404
+ check: ExprNode;
405
+ }): Promise<string>;
406
+ private resolveTypeRefs;
407
+ schemaInfo(name?: string): Promise<any | null>;
408
+ tableAddress(tableId: number | bigint, databaseId?: number | bigint): PublicKey;
409
+ pageAddress(tableId: number | bigint, shardId: number, pageNo: number, databaseId?: number | bigint): PublicKey;
410
+ indexBucketAddress(tableId: number | bigint, indexId: number | bigint, bucketId: number, pageNo?: number, databaseId?: number | bigint): PublicKey;
411
+ indexCatalogAddress(tableId: number | bigint, indexId: number | bigint, databaseId?: number | bigint): PublicKey;
412
+ roleAddress(principal: PublicKey, databaseId?: number | bigint): PublicKey;
413
+ shardDirectoryAddress(tableId: number | bigint, databaseId?: number | bigint): PublicKey;
414
+ pkPageAddress(tableId: number | bigint, bucketId: number, chainNo: number, databaseId?: number | bigint): PublicKey;
415
+ overflowBlobAddress(tableId: number | bigint, key: Uint8Array, databaseId?: number | bigint): PublicKey;
416
+ overflowChunkAddress(tableId: number | bigint, key: Uint8Array, chunkNo: number, databaseId?: number | bigint): PublicKey;
417
+ private directoryCache;
418
+ /** Reads the on-chain shard directory (pages + PK chain lengths). */
419
+ directory(tableId: number | bigint, refresh?: boolean): Promise<DirectoryModel>;
420
+ /** Stages a planned table so later batch statements can resolve it without RPC. */
421
+ stageTableModel(model: TableModel, directory: DirectoryModel): void;
422
+ /** Drops staged models; called by `discardBatch` and `flushBatch`. */
423
+ private clearStagedModels;
424
+ /** Returns the staged directory for a queued table, if any. */
425
+ stagedDirectory(tableId: number | bigint): DirectoryModel | undefined;
426
+ /** Overwrites the staged model after a batched mutation changes the schema. */
427
+ stageSchemaChange(model: TableModel): void;
428
+ /** Drops cached metadata so the next read rebuilds from RPC. */
429
+ invalidate(tableId?: number | bigint): void;
430
+ private tableAddressDatabase;
431
+ initProtocol(options: {
432
+ treasury: PublicKey;
433
+ createDatabaseFee?: bigint;
434
+ createTableFee?: bigint;
435
+ createIndexFee?: bigint;
436
+ mutationFee?: bigint;
437
+ }): Promise<string>;
438
+ setProtocolFeeConfig(options: {
439
+ treasury?: PublicKey;
440
+ feeEnabled?: boolean;
441
+ createDatabaseFee?: bigint;
442
+ createTableFee?: bigint;
443
+ createIndexFee?: bigint;
444
+ mutationFee?: bigint;
445
+ paused?: boolean;
446
+ }): Promise<string>;
447
+ protocol(): Promise<any>;
448
+ treasury(): Promise<PublicKey>;
449
+ mutationFeePerRow(): Promise<bigint>;
450
+ createOrganization(options: {
451
+ organizationId: number | bigint;
452
+ name: string;
453
+ creator?: PublicKey;
454
+ }): Promise<string>;
455
+ /** Membership account for the current wallet, or `null` when it is the org owner. */
456
+ private callerMembership;
457
+ addOrganizationMember(organization: PublicKey, principal: PublicKey, role: "admin" | "member", proposalId?: number): Promise<string>;
458
+ updateOrganizationMember(organization: PublicKey, principal: PublicKey, role: "admin" | "member", proposalId?: number): Promise<string>;
459
+ removeOrganizationMember(organization: PublicKey, principal: PublicKey, proposalId?: number): Promise<string>;
460
+ transferOrganizationOwner(organization: PublicKey, newOwner: PublicKey, proposalId?: number): Promise<string>;
461
+ renameOrganization(organization: PublicKey, name: string, proposalId?: number): Promise<string>;
462
+ organizationPolicyInfo(organization: PublicKey): Promise<any | null>;
463
+ organizationProposalInfo(organization: PublicKey, proposalId: number): Promise<any | null>;
464
+ /**
465
+ * Creates the policy (owner only) or replaces it. Once a policy exists, the
466
+ * replacement itself needs `threshold` approvals via `proposalId`.
467
+ */
468
+ setOrganizationPolicy(organization: PublicKey, args: {
469
+ signers: PublicKey[];
470
+ threshold: number;
471
+ guardedActions: number;
472
+ recoveryAuthority?: PublicKey;
473
+ recoveryDelaySecs?: number;
474
+ }, proposalId?: number): Promise<string>;
475
+ /** First approval; `proposalId` must equal the policy counter. */
476
+ proposeOrganizationAction(organization: PublicKey, args: {
477
+ proposalId: number;
478
+ action: number;
479
+ digest: Buffer | Uint8Array;
480
+ expiresAt?: number;
481
+ }): Promise<string>;
482
+ approveOrganizationAction(organization: PublicKey, proposalId: number): Promise<string>;
483
+ /** Rent cleanup; only an executed or expired proposal can be closed. */
484
+ closeOrganizationProposal(organization: PublicKey, proposalId: number): Promise<string>;
485
+ initiateOrganizationRecovery(organization: PublicKey): Promise<string>;
486
+ cancelOrganizationRecovery(organization: PublicKey): Promise<string>;
487
+ executeOrganizationRecovery(organization: PublicKey, args: {
488
+ signers: PublicKey[];
489
+ threshold: number;
490
+ }): Promise<string>;
491
+ organizationInfo(organization: PublicKey): Promise<any>;
492
+ /**
493
+ * Decodes `DdlEvent` entries from transaction log messages. Anchor emits them
494
+ * as `Program data: <base64>`; non-event lines are ignored. Failed
495
+ * transactions also carry logs, so callers should check `meta.err`.
496
+ */
497
+ decodeDdlEvents(logs: string[]): DdlEvent[];
498
+ /** Organizations the connected wallet created, newest account first. */
499
+ listOrganizations(creator?: PublicKey): Promise<any[]>;
500
+ /** Projects owned by an organization. */
501
+ listProjects(organization?: PublicKey): Promise<any[]>;
502
+ /** Databases owned by a project. */
503
+ listDatabases(project?: PublicKey): Promise<any[]>;
504
+ organizationMemberInfo(organization: PublicKey, principal: PublicKey): Promise<any | null>;
505
+ /** Creates the parent project catalog. One project owns many databases. */
506
+ createProject(options: {
507
+ projectId: number | bigint;
508
+ name: string;
509
+ organization?: PublicKey;
510
+ payer?: PublicKey;
511
+ }): Promise<string>;
512
+ projectInfo(project?: PublicKey): Promise<any>;
513
+ /**
514
+ * Creates the project catalog when it does not exist yet, so an
515
+ * organization-only client can still mint its first database.
516
+ */
517
+ ensureProject(options: {
518
+ organization: PublicKey;
519
+ projectId: number | bigint;
520
+ name?: string;
521
+ payer?: PublicKey;
522
+ }): Promise<PublicKey>;
523
+ createDatabase(options: {
524
+ databaseId?: number | bigint;
525
+ name: string;
526
+ /** Project that owns the database. Defaults to this client's project scope. */
527
+ project?: PublicKey;
528
+ projectId?: number | bigint;
529
+ /** Derived from the project catalog when omitted. */
530
+ organization?: PublicKey;
531
+ payer?: PublicKey;
532
+ }): Promise<string>;
533
+ private organizationOf;
534
+ renounceDatabaseAuthority(databaseId?: number | bigint): Promise<string>;
535
+ /**
536
+ * Starts the staged close. When the organization policy guards
537
+ * `ORG_ACTION.closeDatabase`, pass the approved `proposal` address (see
538
+ * `closeDatabaseDigest`); otherwise the policy PDA alone is enough.
539
+ */
540
+ beginCloseDatabase(databaseId?: number | bigint, proposal?: PublicKey): Promise<string>;
541
+ /** Digest an organization must approve before a guarded `beginCloseDatabase`. */
542
+ closeDatabaseDigest(databaseId?: number | bigint): Promise<Buffer>;
543
+ /** Rent beneficiary for a database: treasury after an external write, else org owner. */
544
+ private closeBeneficiary;
545
+ closeDatabaseBatch(accounts: PublicKey[], databaseId?: number | bigint): Promise<string>;
546
+ /**
547
+ * Closes one table catalog and its name registry. Only valid after every child
548
+ * account of that table passed through `closeDatabaseBatch`; the catalog is
549
+ * the lineage anchor those batches need, so the program keeps it until here.
550
+ */
551
+ closeTableCatalog(tableId: number | bigint, databaseId?: number | bigint): Promise<string>;
552
+ /** Cancels a staged close before any account or catalog was closed. */
553
+ cancelCloseDatabase(databaseId?: number | bigint): Promise<string>;
554
+ /**
555
+ * Closes every table of a database that went through `beginCloseDatabase`:
556
+ * children in chunks that always include the catalog (lineage anchor), then
557
+ * the catalog and its name registry, then `finishCloseDatabase`.
558
+ *
559
+ * `chunk` counts children only; the catalog is added on top, so the default
560
+ * 19 keeps every transaction at the program's 20-account close cap.
561
+ *
562
+ * Returns counts so callers can report what happened instead of assuming.
563
+ */
564
+ closeDatabaseContents(options?: {
565
+ chunk?: number;
566
+ tableIds?: Array<number | bigint>;
567
+ databaseId?: number | bigint;
568
+ }): Promise<{
569
+ tables: number;
570
+ batches: number;
571
+ accounts: number;
572
+ finished: string;
573
+ }>;
574
+ finishCloseDatabase(databaseId?: number | bigint): Promise<string>;
575
+ /** Enables append-only history retention for a v3 table (0 disables). */
576
+ setTableHistoryLimit(tableId: number | bigint, limit: number, databaseId?: number | bigint): Promise<string>;
577
+ /**
578
+ * Declares RANGE/LIST partitions for a v3 table, or clears them with
579
+ * `strategy: "none"`. The partition column must be a BIGINT-like primary-key
580
+ * column; each row's directory lane becomes its partition index, so a scan
581
+ * can visit one lane instead of all of them.
582
+ */
583
+ setTablePartitioning(tableId: number | bigint, options: {
584
+ strategy: "none" | "range" | "list";
585
+ column?: number;
586
+ /** RANGE: ascending exclusive upper bounds. LIST: listed values. */
587
+ bounds?: (number | bigint)[];
588
+ defaultPartition?: boolean;
589
+ }, databaseId?: number | bigint): Promise<string>;
590
+ /**
591
+ * Toggles on-chain audit enforcement: while enabled, every v3 insert, update,
592
+ * delete and reinsert must append an audit event in the same transaction.
593
+ */
594
+ setDatabaseAuditRequired(required: boolean, databaseId?: number | bigint): Promise<string>;
595
+ databaseInfo(databaseId?: number | bigint): Promise<any>;
596
+ /**
597
+ * Canonical audit accounts for a DDL statement. Empty unless the database
598
+ * has `require_audit` enabled; when it does, the program rejects DDL without
599
+ * these two trailing accounts.
600
+ */
601
+ private ddlAuditAccounts;
602
+ grantRole(principal: PublicKey, role: "admin" | "member", databaseId?: number | bigint): Promise<string>;
603
+ revokeRole(principal: PublicKey, databaseId?: number | bigint): Promise<string>;
604
+ /** Authorization helpers for `principal`: organization, membership, grant. */
605
+ roleHelpers(principal?: PublicKey, databaseId?: number | bigint): Promise<any[]>;
606
+ /** Caller's own authorization helpers for a mutation. */
607
+ private selfGrantAccounts;
608
+ /** Queued writes bypass the provider; only `PeridotBase` stages through it. */
609
+ private batchState;
610
+ /** True while an explicit batch collects writes instead of sending them. */
611
+ get batching(): boolean;
612
+ /**
613
+ * Starts a batch: from here every write stages an unsigned transaction and
614
+ * returns `PENDING_SIGNATURE` instead of prompting the wallet. Throws when a
615
+ * batch is already open on this provider.
616
+ */
617
+ beginBatch(): void;
618
+ /**
619
+ * Signs every staged write in a single wallet approval per
620
+ * `signSize` transactions and sends them strictly in order (parallel
621
+ * submissions trip `AccountInUse` on the shared catalog accounts).
622
+ *
623
+ * Confirmation waits are sequential too, so a failing transaction stops the
624
+ * flush and the error carries how many writes already landed.
625
+ */
626
+ flushBatch(signSize?: number): Promise<string[]>;
627
+ /** Discards every staged write without touching the wallet. */
628
+ discardBatch(): void;
629
+ /** Adds the delegated sponsor's signature when it is not the authority. */
630
+ private addSponsorSignature;
631
+ /** Legacy wallets sign one transaction per prompt; keep order for safety. */
632
+ private signOneByOne;
633
+ /**
634
+ * Packs instructions into the fewest legacy transactions that each fit under
635
+ * the packet limit (greedy first-fit; account order never changes).
636
+ *
637
+ * A read-only compute-budget preamble is prepended when callers do not set
638
+ * their own, so a packed transaction runs under the same CU profile as the
639
+ * single-instruction transactions it replaces.
640
+ */
641
+ private packTransactions;
642
+ private buildColumnDefs;
643
+ private createTableInstruction;
644
+ createTable(options: CreateTableOptions): Promise<Table>;
645
+ /**
646
+ * Creates a table with the same columns, constraints, CHECK bytecode and
647
+ * secondary indexes as `source`. Data is never copied. Guards are not copied
648
+ * unless the caller passes them explicitly, so a clone of an IMMUTABLE table
649
+ * is writable.
650
+ */
651
+ createTableLike(source: number | bigint | string, options: {
652
+ tableId: number | bigint;
653
+ name: string;
654
+ shardCount?: number;
655
+ pkBucketCount?: number;
656
+ provisionPages?: number;
657
+ guards?: Partial<Record<TableGuardKind, boolean>>;
658
+ }): Promise<Table>;
659
+ /**
660
+ * Rebuilds the table model from the caller's own options so statements later
661
+ * in a batch can resolve columns, constraints, and indexes without an RPC
662
+ * round trip to an account that does not exist yet.
663
+ */
664
+ private localTableModel;
665
+ private pkBucketCountOf;
666
+ private pageKey;
667
+ alterTable(tableId: number | bigint, addColumns: ColumnSpec[]): Promise<string>;
668
+ /**
669
+ * Changes a column's read-time default. Legacy rows that do not store the
670
+ * column materialize the new default; stored values are never rewritten.
671
+ */
672
+ alterColumnDefault(tableId: number | bigint, column: string | number, defaultValue: any): Promise<string>;
673
+ tableCommentAddress(tableId: number | bigint): PublicKey;
674
+ /** Sets or clears a bounded comment. Empty text clears it. */
675
+ setTableComment(tableId: number | bigint, text: string): Promise<string>;
676
+ tableComment(tableId: number | bigint): Promise<string | null>;
677
+ /**
678
+ * Renames a table without changing its table PDA. The old name-registry PDA is
679
+ * closed and refunded and the new one is created in the same transaction, so
680
+ * a failed rename cannot leave both or neither name claimed.
681
+ */
682
+ renameTable(tableId: number | bigint, newName: string): Promise<string>;
683
+ private createIndexBucketInstruction;
684
+ private createPkPageInstruction;
685
+ /** Creates the head (or next chained) page of a primary-key bucket. */
686
+ createPkPage(tableId: number | bigint, bucketId: number, chainNo: number, initialSpace?: number): Promise<string>;
687
+ /** Creates the next chained page of a secondary-index bucket. */
688
+ createIndexChainPage(tableId: number | bigint, indexId: number | bigint, bucketId: number, pageNo: number, initialSpace?: number): Promise<string>;
689
+ /**
690
+ * Writes an oversized TEXT value out of line: the blob account first, one
691
+ * transaction per chunk (the 1232-byte packet limit forbids batching 4 KiB),
692
+ * then `close_overflow` verifies the assembled length before the row may
693
+ * reference it. Returns the `Value::Ref` payload plus the created accounts.
694
+ */
695
+ storeOverflowText(options: {
696
+ tableId: number | bigint;
697
+ column: number;
698
+ pkBytes: Uint8Array;
699
+ text: string;
700
+ }): Promise<{
701
+ reference: OverflowValue;
702
+ blob: PublicKey;
703
+ chunks: PublicKey[];
704
+ }>;
705
+ private createPageInstruction;
706
+ createPage(tableId: number | bigint, shardId?: number, pageNo?: number, initialSpace?: number): Promise<string>;
707
+ createIndex(tableId: number | bigint, options: {
708
+ indexId: number | bigint;
709
+ name: string;
710
+ column: number;
711
+ unique?: boolean;
712
+ bucketCount?: number;
713
+ }): Promise<string>;
714
+ /**
715
+ * Declares a single-column foreign key in the same database. The target is
716
+ * the parent primary key, or a UNIQUE non-PK column via `parentColumn` plus
717
+ * its `parentIndexId`. `RESTRICT` and immediate `NO ACTION` are supported
718
+ * (the program has no deferred queue); the child table must be empty.
719
+ * Child rows must then be written through v3 storage.
720
+ */
721
+ createForeignKey(childTableId: number | bigint, options: {
722
+ fkId: number | bigint;
723
+ childColumn: string | number;
724
+ parentTableId: number | bigint;
725
+ parentColumn?: string | number;
726
+ parentIndexId?: number | bigint;
727
+ onDelete?: "restrict" | "noAction";
728
+ onUpdate?: "restrict" | "noAction";
729
+ }): Promise<string>;
730
+ /** Removes a foreign key; only allowed while the child table has no rows. */
731
+ dropForeignKey(childTableId: number | bigint, options: {
732
+ fkId: number | bigint;
733
+ parentTableId: number | bigint;
734
+ }): Promise<string>;
735
+ /**
736
+ * Declares a composite foreign key onto a parent composite UNIQUE index.
737
+ * Child columns are matched positionally to the index columns. `MATCH FULL`
738
+ * rejects a partially-NULL tuple; `MATCH SIMPLE` (default) skips any tuple
739
+ * containing a NULL.
740
+ */
741
+ createCompositeForeignKey(childTableId: number | bigint, options: {
742
+ fkId: number | bigint;
743
+ childColumns: Array<string | number>;
744
+ parentTableId: number | bigint;
745
+ parentIndexId?: number | bigint;
746
+ match?: "simple" | "full";
747
+ onDelete?: "restrict" | "noAction";
748
+ onUpdate?: "restrict" | "noAction";
749
+ }): Promise<string>;
750
+ /**
751
+ * Sets `NULLS NOT DISTINCT` on an index before any row exists. When enabled,
752
+ * a second NULL in a UNIQUE index is a duplicate.
753
+ */
754
+ setIndexNullsNotDistinct(tableId: number | bigint, indexId: number | bigint, nullsNotDistinct?: boolean): Promise<string>;
755
+ private provisionIndexBuckets;
756
+ /**
757
+ * Sends instructions in chunks small enough for a single transaction
758
+ * (bucket/page provisioning can exceed the 1232-byte packet limit otherwise).
759
+ */
760
+ private sendInstructions;
761
+ softDropTable(tableId: number | bigint): Promise<string>;
762
+ restoreTable(tableId: number | bigint): Promise<string>;
763
+ setPolicy(tableId: number | bigint, policies: {
764
+ policyId: number | bigint;
765
+ role: "member" | "admin" | "owner";
766
+ ops: number;
767
+ predicate?: ExprNode;
768
+ }[]): Promise<string>;
769
+ /**
770
+ * Pins an opt-in CPI extension: one callee program, one 8-byte instruction
771
+ * discriminator and the exact ordered accounts the callee receives. The
772
+ * program refuses to sign with a PDA, so the callee can never escalate.
773
+ */
774
+ setExtensionPolicy(tableId: number | bigint, input: {
775
+ program: PublicKey;
776
+ discriminator: Uint8Array | number[];
777
+ accounts: {
778
+ key: PublicKey;
779
+ writable?: boolean;
780
+ signer?: boolean;
781
+ }[];
782
+ }): Promise<string>;
783
+ /** Removes the extension policy and returns its rent to the owner. */
784
+ clearExtensionPolicy(tableId: number | bigint): Promise<string>;
785
+ /**
786
+ * Invokes the pinned extension. `accounts` must match the policy order,
787
+ * writability and signer flags exactly; the program rejects any drift.
788
+ */
789
+ invokeExtension(tableId: number | bigint, callee: PublicKey, data: Uint8Array | number[], accounts?: {
790
+ key: PublicKey;
791
+ writable?: boolean;
792
+ signer?: boolean;
793
+ }[]): Promise<string>;
794
+ /**
795
+ * Tightens irreversible table guards. A guard bit that is already set cannot
796
+ * be cleared: the program rejects any request that would relax the table.
797
+ */
798
+ setTableGuard(tableId: number | bigint, guards: Partial<Record<TableGuardKind, boolean>>): Promise<string>;
799
+ /** Reads the decoded guard bits for a table. */
800
+ tableGuards(tableId: number | bigint, refresh?: boolean): Promise<Record<TableGuardKind, boolean>>;
801
+ /** Enables an irreversible timelock for policy changes on a table. */
802
+ setPolicyTimelock(tableId: number | bigint, delaySeconds: number | bigint): Promise<string>;
803
+ policyMultisigAddress(tableId: number | bigint): PublicKey;
804
+ /** Installs the table's irreversible M-of-N policy signer set. */
805
+ setPolicyMultisig(tableId: number | bigint, signers: PublicKey[], threshold: number): Promise<string>;
806
+ approvePolicy(tableId: number | bigint, proposalId: number | bigint): Promise<string>;
807
+ policyProposalAddress(tableId: number | bigint, proposalId: number | bigint): PublicKey;
808
+ /** Proposes a policy change; it becomes applicable after the table's ETA. */
809
+ proposePolicy(tableId: number | bigint, options: {
810
+ proposalId: number | bigint;
811
+ policies: {
812
+ policyId: number | bigint;
813
+ role: "member" | "admin" | "owner";
814
+ ops: number;
815
+ predicate?: ExprNode;
816
+ }[];
817
+ }): Promise<string>;
818
+ /** Applies a proposal whose ETA has elapsed and closes it. */
819
+ applyPolicy(tableId: number | bigint, proposalId: number | bigint): Promise<string>;
820
+ /** Cancels a pending proposal and refunds its rent. */
821
+ cancelPolicy(tableId: number | bigint, proposalId: number | bigint): Promise<string>;
822
+ sponsorAllowanceAddress(sponsor?: PublicKey, grantee?: PublicKey): PublicKey;
823
+ /** Caps how many lamports of mutation fees `grantee` may spend, prepaid. */
824
+ createSponsorAllowance(options: {
825
+ grantee: PublicKey;
826
+ cap: number | bigint;
827
+ /** Unix seconds; omit or `0` for no expiry. */
828
+ expiresAt?: number | bigint;
829
+ }): Promise<string>;
830
+ /** Adds lamports to the cap and optionally replaces the expiry. */
831
+ topUpSponsorAllowance(options: {
832
+ grantee: PublicKey;
833
+ amount: number | bigint;
834
+ /** Unix seconds; omit to keep the current expiry. */
835
+ expiresAt?: number | bigint;
836
+ }): Promise<string>;
837
+ /** Revokes (sponsor) or, after expiry, reclaims (grantee) an allowance. */
838
+ closeSponsorAllowance(grantee: PublicKey, sponsor?: PublicKey): Promise<string>;
839
+ sponsorAllowanceInfo(sponsor?: PublicKey, grantee?: PublicKey): Promise<any | null>;
840
+ auditTrailAddress(databaseId?: number | bigint): PublicKey;
841
+ auditEventAddress(sequence: number | bigint, databaseId?: number | bigint): PublicKey;
842
+ /** Reads the audit head, or `null` before the first event. */
843
+ auditTrail(databaseId?: number | bigint): Promise<AuditTrailModel | null>;
844
+ /**
845
+ * Appends one event. The `subject` is a caller commitment; for row actions use
846
+ * the 32-byte primary-key digest so a verifier can tie the event to a record.
847
+ */
848
+ appendAuditEvent(options: {
849
+ tableId?: number | bigint;
850
+ action: AuditAction | number;
851
+ subject?: Uint8Array;
852
+ payload?: Uint8Array | string;
853
+ databaseId?: number | bigint;
854
+ }): Promise<{
855
+ signature: string;
856
+ sequence: bigint;
857
+ eventHash: Uint8Array;
858
+ }>;
859
+ /** Every audit event for this database, ordered by sequence. */
860
+ listAuditEvents(): Promise<AuditEventModel[]>;
861
+ /**
862
+ * Polls the audit trail and yields newly observed events in sequence order.
863
+ * This is a bounded client-side CDC stream: it reads canonical on-chain
864
+ * accounts, never invents events, and resumes from `fromSequence`.
865
+ */
866
+ watchAudit(options?: {
867
+ fromSequence?: number | bigint;
868
+ intervalMs?: number;
869
+ signal?: AbortSignal;
870
+ limit?: number;
871
+ }): AsyncGenerator<AuditEventModel>;
872
+ /**
873
+ * Push-style CDC: subscribes to the program log line emitted by
874
+ * `append_audit_event`, then fetches the canonical event account. Polling
875
+ * `watchAudit` remains the fallback when a websocket is unavailable.
876
+ */
877
+ watchAuditLive(options?: {
878
+ fromSequence?: number | bigint;
879
+ signal?: AbortSignal;
880
+ limit?: number;
881
+ /** Subscription timeout in ms; a timeout rejects and lets the caller poll. */
882
+ timeoutMs?: number;
883
+ }): AsyncGenerator<AuditEventModel>;
884
+ /** Recomputes the hash chain and reports the first broken link. */
885
+ verifyAuditTrail(): Promise<{
886
+ valid: boolean;
887
+ sequence: number;
888
+ brokenAt?: string;
889
+ }>;
890
+ private computeAuditHash;
891
+ loadTable(tableId: number | bigint, refresh?: boolean): Promise<Table>;
892
+ /** Rebuilds the name -> tableId map from RPC (no local cache needed). */
893
+ loadTables(databaseId?: number | bigint): Promise<TableModel[]>;
894
+ /**
895
+ * PostgreSQL-shaped introspection over the on-chain catalog. Every field is
896
+ * decoded from `TableCatalog`/`ShardDirectory`; nothing is cached off-chain.
897
+ */
898
+ informationSchema(databaseId?: number | bigint): Promise<{
899
+ schema: string;
900
+ databaseId: string;
901
+ tables: Array<{
902
+ name: string;
903
+ tableId: string;
904
+ schemaVersion: number;
905
+ status: "active" | "dropped";
906
+ primaryKey: string;
907
+ rowCount: string;
908
+ columns: Array<{
909
+ name: string;
910
+ type: string;
911
+ nullable: boolean;
912
+ default?: any;
913
+ }>;
914
+ constraints: Array<{
915
+ kind: string;
916
+ column?: string;
917
+ }>;
918
+ indexes: Array<{
919
+ name: string;
920
+ column: string;
921
+ unique: boolean;
922
+ }>;
923
+ guards: Record<TableGuardKind, boolean>;
924
+ }>;
925
+ }>;
926
+ /**
927
+ * Read-side completion hints for editors: SQL keywords plus the live table
928
+ * and column names. `prefix` filters case-insensitively. Purely advisory.
929
+ */
930
+ suggest(prefix?: string): Promise<{
931
+ keywords: string[];
932
+ tables: string[];
933
+ columns: Array<{
934
+ table: string;
935
+ name: string;
936
+ type: string;
937
+ }>;
938
+ }>;
939
+ /**
940
+ * Exports a table's schema and rows as plain JSON-friendly objects. This is a
941
+ * backup/inspection copy, not a new canonical store; restore is not automatic.
942
+ */
943
+ exportTable(tableIdOrName: number | bigint | string, options?: {
944
+ cap?: number;
945
+ }): Promise<any>;
946
+ /** Exports every table in the database using `exportTable`. */
947
+ dumpDatabase(options?: {
948
+ cap?: number;
949
+ }): Promise<any>;
950
+ table(tableIdOrName: number | bigint | string): Promise<Table>;
951
+ /** Same as `table`, but never triggers an RPC scan for queued creations. */
952
+ private batchedTable;
953
+ execute(sql: string, params?: any[] | Record<string, any>): Promise<any>;
954
+ /**
955
+ * Resolves non-correlated subqueries into literals / IN lists before the
956
+ * synchronous predicate evaluator runs. Correlated references are rejected
957
+ * explicitly instead of silently comparing against the wrong row.
958
+ */
959
+ /** `_peridotbase_views` journal; created on first CREATE VIEW. */
960
+ private viewJournal;
961
+ private viewStatements;
962
+ private resolveSubqueries;
963
+ /** Executes a subquery and returns canonical rows (first column first). */
964
+ private subqueryRows;
965
+ private executeStatement;
966
+ /** Projects raw canonical rows for a RETURNING clause. */
967
+ private projectRows;
968
+ /** Applies UPDATE assignments to a canonical row for RETURNING projection. */
969
+ private applyAssignments;
970
+ private valueKey;
971
+ private aggregateValue;
972
+ private evalAdvanced;
973
+ private executeAdvancedSelect;
974
+ /** Shared projection/grouping path for real tables and materialized CTEs. */
975
+ private projectAdvanced;
976
+ private executeCteSelect;
977
+ private nextBatchTableId;
978
+ nextTableId(): Promise<bigint>;
979
+ }
980
+ export declare class Table {
981
+ private client;
982
+ private maxPageBytes;
983
+ model: TableModel;
984
+ private directoryModel?;
985
+ private pendingPageBytes;
986
+ constructor(client: PeridotBase, model: TableModel, maxPageBytes: number);
987
+ /** Seeds the directory for a table whose creation is still queued in a batch. */
988
+ seedBatchDirectory(directory: DirectoryModel): void;
989
+ stagedDirectory(): DirectoryModel;
990
+ get columns(): ColumnModel[];
991
+ get primaryKey(): ColumnModel;
992
+ /** Re-reads the table catalog + shard directory from RPC (authoritative). */
993
+ private sync;
994
+ private directory;
995
+ private indexOn;
996
+ private indexByName;
997
+ /** Page numbers of a shard, straight from the on-chain shard directory. */
998
+ pages(shardId: number): Promise<number[]>;
999
+ private fetchPageAccount;
1000
+ private fetchPage;
1001
+ private fetchPkPage;
1002
+ private fetchIndexPage;
1003
+ helperGrants(): Promise<any[]>;
1004
+ private coerceRow;
1005
+ private overlayPageKey;
1006
+ private ensurePkBucket;
1007
+ private ensureDataPage;
1008
+ private ensureIndexBucket;
1009
+ /** Provisions index chain heads for the indexed (non-null, inline) values. */
1010
+ private ensureIndexBuckets;
1011
+ /** Chooses a page with capacity (or creates the next page of the shard). */
1012
+ private pickInsertPage;
1013
+ private requiresInline;
1014
+ /**
1015
+ * Replaces oversized TEXT values with `Value::Ref` payloads, writing blob and
1016
+ * chunk accounts first. Returns the row that can be written inline.
1017
+ */
1018
+ private prepareOverflow;
1019
+ private resolveOverflow;
1020
+ private decodeRow;
1021
+ toObject(values: SqlValue[]): Record<string, any>;
1022
+ /** Resolves a primary key to its row locator through the on-chain PK index. */
1023
+ pkLocator(pkBytes: Buffer): Promise<RowLocator | null>;
1024
+ /** Point lookup by primary key; `null` when the key is absent or deleted. */
1025
+ findUnique(pkValue: SqlValue): Promise<Record<string, any> | null>;
1026
+ /** Canonical-value variant of `findUnique` (used by SQL projection). */
1027
+ findUniqueValues(pkValue: SqlValue): Promise<SqlValue[] | null>;
1028
+ /** Rows whose indexed column equals `value`, resolved through the index. */
1029
+ selectByIndex(columnName: string, value: SqlValue): Promise<Record<string, any>[]>;
1030
+ /** Canonical-value variant of `selectByIndex` (used by SQL projection). */
1031
+ selectByIndexValues(columnName: string, value: SqlValue): Promise<SqlValue[][]>;
1032
+ /**
1033
+ * Fetches rows for a single-column equality without scanning data pages when
1034
+ * the column is the primary key or carries a secondary index.
1035
+ */
1036
+ valuesFor(columnName: string, value: SqlValue): Promise<SqlValue[][]>;
1037
+ /** Builds a planned query: `table.where("email", "=", v).first()`. */
1038
+ where(column: string, operator: "=", value: SqlValue): Query;
1039
+ explain(column: string, operator: "=", value: SqlValue): Promise<QueryPlan>;
1040
+ estimateInsert(records: Record<string, any>[]): Promise<InsertEstimate>;
1041
+ private requireSinglePrimaryKey;
1042
+ insert(records: Record<string, any>[]): Promise<{
1043
+ signatures: string[];
1044
+ inserted: number;
1045
+ }>;
1046
+ /** Coerces a user record to canonical values, applying column defaults. */
1047
+ materializeRecord(record: Record<string, any>): SqlValue[];
1048
+ updateByKey(pkValue: SqlValue, assignments: {
1049
+ column: number;
1050
+ value: SqlValue;
1051
+ }[]): Promise<any>;
1052
+ softDeleteByKey(pkValue: SqlValue): Promise<any>;
1053
+ /**
1054
+ * Applies several row mutations against one page in a single `execute_batch`
1055
+ * instruction, so one wallet signature covers the whole batch even for wallets
1056
+ * that do not implement `signAllTransactions`.
1057
+ *
1058
+ * Every op must target `(shardId, pageNo)` and carries at most 8 rows/keys; the
1059
+ * program re-validates constraints, uniqueness and index maintenance exactly as
1060
+ * the single-op instructions do.
1061
+ */
1062
+ executeBatch(params: {
1063
+ shardId: number;
1064
+ pageNo: number;
1065
+ ops: BatchInputOp[];
1066
+ }): Promise<string>;
1067
+ private helperBuilder;
1068
+ private addPkChain;
1069
+ private addIndexChain;
1070
+ private insertHelpers;
1071
+ private updateHelpers;
1072
+ private deleteHelpers;
1073
+ /** Full table scan. Never used by the indexed read paths. */
1074
+ scan(): Promise<RowRecord[]>;
1075
+ /** Rows as display objects; used by `dumpDatabase`/backup tooling. */
1076
+ exportObjects(options?: {
1077
+ cap?: number;
1078
+ }): Promise<{
1079
+ rows: Record<string, any>[];
1080
+ truncated: boolean;
1081
+ rowCount: number;
1082
+ }>;
1083
+ /**
1084
+ * Client-side statistics over a bounded scan. This is not a canonical
1085
+ * on-chain statistics account; it is an explicit ANALYZE-style helper.
1086
+ */
1087
+ analyze(options?: {
1088
+ cap?: number;
1089
+ }): Promise<{
1090
+ rowCount: number;
1091
+ columns: {
1092
+ name: string;
1093
+ nulls: number;
1094
+ distinct: number;
1095
+ min?: any;
1096
+ max?: any;
1097
+ }[];
1098
+ }>;
1099
+ /**
1100
+ * Read-side policy filter. Owners/Admins see everything. For Members, if any
1101
+ * SELECT policy exists, only rows whose predicate passes for `actor` are
1102
+ * returned. Solana accounts remain public; this does not hide bytes.
1103
+ */
1104
+ selectVisible(actor: PublicKey | Uint8Array, role?: "owner" | "admin" | "member"): Promise<SqlValue[][]>;
1105
+ selectVisibleObjects(actor: PublicKey | Uint8Array, role?: "owner" | "admin" | "member"): Promise<Record<string, any>[]>;
1106
+ select(predicate?: (row: SqlValue[], rowRecord: RowRecord) => boolean): Promise<SqlValue[][]>;
1107
+ count(): Promise<number>;
1108
+ /** Dumps decoded rows as objects keyed by column name (UUIDs as strings). */
1109
+ selectObjects(predicate?: (row: SqlValue[]) => boolean): Promise<Record<string, any>[]>;
1110
+ /**
1111
+ * Keyset pagination over one or more ordered columns. The cursor is the last
1112
+ * row's key values, so later pages do not shift when rows are inserted before
1113
+ * the cursor (unlike OFFSET). The scan is bounded and `complete` reports
1114
+ * whether every matching row was returned.
1115
+ */
1116
+ keysetPage(options: {
1117
+ columns: string[];
1118
+ after?: SqlValue[];
1119
+ limit: number;
1120
+ direction?: "asc" | "desc";
1121
+ cap?: number;
1122
+ }): Promise<{
1123
+ columns: string[];
1124
+ rows: Record<string, any>[];
1125
+ next: SqlValue[] | null;
1126
+ complete: boolean;
1127
+ scanned: number;
1128
+ }>;
1129
+ /**
1130
+ * Returns every child PDA owned by this table, for staged close batches.
1131
+ * The table catalog is deliberately excluded: it is the lineage anchor each
1132
+ * batch must carry and is closed separately by `closeTableCatalog`.
1133
+ */
1134
+ ownedAccounts(): Promise<PublicKey[]>;
1135
+ }
1136
+ /** A planned equality query produced by `Table.where(...)`. */
1137
+ export declare class Query {
1138
+ private table;
1139
+ private column;
1140
+ private operator;
1141
+ private value;
1142
+ constructor(table: Table, column: string, operator: "=", value: SqlValue);
1143
+ private columnIndex;
1144
+ explain(): Promise<QueryPlan>;
1145
+ get(): Promise<Record<string, any>[]>;
1146
+ getValues(): Promise<SqlValue[][]>;
1147
+ first(): Promise<Record<string, any> | null>;
1148
+ firstValues(): Promise<SqlValue[] | null>;
1149
+ }