@rebasepro/types 0.29.0 → 0.29.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.
@@ -18,8 +18,14 @@ export declare const AGGREGATE_GROUP_TRANSFORMS: readonly AggregateGroupTransfor
18
18
  export declare function aggregateAlias(fn: string, field?: string, p?: number): string;
19
19
  /** `percentile`'s `p`, refused unless it is a fraction a key can name (0–1, at most three decimals). */
20
20
  export declare function isPercentileFraction(p: unknown): p is number;
21
- /** An `AggregateSelect` as a driver is handed it. */
21
+ /**
22
+ * An `AggregateSelect` as a driver is handed it — but for its `where`, which
23
+ * the caller decodes into the driver's `filter` (this package has no filter
24
+ * codec).
25
+ */
22
26
  export declare function toDriverAggregate(select: AggregateSelect<Record<string, unknown>>): DriverAggregate;
27
+ /** Whether `timeZone` names a time zone this runtime knows: an IANA name such as `Europe/Madrid`, or `UTC`. */
28
+ export declare function isTimeZoneName(timeZone: unknown): timeZone is string;
23
29
  /** The key a group comes back under: the column's name, or `<transform>_<field>`. */
24
30
  export declare function aggregateGroupKey(group: string | AggregateGroup | DriverAggregateGroup): string;
25
31
  /** A `groupBy` entry as a driver is handed it. */
@@ -3,6 +3,7 @@ import type { ResourceRef } from "../types/resources.js";
3
3
  import type { RebaseSdkData } from "./data.js";
4
4
  import type { EmailService } from "./email.js";
5
5
  import type { StorageSource } from "./storage.js";
6
+ import type { CallerSqlOptions } from "./data_driver.js";
6
7
  import type { CronJobStatus, CronJobLogEntry, CronJobListing, CronJobStarted } from "../types/cron.js";
7
8
  import type { BackupDownloadLink, BackupListing } from "../types/backup.js";
8
9
  import type { ApiKeysAPI, PersonalKeysAPI } from "../types/api_keys.js";
@@ -90,8 +91,12 @@ export interface AuthClient {
90
91
  * Get the current user's active sessions
91
92
  */
92
93
  getSessions?: () => Promise<DeviceSession[]>;
93
- revokeSession?: (sessionId: string) => Promise<void>;
94
- revokeAllSessions?: () => Promise<void>;
94
+ revokeSession?: (sessionId: string) => Promise<{
95
+ success: boolean;
96
+ }>;
97
+ revokeAllSessions?: () => Promise<{
98
+ success: boolean;
99
+ }>;
95
100
  /**
96
101
  * Sign out the current user and clear local session
97
102
  */
@@ -396,7 +401,7 @@ export type HistoryConfig = boolean | {
396
401
  * - `disconnected` — the outage has outlasted the blip budget (about 15 s).
397
402
  * Every live subscription and joined channel has been told
398
403
  * `CONNECTION_LOST` once, and the client keeps redialling — every 30 s at
399
- * most — for as long as any exists. When the socket is back each is
404
+ * most — for as long as one exists. When the socket is back each is
400
405
  * re-subscribed, and its next update carries what changed meanwhile.
401
406
  * - `closed` — `client.close()`. Final.
402
407
  *
@@ -668,6 +673,29 @@ export interface RebaseServerClient<DB = RegisteredDatabase> extends Omit<Rebase
668
673
  role?: string;
669
674
  params?: unknown[];
670
675
  }): Promise<Record<string, unknown>[]>;
676
+ /**
677
+ * One SQL statement as the service identity `{ uid: "service", roles:
678
+ * ["admin"] }` — the identity {@link dataAsAdmin} reads and writes as —
679
+ * under row-level security: the request role, the tables' policies
680
+ * evaluated, so it reaches what an admin reaches and nothing more. Unlike
681
+ * the owner's {@link sql} it cannot run DDL, and the auth store's sessions,
682
+ * keys and secrets are withheld from it. Read-only unless `{ write: true }`.
683
+ *
684
+ * For a function or a cron that enforces its own rules over tables only
685
+ * admins may read: the caller's {@link DataDriver.sql} (`getSql(c)`) would
686
+ * need the policies opened to the caller, and those same policies would
687
+ * open the tables on the public data API.
688
+ *
689
+ * The guard is the caller-SQL one: the text is the application's own,
690
+ * values go in `params`, and a statement that could change the session
691
+ * (and with it whose rows these are) is refused with `SQL_NOT_ALLOWED`, as
692
+ * is a second statement. A lone statement costs the round trips the
693
+ * owner's {@link sql} costs: one.
694
+ *
695
+ * Throws on a backend whose database has no row-level security to run it
696
+ * under.
697
+ */
698
+ sqlAsAdmin(query: string, options?: CallerSqlOptions): Promise<Record<string, unknown>[]>;
671
699
  /**
672
700
  * The storage source a bucket handle names. Always present server-side.
673
701
  *
@@ -586,6 +586,8 @@ export interface CollectionAccessor<M extends Record<string, unknown> = Record<s
586
586
  createMany?(data: Partial<EntityValues<M>>[], options?: {
587
587
  upsert?: boolean;
588
588
  onConflict?: readonly string[];
589
+ where?: WhereFor<M>;
590
+ ignoreDuplicates?: boolean;
589
591
  }): Promise<Entity<M>[]>;
590
592
  /**
591
593
  * Update an existing record by ID.
@@ -614,6 +616,10 @@ export interface CollectionAccessor<M extends Record<string, unknown> = Record<s
614
616
  * See {@link SDKCollectionClient.deleteMany}. Optional, as `createMany` is.
615
617
  */
616
618
  deleteMany?(ids: (string | number)[]): Promise<void>;
619
+ /** See {@link SDKCollectionClient.updateWhere}. Optional, as `createMany` is. */
620
+ updateWhere?(query: FilteredWriteParams<M>, data: Partial<EntityValues<M>>): Promise<Entity<M>[]>;
621
+ /** See {@link SDKCollectionClient.deleteWhere}. Optional, as `createMany` is. */
622
+ deleteWhere?(query: FilteredWriteParams<M>): Promise<number>;
617
623
  /**
618
624
  * Delete a record by ID.
619
625
  */
@@ -790,38 +796,58 @@ export type QueryComputedFields = {
790
796
  * change when nothing did (a write that set a column to its own value), never
791
797
  * the other way round.
792
798
  *
793
- * The result key is derived rather than chosen: `sum(total)` comes back as
794
- * `sum_total`, a bare `count()` as `count`, `countDistinct(sid)` as
795
- * `count_distinct_sid` and `percentile(fame, 0.95)` as `p95_fame` (see
796
- * {@link AggregateAlias}). Letting a caller name it would mean checking their
797
- * name is not also a `groupBy` field — a rule nobody would guess, and a
798
- * silently overwritten value if it went unchecked.
799
+ * `field` may also be a JSON path (`props->>players`): `sum`, `avg` and
800
+ * `percentile` read the value there as a number (a value that is not one is
801
+ * left out, as a filter leaves it out), the others as text.
802
+ *
803
+ * `where` counts only the rows it matches towards this one aggregate — SQL's
804
+ * `count(*) FILTER (WHERE …)` — so several differently filtered aggregates
805
+ * are one query over the rows the outer `where` chose.
806
+ *
807
+ * The result key is derived — `sum(total)` comes back as `sum_total`, a bare
808
+ * `count()` as `count`, `countDistinct(sid)` as `count_distinct_sid` and
809
+ * `percentile(fame, 0.95)` as `p95_fame` (see {@link AggregateAlias}) —
810
+ * unless `as` names it, which two aggregates of one function need: two
811
+ * filtered `count()`s would both be `count`. A name used twice, or the key of
812
+ * a `groupBy` column, is refused (`INVALID_AGGREGATE_SELECT`) rather than
813
+ * overwritten.
799
814
  *
800
815
  * @group Data
801
816
  */
802
- export type AggregateSelect<M extends Record<string, unknown> = Record<string, unknown>> = {
817
+ export type AggregateSelect<M extends Record<string, unknown> = Record<string, unknown>> = ({
803
818
  fn: "count";
804
- field?: Extract<keyof M, string>;
819
+ field?: Extract<keyof M, string> | JsonFieldPath;
805
820
  } | {
806
821
  fn: "sum" | "avg";
807
- field: NumericKeyOf<M>;
822
+ field: NumericKeyOf<M> | JsonFieldPath;
808
823
  } | {
809
824
  fn: "min" | "max" | "countDistinct" | "mode" | "distinct";
810
- field: Extract<keyof M, string>;
825
+ field: Extract<keyof M, string> | JsonFieldPath;
811
826
  } | {
812
827
  fn: "percentile";
813
- field: NumericKeyOf<M>;
828
+ field: NumericKeyOf<M> | JsonFieldPath;
814
829
  p: number;
815
830
  } | {
816
831
  fn: "fingerprint";
832
+ }) & {
833
+ /** Only the rows matching this count towards this aggregate: `FILTER (WHERE …)`. */
834
+ where?: WhereFor<M>;
835
+ /** The key the aggregate comes back under, instead of the derived one. */
836
+ as?: string;
817
837
  };
838
+ /** A path inside a json/jsonb column: `props->>players`, `meta->a->>b`. @group Data */
839
+ export type JsonFieldPath = `${string}->>${string}`;
818
840
  /**
819
841
  * A transformed column to group by, where a plain column will not do:
820
- * `lower`/`upper` of a text column, the `year`/`month`/`day` of a date (in
821
- * UTC, served as `"2026"`, `"2026-11"`, `"2026-11-08"`), or `unnest` — one
822
- * group per element of an array column, so `count()` beside it counts the rows
842
+ * `lower`/`upper` of a text column, the `year`/`month`/`day` of a timestamp
843
+ * (served as `"2026"`, `"2026-11"`, `"2026-11-08"`), or `unnest` — one group
844
+ * per element of an array column, so `count()` beside it counts the rows
823
845
  * holding each element.
824
846
  *
847
+ * `year`/`month`/`day` read the instant in UTC, or in `timeZone` (an IANA
848
+ * name, `"Europe/Madrid"`): "per day" for people in one place means their
849
+ * days, and a UTC day splits their evening in two.
850
+ *
825
851
  * Its key in each row is `<transform>_<field>` (`lower_artist`,
826
852
  * `unnest_tags`), which is also how `orderBy` names it.
827
853
  *
@@ -830,6 +856,8 @@ export type AggregateSelect<M extends Record<string, unknown> = Record<string, u
830
856
  export type AggregateGroup<Field extends string = string> = {
831
857
  field: Field;
832
858
  transform: AggregateGroupTransform;
859
+ /** `year`/`month`/`day` only: the IANA time zone the instant is read in. UTC when absent. */
860
+ timeZone?: string;
833
861
  };
834
862
  /** What an {@link AggregateGroup} does to its column. @group Data */
835
863
  export type AggregateGroupTransform = "lower" | "upper" | "unnest" | "year" | "month" | "day";
@@ -879,10 +907,11 @@ export interface AggregateParams<M extends Record<string, unknown> = Record<stri
879
907
  select: AggregateSelect<M>[];
880
908
  /**
881
909
  * Columns to group by — or a column transformed ({@link AggregateGroup}),
882
- * e.g. `{ field: "artist", transform: "lower" }`. Omit for a single row
883
- * over everything that matches.
910
+ * e.g. `{ field: "artist", transform: "lower" }`, or a JSON path
911
+ * (`props->>music`, its text; its key in each row is the path as written).
912
+ * Omit for a single row over everything that matches.
884
913
  */
885
- groupBy?: (Extract<keyof M, string> | AggregateGroup<Extract<keyof M, string>>)[];
914
+ groupBy?: (Extract<keyof M, string> | JsonFieldPath | AggregateGroup<Extract<keyof M, string>>)[];
886
915
  /** Filter conditions, as {@link FindParams.where}. */
887
916
  where?: WhereFor<M>;
888
917
  /** An `and`/`or`/`not` group, AND-ed with `where`. */
@@ -1270,9 +1299,49 @@ export type FieldOperationFor<T> = unknown extends T ? FieldOperation : (NonNull
1270
1299
  *
1271
1300
  * @group Data
1272
1301
  */
1273
- export interface UpsertOptions extends WriteOptions {
1302
+ export interface UpsertOptions<M extends Record<string, unknown> = Record<string, unknown>> extends WriteOptions {
1274
1303
  /** Column names forming the conflict target. Defaults to the primary key. */
1275
1304
  onConflict?: readonly string[];
1305
+ /**
1306
+ * Replace a stored row only when it matches this filter, evaluated on the
1307
+ * stored row: `ON CONFLICT … DO UPDATE … WHERE`. A stored row it does not
1308
+ * match is left as it is, and nothing comes back for it. One statement,
1309
+ * so "keep the higher score" or "only if newer" cannot lose a race.
1310
+ *
1311
+ * ```ts
1312
+ * // Writes the score only when it beats the stored one.
1313
+ * const kept = await data.scores.upsert(
1314
+ * { day, sid, hype },
1315
+ * { where: { hype: ["<", hype] } }
1316
+ * ); // undefined when the stored score was higher
1317
+ * ```
1318
+ */
1319
+ where?: WhereFor<M>;
1320
+ /**
1321
+ * Leave a stored row on the conflict target as it is — `ON CONFLICT DO
1322
+ * NOTHING` — and return nothing for it. Insert-or-skip: an idempotent
1323
+ * claim, or a re-runnable import of rows that never change. Not with
1324
+ * `where`.
1325
+ */
1326
+ ignoreDuplicates?: boolean;
1327
+ }
1328
+ /**
1329
+ * The rows a filtered write ({@link SDKCollectionClient.updateWhere},
1330
+ * {@link SDKCollectionClient.deleteWhere}) addresses: the same `where` and
1331
+ * `logical` a `find()` takes, AND-ed.
1332
+ *
1333
+ * At least one condition. A filtered write with none would address every row,
1334
+ * which is the mistake this shape is most exposed to — a filter built from an
1335
+ * empty form, a key misspelled — so it is refused with `FILTER_REQUIRED`
1336
+ * rather than run. A field that is not a column is refused too, never dropped.
1337
+ *
1338
+ * @group Data
1339
+ */
1340
+ export interface FilteredWriteParams<M extends Record<string, unknown> = Record<string, unknown>> {
1341
+ /** Filter conditions, as {@link FindParams.where}. */
1342
+ where?: WhereFor<M>;
1343
+ /** An `and`/`or`/`not` group, AND-ed with `where`. */
1344
+ logical?: LogicalConditionFor<M>;
1276
1345
  }
1277
1346
  /**
1278
1347
  * A placeholder standing for a value only the server will know: the id of a row
@@ -1652,6 +1721,10 @@ Inc = IncludeSpec> {
1652
1721
  * second genuine import — so it performs it again, duplicating every row in
1653
1722
  * the batch rather than just one.
1654
1723
  *
1724
+ * With `upsert`, `ignoreDuplicates` and `where` say what happens to a row
1725
+ * already on the conflict target, as on {@link upsert}: left alone, or
1726
+ * replaced only when it matches. A row left alone is not in the answer.
1727
+ *
1655
1728
  * @returns The written rows, in the order given.
1656
1729
  *
1657
1730
  * @example
@@ -1664,6 +1737,8 @@ Inc = IncludeSpec> {
1664
1737
  createMany(data: I[], options?: {
1665
1738
  upsert?: boolean;
1666
1739
  onConflict?: readonly string[];
1740
+ where?: WhereFor<M>;
1741
+ ignoreDuplicates?: boolean;
1667
1742
  } & WriteOptions): Promise<M[]>;
1668
1743
  /**
1669
1744
  * Update an existing record by ID.
@@ -1708,6 +1783,11 @@ Inc = IncludeSpec> {
1708
1783
  * re-import that reset `createdAt` on everything it touched would take
1709
1784
  * every "new this week" query with it.
1710
1785
  *
1786
+ * `where` replaces a stored row only when it matches, and
1787
+ * `ignoreDuplicates` never replaces one ({@link UpsertOptions}): with
1788
+ * either, the call resolves to `undefined` when the stored row was left
1789
+ * as it was.
1790
+ *
1711
1791
  * @example
1712
1792
  * ```ts
1713
1793
  * await client.data.products.upsert(
@@ -1716,10 +1796,15 @@ Inc = IncludeSpec> {
1716
1796
  * );
1717
1797
  * ```
1718
1798
  */
1719
- upsert(data: I, options: UpsertOptions & {
1799
+ upsert(data: I, options: UpsertOptions<M> & {
1720
1800
  returning: false;
1721
1801
  }): Promise<M | undefined>;
1722
- upsert(data: I, options?: UpsertOptions): Promise<M>;
1802
+ upsert(data: I, options: UpsertOptions<M> & ({
1803
+ where: WhereFor<M>;
1804
+ } | {
1805
+ ignoreDuplicates: true;
1806
+ })): Promise<M | undefined>;
1807
+ upsert(data: I, options?: UpsertOptions<M>): Promise<M>;
1723
1808
  /**
1724
1809
  * Update many records in a single request and a single transaction.
1725
1810
  *
@@ -1762,6 +1847,52 @@ Inc = IncludeSpec> {
1762
1847
  id: string | number;
1763
1848
  data: U | UpdateValues<U>;
1764
1849
  }[], options?: WriteOptions): Promise<M[]>;
1850
+ /**
1851
+ * Update every record a filter matches, in one statement, and return the
1852
+ * records it updated.
1853
+ *
1854
+ * `UPDATE … SET … WHERE <filter> RETURNING *`: atomic, one round trip,
1855
+ * and the filter is evaluated by the statement that writes — so it is
1856
+ * also a compare-and-set. Field operations work as on {@link update}:
1857
+ *
1858
+ * ```ts
1859
+ * // Claim a save slot only if nobody wrote it since revision 7.
1860
+ * const [saved] = await data.saves.updateWhere(
1861
+ * { where: { who: ["==", who], rev: ["==", 7] } },
1862
+ * { body, rev: { $inc: 1 } }
1863
+ * ); // undefined when the revision moved on
1864
+ * ```
1865
+ *
1866
+ * Matching nothing is not an error: the answer is `[]`. Row-level
1867
+ * security applies as to any write. On a collection whose writes run
1868
+ * per-row work — a save hook, history, tenancy, a `beforeQuery`, a trash,
1869
+ * per-field access — the matching rows are read under the caller's scope
1870
+ * and updated one by one through the full pipeline, in one transaction.
1871
+ *
1872
+ * The filter takes at least one condition ({@link FilteredWriteParams}).
1873
+ * Shares `createMany`'s row cap when it runs row by row.
1874
+ */
1875
+ updateWhere(query: FilteredWriteParams<M>, data: U | UpdateValues<U>, options?: WriteOptions): Promise<M[]>;
1876
+ /**
1877
+ * Delete every record a filter matches, in one statement, and return how
1878
+ * many went.
1879
+ *
1880
+ * `DELETE … WHERE <filter>`: atomic and one round trip, where a read
1881
+ * followed by {@link deleteMany} is two and can delete a row that changed
1882
+ * in between. Matching nothing is not an error — the answer is `0` — which
1883
+ * also makes it the delete for a row that may already be gone:
1884
+ *
1885
+ * ```ts
1886
+ * await data.passes.deleteWhere({ where: { token: ["==", token] } });
1887
+ * ```
1888
+ *
1889
+ * Per-row work (`beforeDelete`/`afterDelete`, history, a trash, a
1890
+ * `beforeQuery`) is honoured as {@link updateWhere} honours it: the
1891
+ * matching rows are deleted one by one through the pipeline, in one
1892
+ * transaction. The filter takes at least one condition
1893
+ * ({@link FilteredWriteParams}).
1894
+ */
1895
+ deleteWhere(query: FilteredWriteParams<M>, options?: WriteOptions): Promise<number>;
1765
1896
  /**
1766
1897
  * Delete a record by ID.
1767
1898
  * @throws {RebaseApiError} with status 404 when the record does not exist.
@@ -1776,11 +1907,8 @@ Inc = IncludeSpec> {
1776
1907
  /**
1777
1908
  * Delete many records in a single request and a single transaction.
1778
1909
  *
1779
- * Takes ids, not a filter. A filter-shaped bulk delete is a different and
1780
- * far more dangerous operation — the failure mode is an omitted or
1781
- * mistyped condition emptying a table, and it cannot be reviewed at the
1782
- * call site the way an explicit list can. Read first, then pass the ids you
1783
- * meant.
1910
+ * Takes ids. To delete by a condition, use {@link deleteWhere}, which
1911
+ * refuses an empty filter rather than emptying the table.
1784
1912
  *
1785
1913
  * `beforeDelete` and `afterDelete` fire per row, exactly as they do for
1786
1914
  * single deletes, and returning `false` from `beforeDelete` fails the batch
@@ -1791,10 +1919,7 @@ Inc = IncludeSpec> {
1791
1919
  *
1792
1920
  * @example
1793
1921
  * ```ts
1794
- * const stale = await client.data.sessions.findAll({
1795
- * where: { expires_at: ["<", cutoff] }
1796
- * });
1797
- * await client.data.sessions.deleteMany(stale.map(s => s.id as string));
1922
+ * await client.data.sessions.deleteMany(["s-1", "s-2"]);
1798
1923
  * ```
1799
1924
  */
1800
1925
  deleteMany(ids: (string | number)[], options?: WriteOptions): Promise<void>;
@@ -2065,6 +2190,16 @@ export type RebaseSdkData<DB = unknown> = (unknown extends DB ? unknown : TypedS
2065
2190
  * await accessor.find({ limit: 10 });
2066
2191
  */
2067
2192
  collection<M extends Record<string, unknown> = Record<string, unknown>>(slug: string): SDKCollectionClient<M>;
2193
+ /**
2194
+ * A mixed list of writes across collections, as one transaction: the
2195
+ * in-process form of the HTTP client's `client.batch()`, with the same
2196
+ * operations, `$ref`s and answer. `collection` is the accessor, as
2197
+ * everywhere on this object.
2198
+ *
2199
+ * Reserved, as `collection` is: a collection whose accessor is `batch` is
2200
+ * reached with `data.collection("batch")`.
2201
+ */
2202
+ batch(operations: BatchOperation<unknown extends DB ? Record<string, unknown> : DB>[]): Promise<BatchResult>;
2068
2203
  } & (unknown extends DB ? {
2069
2204
  /**
2070
2205
  * Dynamic flat collection accessor.
@@ -282,6 +282,47 @@ export interface SaveManyProps<M extends Record<string, unknown> = Record<string
282
282
  upsert?: boolean;
283
283
  /** The conflict target for those upserts. See {@link SaveProps.onConflict}. */
284
284
  onConflict?: readonly string[];
285
+ /**
286
+ * With `upsert`: the stored row the conflict-update may write, as a filter
287
+ * on its columns — `ON CONFLICT … DO UPDATE … WHERE`. A stored row it does
288
+ * not match is left as it is and left out of the answer. What a "keep the
289
+ * best score" or "only if newer" write needs, in one statement.
290
+ */
291
+ conflictWhere?: FilterValues<string>;
292
+ /**
293
+ * With `upsert`: leave a stored row on the conflict target untouched —
294
+ * `ON CONFLICT DO NOTHING` — and leave it out of the answer. The
295
+ * insert-or-skip an idempotent claim needs.
296
+ */
297
+ ignoreDuplicates?: boolean;
298
+ }
299
+ /**
300
+ * The rows a filtered write ({@link DataDriver.updateWhere},
301
+ * {@link DataDriver.deleteWhere}) addresses: the same `filter` and `logical`
302
+ * a read takes, AND-ed. At least one condition — a filtered write with none
303
+ * would address every row, and is refused (`FILTER_REQUIRED`).
304
+ *
305
+ * @internal
306
+ */
307
+ export interface WriteFilterProps<M extends Record<string, unknown> = Record<string, unknown>> {
308
+ path: string;
309
+ filter?: FilterValues<string>;
310
+ logical?: LogicalCondition;
311
+ collection?: CollectionConfig<M>;
312
+ }
313
+ /**
314
+ * @internal
315
+ */
316
+ export interface UpdateWhereProps<M extends Record<string, unknown> = Record<string, unknown>> extends WriteFilterProps<M> {
317
+ /** What to set on every row the filter matches; field operations (`$inc`, …) included. */
318
+ values: Partial<EntityValues<M>>;
319
+ }
320
+ /**
321
+ * @internal
322
+ */
323
+ export interface DeleteWhereProps<M extends Record<string, unknown> = Record<string, unknown>> extends WriteFilterProps<M> {
324
+ /** See {@link DeleteProps.hard}. */
325
+ hard?: boolean;
285
326
  }
286
327
  /**
287
328
  * @internal
@@ -401,6 +442,16 @@ export type FilterCombinationValidProps = {
401
442
  filterValues: FilterValues<string>;
402
443
  sortBy?: [string, "asc" | "desc"];
403
444
  };
445
+ /** Options of {@link DataDriver.sql}. */
446
+ export interface CallerSqlOptions {
447
+ /** The statement's values, referenced as `$1`, `$2`, … in the query text. */
448
+ params?: unknown[];
449
+ /**
450
+ * Run in a read-write transaction. Off by default: the statement runs
451
+ * read-only, and an `INSERT`, `UPDATE` or `DELETE` fails with `25006`.
452
+ */
453
+ write?: boolean;
454
+ }
404
455
  /**
405
456
  * The integration SPI for plugging a data backend into Rebase.
406
457
  *
@@ -500,6 +551,22 @@ export interface DataDriver {
500
551
  * a caller reaches for a batch to get.
501
552
  */
502
553
  updateMany?<M extends Record<string, unknown> = Record<string, unknown>>(props: UpdateManyProps<M>): Promise<Record<string, unknown>[]>;
554
+ /**
555
+ * Update every row a filter matches, as one statement where nothing needs
556
+ * the rows one by one (no hook, no history, no tenancy), and through the
557
+ * per-row pipeline in one transaction where something does. Resolves to
558
+ * the rows updated, which may be none: a filter matching nothing is not an
559
+ * error, and is how a compare-and-set reports that it lost.
560
+ *
561
+ * Optional: a driver that cannot do it atomically leaves it undefined.
562
+ */
563
+ updateWhere?<M extends Record<string, unknown> = Record<string, unknown>>(props: UpdateWhereProps<M>): Promise<Record<string, unknown>[]>;
564
+ /**
565
+ * Delete every row a filter matches, under the same rules as
566
+ * {@link updateWhere}. Resolves to how many rows went; none is not an
567
+ * error.
568
+ */
569
+ deleteWhere?<M extends Record<string, unknown> = Record<string, unknown>>(props: DeleteWhereProps<M>): Promise<number>;
503
570
  /**
504
571
  * Recompute the rows of a collection that serves a materialized view —
505
572
  * see `SDKCollectionClient.refresh`. Optional: only a driver with views
@@ -568,8 +635,7 @@ export interface DataDriver {
568
635
  /**
569
636
  * Delete many rows in one transaction, addressed by id.
570
637
  *
571
- * Ids rather than a filter, deliberately — see
572
- * {@link SDKCollectionClient.deleteMany}. Optional, as `saveMany` is.
638
+ * Ids; a filter is {@link deleteWhere}. Optional, as `saveMany` is.
573
639
  */
574
640
  deleteMany?<M extends Record<string, unknown> = Record<string, unknown>>(props: DeleteManyProps<M>): Promise<void>;
575
641
  /**
@@ -626,6 +692,26 @@ export interface DataDriver {
626
692
  * Optional: a driver without it is called directly, read by read.
627
693
  */
628
694
  readTogether?<T>(work: (driver: DataDriver) => Promise<T>): Promise<T>;
695
+ /**
696
+ * Run one SQL statement as this driver's identity: in the caller's own
697
+ * transaction, under the same row-level security as every read and write
698
+ * on this driver, so the tables' policies decide which rows it sees and
699
+ * changes. Read-only unless `write: true`.
700
+ *
701
+ * The query text must be the application's own. Every value — above all
702
+ * anything a user sent — goes in `params` as `$1`, `$2`, …: identity rides
703
+ * in session settings, and a statement able to change them is refused
704
+ * (`SQL_NOT_ALLOWED`), as is more than one statement.
705
+ *
706
+ * Policies are what it shares with the SDK, and all it shares. Per-field
707
+ * `access` rules, `afterRead`/`beforeQuery` hooks, validation, save hooks
708
+ * and history are application code the SDK runs and this does not.
709
+ *
710
+ * Optional: an engine without row-level security has none. On the
711
+ * server's own (unscoped) driver it is absent too — that one's raw SQL is
712
+ * `admin.executeSql`, which runs as the owner.
713
+ */
714
+ sql?(query: string, options?: CallerSqlOptions): Promise<Record<string, unknown>[]>;
629
715
  /**
630
716
  * Every row a collection stores, as stored, a page at a time: soft-deleted
631
717
  * rows included, and past every read hook — no `beforeQuery`, no
@@ -701,16 +787,20 @@ export interface DataDriver {
701
787
  */
702
788
  export interface DriverAggregate {
703
789
  fn: "count" | "sum" | "avg" | "min" | "max" | "countDistinct" | "mode" | "percentile" | "distinct" | "fingerprint";
704
- /** Absent for `count()` and `fingerprint()`. */
790
+ /** Absent for `count()` and `fingerprint()`. A column, or a JSON path (`props->>players`). */
705
791
  field?: string;
706
792
  /** `percentile`'s fraction, 0–1. */
707
793
  p?: number;
794
+ /** Only the rows matching this count towards the aggregate: SQL's `FILTER (WHERE …)`. */
795
+ filter?: FilterValues<string>;
708
796
  alias: string;
709
797
  }
710
798
  /** A transformed group (`AggregateGroup`) as a driver is handed it, with the key it comes back under. */
711
799
  export interface DriverAggregateGroup {
712
800
  field: string;
713
801
  transform: AggregateGroupTransform;
802
+ /** `year`/`month`/`day`: the IANA time zone the date is read in. UTC when absent. */
803
+ timeZone?: string;
714
804
  /** `<transform>_<field>`. */
715
805
  key: string;
716
806
  }
@@ -82,13 +82,14 @@ export declare function storageReferencesForDownloadUrls(text: string): string;
82
82
  /**
83
83
  * Where {@link resolveStorageReferences} gets URLs from: a function that
84
84
  * answers one, or anything shaped like a Rebase client — its `storage` for the
85
- * default source and `createStorageSource(id)` for a named one.
85
+ * default source and `createStorageSource(id)` for a named one. Only a
86
+ * source's `getSignedUrl` is read.
86
87
  *
87
88
  * @group Models
88
89
  */
89
90
  export type StorageReferenceResolver = ((target: StorageReferenceTarget) => Promise<string | null | undefined>) | {
90
- storage?: StorageSource;
91
- createStorageSource?(storageId: string): StorageSource;
91
+ storage?: Pick<StorageSource, "getSignedUrl">;
92
+ createStorageSource?(storageId: string): Pick<StorageSource, "getSignedUrl">;
92
93
  };
93
94
  /**
94
95
  * Exchange every storage reference in `text` for a URL, at the moment the text
@@ -370,9 +370,10 @@ export declare interface StorageReference {
370
370
  */
371
371
  toString(): string;
372
372
  /**
373
- * A reference to the root of this object's bucket.
373
+ * A reference to the root of this object's bucket, or null where the source
374
+ * does not model one — the built-in local, S3 and GCS sources all leave it null.
374
375
  */
375
- root: StorageReference;
376
+ root: StorageReference | null;
376
377
  /**
377
378
  * The name of the bucket containing this reference's object.
378
379
  */