The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Builds effectful, schema-aware queries for typed browser IndexedDB versions. |
| 3 | * |
| 4 | * An `IndexedDbQueryBuilder` is created from an open database and a version's |
| 5 | * table descriptors, then exposes `from(tableName)` as the entry point for |
| 6 | * table operations. Query objects can select, count, delete, insert, upsert, |
| 7 | * clear tables, stream paged reads, react to invalidations, and run multiple |
| 8 | * effects in a shared `IDBTransaction` with `withTransaction`. Reads decode |
| 9 | * stored rows with the table schema, and writes encode input values before |
| 10 | * sending them to IndexedDB. |
| 11 | * |
| 12 | * @stability unstable |
| 13 | * @since 4.0.0 |
| 14 | */ |
| 15 | import type { NonEmptyReadonlyArray } from "effect/Array" |
| 16 | import * as Cause from "effect/Cause" |
| 17 | import * as Context from "effect/Context" |
| 18 | import * as Data from "effect/Data" |
| 19 | import * as Effect from "effect/Effect" |
| 20 | import * as Effectable from "effect/Effectable" |
| 21 | import * as Fiber from "effect/Fiber" |
| 22 | import type { Inspectable } from "effect/Inspectable" |
| 23 | import { BaseProto } from "effect/Inspectable" |
| 24 | import type * as MutableRef from "effect/MutableRef" |
| 25 | import * as Option from "effect/Option" |
| 26 | import * as Pipeable from "effect/Pipeable" |
| 27 | import type * as Queue from "effect/Queue" |
| 28 | import type * as Reactivity from "effect/reactivity/Reactivity" |
| 29 | import type * as Record from "effect/Record" |
| 30 | import * as References from "effect/References" |
| 31 | import * as Schema from "effect/Schema" |
| 32 | import * as SchemaIssue from "effect/SchemaIssue" |
| 33 | import * as SchemaParser from "effect/SchemaParser" |
| 34 | import type * as Scope from "effect/Scope" |
| 35 | import * as Stream from "effect/Stream" |
| 36 | import * as Utils from "effect/Utils" |
| 37 | import type * as IndexedDb from "./IndexedDb.ts" |
| 38 | import type * as IndexedDbDatabase from "./IndexedDbDatabase.ts" |
| 39 | import type * as IndexedDbTable from "./IndexedDbTable.ts" |
| 40 | import type * as IndexedDbVersion from "./IndexedDbVersion.ts" |
| 41 | |
| 42 | const ErrorTypeId = "~@effect/platform-browser/IndexedDbQueryBuilder/IndexedDbQueryError" |
| 43 | |
| 44 | const CommonProto = { |
| 45 | [Symbol.iterator]() { |
| 46 | return new Utils.SingleShotGen(this) as any |
| 47 | }, |
| 48 | ...Pipeable.Prototype, |
| 49 | ...BaseProto, |
| 50 | toJSON(this: any) { |
| 51 | return { |
| 52 | _id: "IndexedDbQueryBuilder" |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * String union describing IndexedDB query failure categories such as decoding, encoding, and transaction errors. |
| 59 | * |
| 60 | * @stability unstable |
| 61 | * @category errors |
| 62 | * @since 4.0.0 |
| 63 | */ |
| 64 | export type ErrorReason = |
| 65 | | "UnknownError" |
| 66 | | "DecodeError" |
| 67 | | "EncodeError" |
| 68 | | "TransactionError" |
| 69 | |
| 70 | /** |
| 71 | * Tagged error for IndexedDB query operations, carrying a query error reason and the original cause. |
| 72 | * |
| 73 | * **Details** |
| 74 | * |
| 75 | * `reason` is the query failure category, `cause` preserves the underlying |
| 76 | * schema, IndexedDB request, transaction, or user callback failure, and |
| 77 | * `message` is set to the reason. |
| 78 | * |
| 79 | * @see {@link ErrorReason} for the supported failure categories |
| 80 | * |
| 81 | * @stability unstable |
| 82 | * @category errors |
| 83 | * @since 4.0.0 |
| 84 | */ |
| 85 | export class IndexedDbQueryError extends Data.TaggedError( |
| 86 | "IndexedDbQueryError" |
| 87 | )<{ |
| 88 | reason: ErrorReason |
| 89 | cause: unknown |
| 90 | }> { |
| 91 | /** |
| 92 | * Marks this value as an IndexedDB query builder error for runtime guards. |
| 93 | * |
| 94 | * @since 4.0.0 |
| 95 | */ |
| 96 | readonly [ErrorTypeId]: typeof ErrorTypeId = ErrorTypeId |
| 97 | |
| 98 | override readonly message = this.reason |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Typed query builder for an IndexedDB version, with helpers for table queries, database access, clearing data, and running effects in a shared transaction. |
| 103 | * |
| 104 | * @stability unstable |
| 105 | * @category models |
| 106 | * @since 4.0.0 |
| 107 | */ |
| 108 | export interface IndexedDbQueryBuilder< |
| 109 | Source extends IndexedDbVersion.AnyWithProps |
| 110 | > extends Pipeable.Pipeable, Inspectable { |
| 111 | readonly tables: ReadonlyMap<string, IndexedDbVersion.Tables<Source>> |
| 112 | readonly database: MutableRef.MutableRef<globalThis.IDBDatabase> |
| 113 | readonly reactivity: Reactivity.Reactivity |
| 114 | readonly IDBKeyRange: typeof globalThis.IDBKeyRange |
| 115 | readonly IDBTransaction: globalThis.IDBTransaction | undefined |
| 116 | |
| 117 | readonly use: <A = unknown>( |
| 118 | f: (database: globalThis.IDBDatabase) => A |
| 119 | ) => Effect.Effect<A, IndexedDbQueryError> |
| 120 | |
| 121 | readonly from: < |
| 122 | const Name extends IndexedDbTable.TableName< |
| 123 | IndexedDbVersion.Tables<Source> |
| 124 | > |
| 125 | >( |
| 126 | table: Name |
| 127 | ) => IndexedDbQuery.From<IndexedDbVersion.TableWithName<Source, Name>> |
| 128 | |
| 129 | /** @internal */ |
| 130 | readonly fromCache: Map<string, IndexedDbQuery.From<IndexedDbVersion.TableWithName<Source, any>>> |
| 131 | |
| 132 | readonly clearAll: Effect.Effect<void, IndexedDbQueryError> |
| 133 | |
| 134 | readonly withTransaction: < |
| 135 | Tables extends NonEmptyReadonlyArray< |
| 136 | IndexedDbTable.TableName<IndexedDbVersion.Tables<Source>> |
| 137 | >, |
| 138 | Mode extends "readonly" | "readwrite" |
| 139 | >(options: { |
| 140 | readonly tables: Tables |
| 141 | readonly mode: Mode |
| 142 | readonly durability?: IDBTransactionDurability |
| 143 | }) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect< |
| 144 | A, |
| 145 | E | IndexedDbQueryError, |
| 146 | Exclude<R, IndexedDbTransaction> |
| 147 | > |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * Valid key-path type for a table schema, using encoded fields whose values are IndexedDB-valid keys. |
| 152 | * |
| 153 | * @stability unstable |
| 154 | * @category utility types |
| 155 | * @since 4.0.0 |
| 156 | */ |
| 157 | export type KeyPath<TableSchema extends IndexedDbTable.AnySchemaStruct> = |
| 158 | | IndexedDbValidKeys<TableSchema> |
| 159 | | NonEmptyReadonlyArray<IndexedDbValidKeys<TableSchema>> |
| 160 | |
| 161 | /** |
| 162 | * Valid numeric key-path type for a table schema, used for auto-increment key paths. |
| 163 | * |
| 164 | * @stability unstable |
| 165 | * @category utility types |
| 166 | * @since 4.0.0 |
| 167 | */ |
| 168 | export type KeyPathNumber<TableSchema extends IndexedDbTable.AnySchemaStruct> = |
| 169 | | IndexedDbValidNumberKeys<TableSchema> |
| 170 | | NonEmptyReadonlyArray<IndexedDbValidNumberKeys<TableSchema>> |
| 171 | |
| 172 | /** |
| 173 | * Namespace containing the typed IndexedDB query model interfaces and helper types. |
| 174 | * |
| 175 | * @stability unstable |
| 176 | * @since 4.0.0 |
| 177 | */ |
| 178 | export declare namespace IndexedDbQuery { |
| 179 | /** |
| 180 | * Decoded row type returned by select queries, adding a `key` field when the table does not define a key path. |
| 181 | * |
| 182 | * @category utility types |
| 183 | * @since 4.0.0 |
| 184 | */ |
| 185 | export type SelectType< |
| 186 | Table extends IndexedDbTable.AnyWithProps |
| 187 | > = [IndexedDbTable.KeyPath<Table>] extends [undefined] ? IndexedDbTable.TableSchema<Table>["Type"] & { |
| 188 | readonly key: (typeof IndexedDb.IDBValidKey)["Type"] |
| 189 | } : |
| 190 | IndexedDbTable.TableSchema<Table>["Type"] |
| 191 | |
| 192 | /** |
| 193 | * Input type for insert and upsert operations, adjusted for auto-increment keys and out-of-line keys. |
| 194 | * |
| 195 | * @category utility types |
| 196 | * @since 4.0.0 |
| 197 | */ |
| 198 | export type ModifyType< |
| 199 | Table extends IndexedDbTable.AnyWithProps |
| 200 | > = |
| 201 | & (IndexedDbTable.AutoIncrement<Table> extends true ? |
| 202 | & { |
| 203 | [ |
| 204 | key in keyof Schema.Struct.MakeIn< |
| 205 | Omit< |
| 206 | IndexedDbTable.TableSchema<Table>["fields"], |
| 207 | IndexedDbTable.KeyPath<Table> |
| 208 | > |
| 209 | > |
| 210 | ]: key extends keyof Schema.Struct.MakeIn< |
| 211 | IndexedDbTable.TableSchema<Table>["fields"] |
| 212 | > ? Schema.Struct.MakeIn< |
| 213 | IndexedDbTable.TableSchema<Table>["fields"] |
| 214 | >[key] |
| 215 | : never |
| 216 | } |
| 217 | & { |
| 218 | [key in IndexedDbTable.KeyPath<Table>]?: number | undefined |
| 219 | } |
| 220 | : Schema.Struct.MakeIn<IndexedDbTable.TableSchema<Table>["fields"]>) |
| 221 | & ([IndexedDbTable.KeyPath<Table>] extends [undefined] ? { |
| 222 | key: IDBValidKey |
| 223 | } |
| 224 | : {}) |
| 225 | |
| 226 | /** |
| 227 | * Value type accepted by `equals` comparisons for a table key path or index. |
| 228 | * |
| 229 | * @category utility types |
| 230 | * @since 4.0.0 |
| 231 | */ |
| 232 | export type EqualsType< |
| 233 | Table extends IndexedDbTable.AnyWithProps, |
| 234 | Index extends keyof Table["indexes"], |
| 235 | KeyPath = [Index] extends [never] ? Table["keyPath"] : Table["indexes"][Index], |
| 236 | Type = Table["tableSchema"]["Encoded"] |
| 237 | > = [KeyPath] extends [undefined] ? IDBValidKey |
| 238 | : KeyPath extends keyof Type ? Type[KeyPath] |
| 239 | : { [I in keyof KeyPath]: KeyPath[I] extends keyof Type ? Type[KeyPath[I]] | [] : never } |
| 240 | |
| 241 | /** |
| 242 | * Value type accepted by range comparisons for a table key path or index, including partial tuples for compound indexes. |
| 243 | * |
| 244 | * @category utility types |
| 245 | * @since 4.0.0 |
| 246 | */ |
| 247 | export type ExtractIndexType< |
| 248 | Table extends IndexedDbTable.AnyWithProps, |
| 249 | Index extends keyof Table["indexes"], |
| 250 | KeyPath = [Index] extends [never] ? Table["keyPath"] : Table["indexes"][Index], |
| 251 | Type = Table["tableSchema"]["Encoded"] |
| 252 | > = KeyPath extends keyof Type ? Type[KeyPath] |
| 253 | : KeyPath extends readonly [infer K, ...infer Rest] ? K extends keyof Type ? [ |
| 254 | Type[K], |
| 255 | ...{ [P in keyof Rest]?: Rest[P] extends keyof Type ? Type[Rest[P]] | [] : never } |
| 256 | ] : |
| 257 | never : |
| 258 | never |
| 259 | |
| 260 | /** |
| 261 | * Mutation input type for insert and upsert operations, including any required key fields. |
| 262 | * |
| 263 | * @category utility types |
| 264 | * @since 4.0.0 |
| 265 | */ |
| 266 | export type ModifyWithKey<Table extends IndexedDbTable.AnyWithProps> = ModifyType<Table> |
| 267 | |
| 268 | /** |
| 269 | * Query entry point for a table, exposing clear, select, count, delete, insert, and upsert operations. |
| 270 | * |
| 271 | * @category models |
| 272 | * @since 4.0.0 |
| 273 | */ |
| 274 | export interface From<Table extends IndexedDbTable.AnyWithProps> { |
| 275 | readonly table: Table |
| 276 | readonly database: MutableRef.MutableRef<globalThis.IDBDatabase> |
| 277 | readonly IDBKeyRange: typeof globalThis.IDBKeyRange |
| 278 | readonly reactivity: Reactivity.Reactivity |
| 279 | |
| 280 | readonly clear: Effect.Effect<void, IndexedDbQueryError> |
| 281 | |
| 282 | readonly select: { |
| 283 | <Index extends IndexedDbDatabase.IndexFromTable<Table>>( |
| 284 | index: Index |
| 285 | ): Select<Table, Index> |
| 286 | (): Select<Table, never> |
| 287 | } |
| 288 | |
| 289 | /** @internal */ |
| 290 | readonly selectCache: Map< |
| 291 | string | undefined, |
| 292 | IndexedDbQuery.Select<any, never> |
| 293 | > |
| 294 | |
| 295 | readonly count: { |
| 296 | <Index extends IndexedDbDatabase.IndexFromTable<Table>>( |
| 297 | index: Index |
| 298 | ): Count<Table, Index> |
| 299 | (): Count<Table, never> |
| 300 | } |
| 301 | |
| 302 | /** @internal */ |
| 303 | readonly countCache: Map< |
| 304 | string | undefined, |
| 305 | IndexedDbQuery.Count<any, never> |
| 306 | > |
| 307 | |
| 308 | readonly delete: { |
| 309 | <Index extends IndexedDbDatabase.IndexFromTable<Table>>( |
| 310 | index: Index |
| 311 | ): DeletePartial<Table, Index> |
| 312 | (): DeletePartial<Table, never> |
| 313 | } |
| 314 | |
| 315 | /** @internal */ |
| 316 | readonly deleteCache: Map< |
| 317 | string | undefined, |
| 318 | IndexedDbQuery.DeletePartial<any, never> |
| 319 | > |
| 320 | |
| 321 | readonly insert: (value: ModifyWithKey<Table>) => Modify<Table> |
| 322 | readonly insertAll: ( |
| 323 | values: Array<ModifyWithKey<Table>> |
| 324 | ) => ModifyAll<Table> |
| 325 | readonly upsert: (value: ModifyWithKey<Table>) => Modify<Table> |
| 326 | readonly upsertAll: ( |
| 327 | values: Array<ModifyWithKey<Table>> |
| 328 | ) => ModifyAll<Table> |
| 329 | } |
| 330 | |
| 331 | /** |
| 332 | * Effect model for clearing all rows from a table. |
| 333 | * |
| 334 | * @category models |
| 335 | * @since 4.0.0 |
| 336 | */ |
| 337 | export interface Clear< |
| 338 | Table extends IndexedDbTable.AnyWithProps |
| 339 | > extends Effect.Effect<void, IndexedDbQueryError> { |
| 340 | readonly from: From<Table> |
| 341 | } |
| 342 | |
| 343 | type ComparisonKeys = "equals" | "gte" | "lte" | "gt" | "lt" | "between" |
| 344 | |
| 345 | /** |
| 346 | * Effect model for counting table rows, optionally constrained by an index and key-range comparisons. |
| 347 | * |
| 348 | * @category models |
| 349 | * @since 4.0.0 |
| 350 | */ |
| 351 | export interface Count< |
| 352 | Table extends IndexedDbTable.AnyWithProps, |
| 353 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 354 | > extends Effect.Effect<number, IndexedDbQueryError> { |
| 355 | readonly from: From<Table> |
| 356 | readonly index?: Index |
| 357 | readonly only?: ExtractIndexType<Table, Index> |
| 358 | readonly lowerBound?: ExtractIndexType<Table, Index> |
| 359 | readonly upperBound?: ExtractIndexType<Table, Index> |
| 360 | readonly excludeLowerBound?: boolean |
| 361 | readonly excludeUpperBound?: boolean |
| 362 | |
| 363 | readonly equals: ( |
| 364 | value: EqualsType<Table, Index> |
| 365 | ) => Omit<Count<Table, Index>, ComparisonKeys> |
| 366 | |
| 367 | readonly gte: ( |
| 368 | value: ExtractIndexType<Table, Index> |
| 369 | ) => Omit<Count<Table, Index>, ComparisonKeys> |
| 370 | |
| 371 | readonly lte: ( |
| 372 | value: ExtractIndexType<Table, Index> |
| 373 | ) => Omit<Count<Table, Index>, ComparisonKeys> |
| 374 | |
| 375 | readonly gt: ( |
| 376 | value: ExtractIndexType<Table, Index> |
| 377 | ) => Omit<Count<Table, Index>, ComparisonKeys> |
| 378 | |
| 379 | readonly lt: ( |
| 380 | value: ExtractIndexType<Table, Index> |
| 381 | ) => Omit<Count<Table, Index>, ComparisonKeys> |
| 382 | |
| 383 | readonly between: ( |
| 384 | lowerBound: ExtractIndexType<Table, Index>, |
| 385 | upperBound: ExtractIndexType<Table, Index>, |
| 386 | options?: { excludeLowerBound?: boolean; excludeUpperBound?: boolean } |
| 387 | ) => Omit<Count<Table, Index>, ComparisonKeys> |
| 388 | } |
| 389 | |
| 390 | /** |
| 391 | * Intermediate delete builder used to choose a key range or limit before producing an executable delete query. |
| 392 | * |
| 393 | * @category models |
| 394 | * @since 4.0.0 |
| 395 | */ |
| 396 | export interface DeletePartial< |
| 397 | Table extends IndexedDbTable.AnyWithProps, |
| 398 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 399 | > { |
| 400 | readonly from: From<Table> |
| 401 | readonly index?: Index |
| 402 | |
| 403 | readonly equals: ( |
| 404 | value: EqualsType<Table, Index> |
| 405 | ) => Delete<Table, Index> |
| 406 | |
| 407 | readonly gte: ( |
| 408 | value: ExtractIndexType<Table, Index> |
| 409 | ) => Delete<Table, Index> |
| 410 | |
| 411 | readonly lte: ( |
| 412 | value: ExtractIndexType<Table, Index> |
| 413 | ) => Delete<Table, Index> |
| 414 | |
| 415 | readonly gt: ( |
| 416 | value: ExtractIndexType<Table, Index> |
| 417 | ) => Delete<Table, Index> |
| 418 | |
| 419 | readonly lt: ( |
| 420 | value: ExtractIndexType<Table, Index> |
| 421 | ) => Delete<Table, Index> |
| 422 | |
| 423 | readonly between: ( |
| 424 | lowerBound: ExtractIndexType<Table, Index>, |
| 425 | upperBound: ExtractIndexType<Table, Index>, |
| 426 | options?: { excludeLowerBound?: boolean; excludeUpperBound?: boolean } |
| 427 | ) => Delete<Table, Index> |
| 428 | |
| 429 | readonly limit: ( |
| 430 | limit: number |
| 431 | ) => DeleteWithout<Table, Index, "limit"> |
| 432 | } |
| 433 | |
| 434 | type DeleteWithout< |
| 435 | Table extends IndexedDbTable.AnyWithProps, |
| 436 | Index extends IndexedDbDatabase.IndexFromTable<Table>, |
| 437 | ExcludedKeys extends string |
| 438 | > = Omit<Delete<Table, Index, ExcludedKeys>, ExcludedKeys> |
| 439 | |
| 440 | /** |
| 441 | * Effect model for deleting rows from a table, with optional key-range, limit, filter, and reactivity invalidation helpers. |
| 442 | * |
| 443 | * @category models |
| 444 | * @since 4.0.0 |
| 445 | */ |
| 446 | export interface Delete< |
| 447 | Table extends IndexedDbTable.AnyWithProps, |
| 448 | Index extends IndexedDbDatabase.IndexFromTable<Table>, |
| 449 | ExcludedKeys extends string = never |
| 450 | > extends Effect.Effect<void, IndexedDbQueryError> { |
| 451 | readonly delete: DeletePartial<Table, Index> |
| 452 | readonly index?: Index |
| 453 | readonly limitValue?: number |
| 454 | readonly only?: ExtractIndexType<Table, Index> |
| 455 | readonly lowerBound?: ExtractIndexType<Table, Index> |
| 456 | readonly upperBound?: ExtractIndexType<Table, Index> |
| 457 | readonly excludeLowerBound?: boolean |
| 458 | readonly excludeUpperBound?: boolean |
| 459 | readonly predicate?: (item: IndexedDbTable.Encoded<Table>) => boolean |
| 460 | |
| 461 | readonly limit: ( |
| 462 | limit: number |
| 463 | ) => DeleteWithout<Table, Index, ExcludedKeys | "limit"> |
| 464 | |
| 465 | readonly filter: ( |
| 466 | f: (value: IndexedDbTable.Encoded<Table>) => boolean |
| 467 | ) => DeleteWithout<Table, Index, ExcludedKeys> |
| 468 | |
| 469 | /** |
| 470 | * Invalidate any queries using Reactivity service with the provided keys. |
| 471 | * |
| 472 | * **Details** |
| 473 | * |
| 474 | * If no keys are provided, the table name is used as the reactivity key. |
| 475 | */ |
| 476 | readonly invalidate: ( |
| 477 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 478 | ) => Effect.Effect<void, IndexedDbQueryError, IndexedDbTable.Context<Table>> |
| 479 | } |
| 480 | |
| 481 | type SelectWithout< |
| 482 | Table extends IndexedDbTable.AnyWithProps, |
| 483 | Index extends IndexedDbDatabase.IndexFromTable<Table>, |
| 484 | ExcludedKeys extends string |
| 485 | > = Omit<Select<Table, Index, ExcludedKeys>, ExcludedKeys> |
| 486 | |
| 487 | /** |
| 488 | * Effect model for selecting rows from a table, with chainable range, paging, filtering, streaming, and reactive query helpers. |
| 489 | * |
| 490 | * @category models |
| 491 | * @since 4.0.0 |
| 492 | */ |
| 493 | export interface Select< |
| 494 | Table extends IndexedDbTable.AnyWithProps, |
| 495 | Index extends IndexedDbDatabase.IndexFromTable<Table>, |
| 496 | ExcludedKeys extends string = never |
| 497 | > extends |
| 498 | Effect.Effect< |
| 499 | Array<SelectType<Table>>, |
| 500 | IndexedDbQueryError, |
| 501 | IndexedDbTable.Context<Table> |
| 502 | > |
| 503 | { |
| 504 | readonly from: From<Table> |
| 505 | readonly index?: Index |
| 506 | readonly limitValue?: number |
| 507 | readonly offsetValue?: number |
| 508 | readonly reverseValue?: boolean |
| 509 | readonly only?: ExtractIndexType<Table, Index> |
| 510 | readonly lowerBound?: ExtractIndexType<Table, Index> |
| 511 | readonly upperBound?: ExtractIndexType<Table, Index> |
| 512 | readonly excludeLowerBound?: boolean |
| 513 | readonly excludeUpperBound?: boolean |
| 514 | readonly predicate?: (item: IndexedDbTable.Encoded<Table>) => boolean |
| 515 | |
| 516 | readonly equals: ( |
| 517 | value: EqualsType<Table, Index> |
| 518 | ) => SelectWithout<Table, Index, ExcludedKeys | ComparisonKeys> |
| 519 | |
| 520 | readonly gte: ( |
| 521 | value: ExtractIndexType<Table, Index> |
| 522 | ) => SelectWithout<Table, Index, ExcludedKeys | ComparisonKeys> |
| 523 | |
| 524 | readonly lte: ( |
| 525 | value: ExtractIndexType<Table, Index> |
| 526 | ) => SelectWithout<Table, Index, ExcludedKeys | ComparisonKeys> |
| 527 | |
| 528 | readonly gt: ( |
| 529 | value: ExtractIndexType<Table, Index> |
| 530 | ) => SelectWithout<Table, Index, ExcludedKeys | ComparisonKeys> |
| 531 | |
| 532 | readonly lt: ( |
| 533 | value: ExtractIndexType<Table, Index> |
| 534 | ) => SelectWithout<Table, Index, ExcludedKeys | ComparisonKeys> |
| 535 | |
| 536 | readonly between: ( |
| 537 | lowerBound: ExtractIndexType<Table, Index>, |
| 538 | upperBound: ExtractIndexType<Table, Index>, |
| 539 | options?: { excludeLowerBound?: boolean; excludeUpperBound?: boolean } |
| 540 | ) => SelectWithout<Table, Index, ExcludedKeys | ComparisonKeys> |
| 541 | |
| 542 | readonly limit: ( |
| 543 | limit: number |
| 544 | ) => SelectWithout<Table, Index, ExcludedKeys | "limit" | "first"> |
| 545 | |
| 546 | readonly offset: ( |
| 547 | offset: number |
| 548 | ) => SelectWithout<Table, Index, ExcludedKeys | "offset" | "first"> |
| 549 | |
| 550 | readonly reverse: () => SelectWithout<Table, Index, ExcludedKeys | "reverse" | "first"> |
| 551 | |
| 552 | readonly filter: ( |
| 553 | f: (value: IndexedDbTable.Encoded<Table>) => boolean |
| 554 | ) => SelectWithout<Table, Index, ExcludedKeys | "first"> |
| 555 | |
| 556 | readonly first: () => First<Table, Index> |
| 557 | |
| 558 | /** |
| 559 | * Stream the selected data. |
| 560 | * |
| 561 | * **Details** |
| 562 | * |
| 563 | * The default chunk size is 100. |
| 564 | */ |
| 565 | readonly stream: (options?: { |
| 566 | readonly chunkSize?: number | undefined |
| 567 | }) => Stream.Stream< |
| 568 | SelectType<Table>, |
| 569 | IndexedDbQueryError, |
| 570 | IndexedDbTable.Context<Table> |
| 571 | > |
| 572 | |
| 573 | /** |
| 574 | * Use the Reactivity service to react to changes to the selected data. |
| 575 | * |
| 576 | * **Details** |
| 577 | * |
| 578 | * By default, the table name is used as the reactivity key. |
| 579 | */ |
| 580 | readonly reactive: ( |
| 581 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 582 | ) => Stream.Stream< |
| 583 | Array<SelectType<Table>>, |
| 584 | IndexedDbQueryError, |
| 585 | IndexedDbTable.Context<Table> |
| 586 | > |
| 587 | readonly reactiveQueue: ( |
| 588 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 589 | ) => Effect.Effect< |
| 590 | Queue.Dequeue<Array<SelectType<Table>>, IndexedDbQueryError>, |
| 591 | never, |
| 592 | Scope.Scope | IndexedDbTable.Context<Table> |
| 593 | > |
| 594 | } |
| 595 | |
| 596 | /** |
| 597 | * Effect model for selecting the first matching row, failing with `NoSuchElementError` when no row is found. |
| 598 | * |
| 599 | * @category models |
| 600 | * @since 4.0.0 |
| 601 | */ |
| 602 | export interface First< |
| 603 | Table extends IndexedDbTable.AnyWithProps, |
| 604 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 605 | > extends |
| 606 | Effect.Effect< |
| 607 | SelectType<Table>, |
| 608 | IndexedDbQueryError | Cause.NoSuchElementError, |
| 609 | IndexedDbTable.Context<Table> |
| 610 | > |
| 611 | { |
| 612 | readonly select: Select<Table, Index> |
| 613 | |
| 614 | /** |
| 615 | * Use the Reactivity service to react to changes to the selected data. |
| 616 | * |
| 617 | * **Details** |
| 618 | * |
| 619 | * By default, the table name is used as the reactivity key. |
| 620 | */ |
| 621 | readonly reactive: ( |
| 622 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 623 | ) => Stream.Stream< |
| 624 | SelectType<Table>, |
| 625 | IndexedDbQueryError | Cause.NoSuchElementError, |
| 626 | IndexedDbTable.Context<Table> |
| 627 | > |
| 628 | |
| 629 | /** |
| 630 | * Use the Reactivity service to react to changes to the selected data. |
| 631 | * |
| 632 | * **Details** |
| 633 | * |
| 634 | * By default, the table name is used as the reactivity key. |
| 635 | */ |
| 636 | readonly reactiveQueue: ( |
| 637 | keys: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> |
| 638 | ) => Effect.Effect< |
| 639 | Queue.Dequeue<SelectType<Table>, IndexedDbQueryError | Cause.NoSuchElementError>, |
| 640 | never, |
| 641 | Scope.Scope | IndexedDbTable.Context<Table> |
| 642 | > |
| 643 | } |
| 644 | |
| 645 | /** |
| 646 | * Effect model for a select query filtered by one or more predicates over encoded table rows. |
| 647 | * |
| 648 | * @category models |
| 649 | * @since 4.0.0 |
| 650 | */ |
| 651 | export interface Filter< |
| 652 | Table extends IndexedDbTable.AnyWithProps, |
| 653 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 654 | > extends |
| 655 | Effect.Effect< |
| 656 | Array<SelectType<Table>>, |
| 657 | IndexedDbQueryError, |
| 658 | IndexedDbTable.Context<Table> |
| 659 | > |
| 660 | { |
| 661 | readonly select: Select<Table, Index> |
| 662 | readonly predicate: (item: IndexedDbTable.Encoded<Table>) => boolean |
| 663 | readonly filter: ( |
| 664 | f: (value: IndexedDbTable.Encoded<Table>) => boolean |
| 665 | ) => Filter<Table, Index> |
| 666 | } |
| 667 | |
| 668 | /** |
| 669 | * Effect model for inserting or upserting one row, returning the resulting IndexedDB key and supporting reactivity invalidation. |
| 670 | * |
| 671 | * @category models |
| 672 | * @since 4.0.0 |
| 673 | */ |
| 674 | export interface Modify< |
| 675 | Table extends IndexedDbTable.AnyWithProps |
| 676 | > extends |
| 677 | Effect.Effect< |
| 678 | globalThis.IDBValidKey, |
| 679 | IndexedDbQueryError, |
| 680 | IndexedDbTable.Context<Table> |
| 681 | > |
| 682 | { |
| 683 | readonly operation: "add" | "put" |
| 684 | readonly from: From<Table> |
| 685 | readonly value: ModifyWithKey<Table> |
| 686 | |
| 687 | /** |
| 688 | * Invalidate any queries using Reactivity service with the provided keys. |
| 689 | * |
| 690 | * **Details** |
| 691 | * |
| 692 | * If no keys are provided, the table name is used as the reactivity key. |
| 693 | */ |
| 694 | readonly invalidate: ( |
| 695 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 696 | ) => Effect.Effect<globalThis.IDBValidKey, IndexedDbQueryError, IndexedDbTable.Context<Table>> |
| 697 | } |
| 698 | |
| 699 | /** |
| 700 | * Effect model for inserting or upserting multiple rows, returning the resulting IndexedDB keys and supporting reactivity invalidation. |
| 701 | * |
| 702 | * @category models |
| 703 | * @since 4.0.0 |
| 704 | */ |
| 705 | export interface ModifyAll< |
| 706 | Table extends IndexedDbTable.AnyWithProps |
| 707 | > extends |
| 708 | Effect.Effect< |
| 709 | Array<globalThis.IDBValidKey>, |
| 710 | IndexedDbQueryError, |
| 711 | IndexedDbTable.Context<Table> |
| 712 | > |
| 713 | { |
| 714 | readonly operation: "add" | "put" |
| 715 | readonly from: From<Table> |
| 716 | readonly values: Array<ModifyWithKey<Table>> |
| 717 | |
| 718 | /** |
| 719 | * Invalidate any queries using Reactivity service with the provided keys. |
| 720 | * |
| 721 | * **Details** |
| 722 | * |
| 723 | * If no keys are provided, the table name is used as the reactivity key. |
| 724 | */ |
| 725 | readonly invalidate: ( |
| 726 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 727 | ) => Effect.Effect<globalThis.IDBValidKey, IndexedDbQueryError, IndexedDbTable.Context<Table>> |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | /** |
| 732 | * Service tag for the active `IDBTransaction` used to share a transaction across IndexedDB query effects. |
| 733 | * |
| 734 | * @stability unstable |
| 735 | * @category services |
| 736 | * @since 4.0.0 |
| 737 | */ |
| 738 | export class IndexedDbTransaction extends Context.Service<IndexedDbTransaction, globalThis.IDBTransaction>()( |
| 739 | "@effect/platform-browser/IndexedDbQueryBuilder/IndexedDbTransaction" |
| 740 | ) {} |
| 741 | |
| 742 | // ----------------------------------------------------------------------------- |
| 743 | // internal |
| 744 | // ----------------------------------------------------------------------------- |
| 745 | |
| 746 | type IndexedDbValidKeys<TableSchema extends IndexedDbTable.AnySchemaStruct> = keyof TableSchema["Encoded"] extends |
| 747 | infer K ? K extends keyof TableSchema["Encoded"] ? TableSchema["Encoded"][K] extends Readonly<IDBValidKey> ? K |
| 748 | : never |
| 749 | : never |
| 750 | : never |
| 751 | |
| 752 | type IndexedDbValidNumberKeys< |
| 753 | TableSchema extends IndexedDbTable.AnySchemaStruct |
| 754 | > = keyof TableSchema["Encoded"] extends infer K |
| 755 | ? K extends keyof TableSchema["Encoded"] ? [TableSchema["Encoded"][K]] extends [number | undefined] ? K |
| 756 | : never |
| 757 | : never |
| 758 | : never |
| 759 | |
| 760 | const applyDelete = (query: IndexedDbQuery.Delete<any, never>) => |
| 761 | Effect.callback<any, IndexedDbQueryError>((resume) => { |
| 762 | const database = query.delete.from.database |
| 763 | const IDBKeyRange = query.delete.from.IDBKeyRange |
| 764 | const transaction = getOrCreateTransaction(database.current, [query.delete.from.table.tableName], "readwrite", { |
| 765 | durability: query.delete.from.table.durability |
| 766 | }) |
| 767 | const objectStore = transaction.objectStore(query.delete.from.table.tableName) |
| 768 | const store = query.delete.index === undefined ? objectStore : objectStore.index(query.delete.index) |
| 769 | const predicate = query.predicate |
| 770 | |
| 771 | let keyRange: globalThis.IDBKeyRange | undefined = undefined |
| 772 | |
| 773 | if (query.only !== undefined) { |
| 774 | keyRange = IDBKeyRange.only(query.only) |
| 775 | } else if ( |
| 776 | query.lowerBound !== undefined && |
| 777 | query.upperBound !== undefined |
| 778 | ) { |
| 779 | keyRange = IDBKeyRange.bound( |
| 780 | query.lowerBound, |
| 781 | query.upperBound, |
| 782 | query.excludeLowerBound, |
| 783 | query.excludeUpperBound |
| 784 | ) |
| 785 | } else if (query.lowerBound !== undefined) { |
| 786 | keyRange = IDBKeyRange.lowerBound( |
| 787 | query.lowerBound, |
| 788 | query.excludeLowerBound |
| 789 | ) |
| 790 | } else if (query.upperBound !== undefined) { |
| 791 | keyRange = IDBKeyRange.upperBound( |
| 792 | query.upperBound, |
| 793 | query.excludeUpperBound |
| 794 | ) |
| 795 | } |
| 796 | |
| 797 | let request: globalThis.IDBRequest |
| 798 | |
| 799 | if (query.delete.index !== undefined || query.limitValue !== undefined || predicate) { |
| 800 | const cursorRequest = store.openCursor(keyRange) |
| 801 | let count = 0 |
| 802 | |
| 803 | cursorRequest.onerror = () => { |
| 804 | resume( |
| 805 | Effect.fail( |
| 806 | new IndexedDbQueryError({ |
| 807 | reason: "TransactionError", |
| 808 | cause: cursorRequest.error |
| 809 | }) |
| 810 | ) |
| 811 | ) |
| 812 | } |
| 813 | |
| 814 | cursorRequest.onsuccess = () => { |
| 815 | const cursor = cursorRequest.result |
| 816 | if (cursor === null) { |
| 817 | return resume(Effect.void) |
| 818 | } |
| 819 | |
| 820 | if (predicate === undefined || predicate(cursor.value)) { |
| 821 | const deleteRequest = cursor.delete() |
| 822 | deleteRequest.onerror = () => { |
| 823 | resume( |
| 824 | Effect.fail( |
| 825 | new IndexedDbQueryError({ |
| 826 | reason: "TransactionError", |
| 827 | cause: deleteRequest.error |
| 828 | }) |
| 829 | ) |
| 830 | ) |
| 831 | } |
| 832 | count += 1 |
| 833 | } |
| 834 | |
| 835 | if (query.limitValue === undefined || count < query.limitValue) { |
| 836 | return cursor.continue() |
| 837 | } |
| 838 | |
| 839 | resume(Effect.void) |
| 840 | } |
| 841 | } else if (keyRange !== undefined) { |
| 842 | request = objectStore.delete(keyRange) |
| 843 | |
| 844 | request.onerror = (event) => { |
| 845 | resume( |
| 846 | Effect.fail( |
| 847 | new IndexedDbQueryError({ |
| 848 | reason: "TransactionError", |
| 849 | cause: event |
| 850 | }) |
| 851 | ) |
| 852 | ) |
| 853 | } |
| 854 | |
| 855 | request.onsuccess = () => { |
| 856 | resume(Effect.succeed(request.result)) |
| 857 | } |
| 858 | } else { |
| 859 | resume( |
| 860 | Effect.die(new Error("No key range provided for delete operation")) |
| 861 | ) |
| 862 | } |
| 863 | }) |
| 864 | |
| 865 | const getReadonlyObjectStore = ( |
| 866 | query: IndexedDbQuery.Select<any, never> | IndexedDbQuery.Count<any, never> |
| 867 | ) => { |
| 868 | const database = query.from.database |
| 869 | const IDBKeyRange = query.from.IDBKeyRange |
| 870 | const transaction = getOrCreateTransaction(database.current, [query.from.table.tableName], "readonly", { |
| 871 | durability: query.from.table.durability |
| 872 | }) |
| 873 | const objectStore = transaction.objectStore(query.from.table.tableName) |
| 874 | |
| 875 | let keyRange: globalThis.IDBKeyRange | undefined = undefined |
| 876 | let store: globalThis.IDBObjectStore | globalThis.IDBIndex |
| 877 | |
| 878 | if (query.only !== undefined) { |
| 879 | keyRange = IDBKeyRange.only(query.only) |
| 880 | } else if (query.lowerBound !== undefined && query.upperBound !== undefined) { |
| 881 | keyRange = IDBKeyRange.bound( |
| 882 | query.lowerBound, |
| 883 | query.upperBound, |
| 884 | query.excludeLowerBound, |
| 885 | query.excludeUpperBound |
| 886 | ) |
| 887 | } else if (query.lowerBound !== undefined) { |
| 888 | keyRange = IDBKeyRange.lowerBound( |
| 889 | query.lowerBound, |
| 890 | query.excludeLowerBound |
| 891 | ) |
| 892 | } else if (query.upperBound !== undefined) { |
| 893 | keyRange = IDBKeyRange.upperBound( |
| 894 | query.upperBound, |
| 895 | query.excludeUpperBound |
| 896 | ) |
| 897 | } |
| 898 | |
| 899 | if (query.index !== undefined) { |
| 900 | store = objectStore.index(query.index) |
| 901 | } else { |
| 902 | store = objectStore |
| 903 | } |
| 904 | |
| 905 | return { store, keyRange } |
| 906 | } |
| 907 | |
| 908 | const applySelect = Effect.fnUntraced(function*( |
| 909 | query: IndexedDbQuery.Select<any, never, any> |
| 910 | ): Effect.fn.Return<Array<any>, IndexedDbQueryError, unknown> { |
| 911 | const keyPath = query.from.table.keyPath |
| 912 | const predicate = query.predicate |
| 913 | |
| 914 | const data = predicate || keyPath === undefined || query.offsetValue !== undefined || query.reverseValue ? |
| 915 | yield* Effect.callback<Array<any>, IndexedDbQueryError>((resume) => { |
| 916 | const { keyRange, store } = getReadonlyObjectStore(query) |
| 917 | |
| 918 | const cursorRequest = store.openCursor(keyRange, query.reverseValue ? "prev" : "next") |
| 919 | const results: Array<any> = [] |
| 920 | let count = 0 |
| 921 | let offsetApplied = false |
| 922 | |
| 923 | cursorRequest.onerror = () => { |
| 924 | resume( |
| 925 | Effect.fail( |
| 926 | new IndexedDbQueryError({ |
| 927 | reason: "TransactionError", |
| 928 | cause: cursorRequest.error |
| 929 | }) |
| 930 | ) |
| 931 | ) |
| 932 | } |
| 933 | |
| 934 | cursorRequest.onsuccess = () => { |
| 935 | const cursor = cursorRequest.result |
| 936 | if (cursor === null) { |
| 937 | return resume(Effect.succeed(results)) |
| 938 | } |
| 939 | |
| 940 | if (query.offsetValue && !offsetApplied) { |
| 941 | offsetApplied = true |
| 942 | return cursor.advance(query.offsetValue) |
| 943 | } |
| 944 | |
| 945 | if (predicate === undefined || predicate(cursor.value)) { |
| 946 | results.push( |
| 947 | keyPath === undefined |
| 948 | ? { ...cursor.value, key: cursor.primaryKey } |
| 949 | : cursor.value |
| 950 | ) |
| 951 | count += 1 |
| 952 | } |
| 953 | |
| 954 | if (query.limitValue === undefined || count < query.limitValue) { |
| 955 | return cursor.continue() |
| 956 | } |
| 957 | |
| 958 | resume(Effect.succeed(results)) |
| 959 | } |
| 960 | }) : |
| 961 | yield* Effect.callback<Array<any>, IndexedDbQueryError>((resume) => { |
| 962 | const { keyRange, store } = getReadonlyObjectStore(query) |
| 963 | const request = store.getAll(keyRange, query.limitValue) |
| 964 | request.onerror = (event) => { |
| 965 | resume( |
| 966 | Effect.fail( |
| 967 | new IndexedDbQueryError({ |
| 968 | reason: "TransactionError", |
| 969 | cause: event |
| 970 | }) |
| 971 | ) |
| 972 | ) |
| 973 | } |
| 974 | request.onsuccess = () => { |
| 975 | if (query.reverseValue) { |
| 976 | request.result.reverse() |
| 977 | } |
| 978 | resume(Effect.succeed(request.result)) |
| 979 | } |
| 980 | }) |
| 981 | |
| 982 | const tableSchema = (query.from.table as IndexedDbTable.AnyWithProps).arraySchema |
| 983 | |
| 984 | return yield* Schema.decodeUnknownEffect(tableSchema)(data).pipe( |
| 985 | Effect.mapError( |
| 986 | (error) => |
| 987 | new IndexedDbQueryError({ |
| 988 | reason: "DecodeError", |
| 989 | cause: error |
| 990 | }) |
| 991 | ) |
| 992 | ) as Effect.Effect<Array<any>, IndexedDbQueryError, unknown> |
| 993 | }) |
| 994 | |
| 995 | const applyFirst = Effect.fnUntraced(function*( |
| 996 | query: IndexedDbQuery.First<any, never> |
| 997 | ) { |
| 998 | const keyPath = query.select.from.table.keyPath |
| 999 | |
| 1000 | const data = yield* Effect.callback<any, IndexedDbQueryError | Cause.NoSuchElementError>((resume) => { |
| 1001 | const { keyRange, store } = getReadonlyObjectStore(query.select) |
| 1002 | |
| 1003 | if (keyRange !== undefined && keyPath !== undefined) { |
| 1004 | const request = store.get(keyRange) |
| 1005 | |
| 1006 | request.onerror = (event) => { |
| 1007 | resume( |
| 1008 | Effect.fail( |
| 1009 | new IndexedDbQueryError({ |
| 1010 | reason: "TransactionError", |
| 1011 | cause: event |
| 1012 | }) |
| 1013 | ) |
| 1014 | ) |
| 1015 | } |
| 1016 | |
| 1017 | request.onsuccess = () => { |
| 1018 | if (request.result === undefined) { |
| 1019 | resume( |
| 1020 | Effect.fail(new Cause.NoSuchElementError(`No such element in table ${query.select.from.table.tableName}`)) |
| 1021 | ) |
| 1022 | } else { |
| 1023 | resume(Effect.succeed(request.result)) |
| 1024 | } |
| 1025 | } |
| 1026 | } else { |
| 1027 | const request = store.openCursor(keyRange) |
| 1028 | |
| 1029 | request.onerror = (event) => { |
| 1030 | resume( |
| 1031 | Effect.fail( |
| 1032 | new IndexedDbQueryError({ |
| 1033 | reason: "TransactionError", |
| 1034 | cause: event |
| 1035 | }) |
| 1036 | ) |
| 1037 | ) |
| 1038 | } |
| 1039 | |
| 1040 | request.onsuccess = () => { |
| 1041 | const value = request.result?.value |
| 1042 | const key = request.result?.primaryKey |
| 1043 | |
| 1044 | if (value === undefined) { |
| 1045 | resume( |
| 1046 | Effect.fail(new Cause.NoSuchElementError(`No such element in table ${query.select.from.table.tableName}`)) |
| 1047 | ) |
| 1048 | } else { |
| 1049 | resume( |
| 1050 | Effect.succeed(keyPath === undefined ? { ...value, key } : value) |
| 1051 | ) |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | }) |
| 1056 | |
| 1057 | return yield* Schema.decodeUnknownEffect(query.select.from.table.readSchema)( |
| 1058 | data |
| 1059 | ).pipe( |
| 1060 | Effect.mapError( |
| 1061 | (error) => |
| 1062 | new IndexedDbQueryError({ |
| 1063 | reason: "DecodeError", |
| 1064 | cause: error |
| 1065 | }) |
| 1066 | ) |
| 1067 | ) |
| 1068 | }) |
| 1069 | |
| 1070 | const applyModify = Effect.fnUntraced(function*({ |
| 1071 | query, |
| 1072 | value |
| 1073 | }: { |
| 1074 | query: IndexedDbQuery.Modify<any> |
| 1075 | value: any |
| 1076 | }) { |
| 1077 | const autoIncrement = query.from.table.autoIncrement as boolean |
| 1078 | const keyPath = query.from.table.keyPath |
| 1079 | const table = query.from.table |
| 1080 | const schema: Schema.Top = autoIncrement && value[keyPath] === undefined |
| 1081 | ? table.autoincrementSchema |
| 1082 | : table.tableSchema |
| 1083 | |
| 1084 | const encodedValue = yield* schema.makeEffect(value).pipe( |
| 1085 | Effect.flatMap(Schema.encodeUnknownEffect(schema)), |
| 1086 | Effect.mapError( |
| 1087 | (error) => |
| 1088 | new IndexedDbQueryError({ |
| 1089 | reason: "EncodeError", |
| 1090 | cause: error |
| 1091 | }) |
| 1092 | ) |
| 1093 | ) |
| 1094 | |
| 1095 | return yield* Effect.callback<any, IndexedDbQueryError>((resume) => { |
| 1096 | const database = query.from.database |
| 1097 | const transaction = getOrCreateTransaction(database.current, [query.from.table.tableName], "readwrite", { |
| 1098 | durability: query.from.table.durability |
| 1099 | }) |
| 1100 | const objectStore = transaction.objectStore(query.from.table.tableName) |
| 1101 | |
| 1102 | let request: globalThis.IDBRequest<IDBValidKey> |
| 1103 | |
| 1104 | if (query.operation === "add") { |
| 1105 | request = objectStore.add( |
| 1106 | encodedValue, |
| 1107 | keyPath === undefined ? value["key"] : undefined |
| 1108 | ) |
| 1109 | } else if (query.operation === "put") { |
| 1110 | request = objectStore.put( |
| 1111 | encodedValue, |
| 1112 | keyPath === undefined ? value["key"] : undefined |
| 1113 | ) |
| 1114 | } else { |
| 1115 | return resume(Effect.die(new Error("Invalid modify operation"))) |
| 1116 | } |
| 1117 | |
| 1118 | request.onerror = (event) => { |
| 1119 | resume( |
| 1120 | Effect.fail( |
| 1121 | new IndexedDbQueryError({ |
| 1122 | reason: "TransactionError", |
| 1123 | cause: event |
| 1124 | }) |
| 1125 | ) |
| 1126 | ) |
| 1127 | } |
| 1128 | |
| 1129 | request.onsuccess = () => { |
| 1130 | resume(Effect.succeed(request.result)) |
| 1131 | } |
| 1132 | }) |
| 1133 | }) |
| 1134 | |
| 1135 | const applyModifyAll = Effect.fnUntraced( |
| 1136 | function*({ |
| 1137 | query, |
| 1138 | values |
| 1139 | }: { |
| 1140 | query: IndexedDbQuery.ModifyAll<any> |
| 1141 | values: Array<any> |
| 1142 | }) { |
| 1143 | const autoIncrement = query.from.table.autoIncrement as boolean |
| 1144 | const keyPath = query.from.table.keyPath |
| 1145 | const schema = query.from.table.tableSchema |
| 1146 | const encodedValues = new Array(values.length) |
| 1147 | const makeValue = SchemaParser.makeEffect(schema) |
| 1148 | const encodeValue = SchemaParser.encodeUnknownEffect(schema) |
| 1149 | const makeValueAutoincrement = SchemaParser.makeEffect(query.from.table.autoincrementSchema) |
| 1150 | const encodeValueAutoincrement = SchemaParser.encodeUnknownEffect(query.from.table.autoincrementSchema) |
| 1151 | |
| 1152 | for (let i = 0; i < values.length; i++) { |
| 1153 | const value = values[i] |
| 1154 | if (autoIncrement && value[keyPath] === undefined) { |
| 1155 | encodedValues[i] = yield* encodeValueAutoincrement(yield* makeValueAutoincrement(value)) |
| 1156 | } else { |
| 1157 | encodedValues[i] = yield* encodeValue(yield* makeValue(value)) |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | return yield* Effect.callback< |
| 1162 | Array<globalThis.IDBValidKey>, |
| 1163 | IndexedDbQueryError |
| 1164 | >((resume) => { |
| 1165 | if (encodedValues.length === 0) { |
| 1166 | return resume(Effect.succeed([])) |
| 1167 | } |
| 1168 | |
| 1169 | const database = query.from.database |
| 1170 | const transaction = getOrCreateTransaction(database.current, [query.from.table.tableName], "readwrite", { |
| 1171 | durability: query.from.table.durability |
| 1172 | }) |
| 1173 | const objectStore = transaction.objectStore(query.from.table.tableName) |
| 1174 | |
| 1175 | const results: Array<globalThis.IDBValidKey> = new Array(encodedValues.length) |
| 1176 | let remaining = encodedValues.length |
| 1177 | |
| 1178 | if (query.operation === "add") { |
| 1179 | for (let i = 0; i < encodedValues.length; i++) { |
| 1180 | const request = objectStore.add( |
| 1181 | encodedValues[i], |
| 1182 | keyPath === undefined ? values[i]["key"] : undefined |
| 1183 | ) |
| 1184 | |
| 1185 | request.onerror = () => { |
| 1186 | resume( |
| 1187 | Effect.fail( |
| 1188 | new IndexedDbQueryError({ |
| 1189 | reason: "TransactionError", |
| 1190 | cause: request.error |
| 1191 | }) |
| 1192 | ) |
| 1193 | ) |
| 1194 | } |
| 1195 | |
| 1196 | request.onsuccess = () => { |
| 1197 | results[i] = request.result |
| 1198 | remaining -= 1 |
| 1199 | if (remaining === 0) { |
| 1200 | resume(Effect.succeed(results)) |
| 1201 | } |
| 1202 | } |
| 1203 | } |
| 1204 | } else if (query.operation === "put") { |
| 1205 | for (let i = 0; i < encodedValues.length; i++) { |
| 1206 | const request = objectStore.put( |
| 1207 | encodedValues[i], |
| 1208 | keyPath === undefined ? values[i]["key"] : undefined |
| 1209 | ) |
| 1210 | |
| 1211 | request.onerror = () => { |
| 1212 | resume( |
| 1213 | Effect.fail( |
| 1214 | new IndexedDbQueryError({ |
| 1215 | reason: "TransactionError", |
| 1216 | cause: request.error |
| 1217 | }) |
| 1218 | ) |
| 1219 | ) |
| 1220 | } |
| 1221 | |
| 1222 | request.onsuccess = () => { |
| 1223 | results[i] = request.result |
| 1224 | remaining -= 1 |
| 1225 | if (remaining === 0) { |
| 1226 | resume(Effect.succeed(results)) |
| 1227 | } |
| 1228 | } |
| 1229 | } |
| 1230 | } else { |
| 1231 | return resume(Effect.die(new Error("Invalid modify all operation"))) |
| 1232 | } |
| 1233 | |
| 1234 | objectStore.transaction.onerror = () => { |
| 1235 | resume( |
| 1236 | Effect.fail( |
| 1237 | new IndexedDbQueryError({ |
| 1238 | reason: "TransactionError", |
| 1239 | cause: objectStore.transaction.error |
| 1240 | }) |
| 1241 | ) |
| 1242 | ) |
| 1243 | } |
| 1244 | }) |
| 1245 | }, |
| 1246 | Effect.catchIf( |
| 1247 | SchemaIssue.isIssue, |
| 1248 | (issue) => Effect.fail(new IndexedDbQueryError({ reason: "EncodeError", cause: new Schema.SchemaError(issue) })) |
| 1249 | ) |
| 1250 | ) |
| 1251 | |
| 1252 | const applyClear = (options: { |
| 1253 | readonly database: globalThis.IDBDatabase |
| 1254 | readonly table: IndexedDbTable.AnyWithProps |
| 1255 | }) => |
| 1256 | Effect.callback<void, IndexedDbQueryError>((resume) => { |
| 1257 | const database = options.database |
| 1258 | const transaction = getOrCreateTransaction(database, [options.table.tableName], "readwrite", { |
| 1259 | durability: options.table.durability |
| 1260 | }) |
| 1261 | const objectStore = transaction.objectStore(options.table.tableName) |
| 1262 | |
| 1263 | const request = objectStore.clear() |
| 1264 | |
| 1265 | request.onerror = (event) => { |
| 1266 | resume( |
| 1267 | Effect.fail( |
| 1268 | new IndexedDbQueryError({ |
| 1269 | reason: "TransactionError", |
| 1270 | cause: event |
| 1271 | }) |
| 1272 | ) |
| 1273 | ) |
| 1274 | } |
| 1275 | |
| 1276 | request.onsuccess = () => { |
| 1277 | resume(Effect.void) |
| 1278 | } |
| 1279 | }) |
| 1280 | |
| 1281 | const applyClearAll = (options: { |
| 1282 | readonly database: globalThis.IDBDatabase |
| 1283 | }) => |
| 1284 | Effect.callback<void, IndexedDbQueryError>((resume) => { |
| 1285 | const database = options.database |
| 1286 | const tables = database.objectStoreNames |
| 1287 | const transaction = getOrCreateTransaction(database, [...tables], "readwrite") |
| 1288 | |
| 1289 | for (let t = 0; t < tables.length; t++) { |
| 1290 | const objectStore = transaction.objectStore(tables[t]) |
| 1291 | const request = objectStore.clear() |
| 1292 | |
| 1293 | request.onerror = () => { |
| 1294 | resume( |
| 1295 | Effect.fail( |
| 1296 | new IndexedDbQueryError({ |
| 1297 | reason: "TransactionError", |
| 1298 | cause: request.error |
| 1299 | }) |
| 1300 | ) |
| 1301 | ) |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | transaction.onerror = () => { |
| 1306 | resume( |
| 1307 | Effect.fail( |
| 1308 | new IndexedDbQueryError({ |
| 1309 | reason: "TransactionError", |
| 1310 | cause: transaction.error |
| 1311 | }) |
| 1312 | ) |
| 1313 | ) |
| 1314 | } |
| 1315 | |
| 1316 | transaction.oncomplete = () => { |
| 1317 | resume(Effect.void) |
| 1318 | } |
| 1319 | }) |
| 1320 | |
| 1321 | const getCount = (query: IndexedDbQuery.Count<any, never>) => |
| 1322 | Effect.callback<number, IndexedDbQueryError>((resume) => { |
| 1323 | const { keyRange, store } = getReadonlyObjectStore(query) |
| 1324 | |
| 1325 | const request = store.count(keyRange) |
| 1326 | |
| 1327 | request.onerror = (event) => { |
| 1328 | resume( |
| 1329 | Effect.fail( |
| 1330 | new IndexedDbQueryError({ |
| 1331 | reason: "TransactionError", |
| 1332 | cause: event |
| 1333 | }) |
| 1334 | ) |
| 1335 | ) |
| 1336 | } |
| 1337 | |
| 1338 | request.onsuccess = () => { |
| 1339 | resume(Effect.succeed(request.result)) |
| 1340 | } |
| 1341 | }) |
| 1342 | |
| 1343 | const FromProto: Omit< |
| 1344 | IndexedDbQuery.From<any>, |
| 1345 | | "table" |
| 1346 | | "database" |
| 1347 | | "IDBKeyRange" |
| 1348 | | "transaction" |
| 1349 | | "reactivity" |
| 1350 | | "selectCache" |
| 1351 | | "countCache" |
| 1352 | | "deleteCache" |
| 1353 | > = { |
| 1354 | select<Index extends IndexedDbDatabase.IndexFromTable<any>>( |
| 1355 | this: IndexedDbQuery.From<any>, |
| 1356 | index?: Index |
| 1357 | ) { |
| 1358 | let select = this.selectCache.get(index) |
| 1359 | if (select === undefined) { |
| 1360 | select = makeSelect({ |
| 1361 | from: this, |
| 1362 | index |
| 1363 | }) |
| 1364 | this.selectCache.set(index, select) |
| 1365 | } |
| 1366 | return select |
| 1367 | }, |
| 1368 | count<Index extends IndexedDbDatabase.IndexFromTable<any>>( |
| 1369 | this: IndexedDbQuery.From<any>, |
| 1370 | index?: Index |
| 1371 | ) { |
| 1372 | let count = this.countCache.get(index) |
| 1373 | if (count === undefined) { |
| 1374 | count = makeCount({ |
| 1375 | from: this, |
| 1376 | index |
| 1377 | }) |
| 1378 | this.countCache.set(index, count) |
| 1379 | } |
| 1380 | return count |
| 1381 | }, |
| 1382 | delete<Index extends IndexedDbDatabase.IndexFromTable<any>>( |
| 1383 | this: IndexedDbQuery.From<any>, |
| 1384 | index?: Index |
| 1385 | ) { |
| 1386 | let cached = this.deleteCache.get(index) |
| 1387 | if (cached === undefined) { |
| 1388 | cached = makeDeletePartial({ |
| 1389 | from: this, |
| 1390 | index |
| 1391 | }) |
| 1392 | this.deleteCache.set(index, cached) |
| 1393 | } |
| 1394 | return cached |
| 1395 | }, |
| 1396 | insert(this: IndexedDbQuery.From<any>, value: any) { |
| 1397 | return makeModify({ from: this, value, operation: "add" }) |
| 1398 | }, |
| 1399 | upsert(this: IndexedDbQuery.From<any>, value: any) { |
| 1400 | return makeModify({ from: this, value, operation: "put" }) |
| 1401 | }, |
| 1402 | insertAll(this: IndexedDbQuery.From<any>, values: Array<any>) { |
| 1403 | return makeModifyAll({ from: this, values, operation: "add" }) |
| 1404 | }, |
| 1405 | upsertAll(this: IndexedDbQuery.From<any>, values: Array<any>) { |
| 1406 | return makeModifyAll({ from: this, values, operation: "put" }) |
| 1407 | }, |
| 1408 | get clear() { |
| 1409 | const self = this as IndexedDbQuery.From<any> |
| 1410 | return applyClear({ |
| 1411 | database: self.database.current, |
| 1412 | table: self.table |
| 1413 | }) |
| 1414 | }, |
| 1415 | ...CommonProto |
| 1416 | } |
| 1417 | |
| 1418 | const makeFrom = < |
| 1419 | const Table extends IndexedDbTable.AnyWithProps |
| 1420 | >(options: { |
| 1421 | readonly table: Table |
| 1422 | readonly database: MutableRef.MutableRef<globalThis.IDBDatabase> |
| 1423 | readonly IDBKeyRange: typeof globalThis.IDBKeyRange |
| 1424 | readonly reactivity: Reactivity.Reactivity |
| 1425 | }): IndexedDbQuery.From<Table> => { |
| 1426 | const self = Object.create(FromProto) |
| 1427 | self.table = options.table |
| 1428 | self.database = options.database |
| 1429 | self.IDBKeyRange = options.IDBKeyRange |
| 1430 | self.reactivity = options.reactivity |
| 1431 | self.selectCache = new Map() |
| 1432 | self.countCache = new Map() |
| 1433 | self.deleteCache = new Map() |
| 1434 | return self |
| 1435 | } |
| 1436 | |
| 1437 | const DeletePartialProto: Omit< |
| 1438 | IndexedDbQuery.DeletePartial<any, never>, |
| 1439 | | "from" |
| 1440 | | "index" |
| 1441 | > = { |
| 1442 | ...CommonProto, |
| 1443 | limit(this: IndexedDbQuery.DeletePartial<any, never>, limit: number) { |
| 1444 | return makeDelete({ |
| 1445 | delete: this as any, |
| 1446 | limitValue: limit |
| 1447 | }) |
| 1448 | }, |
| 1449 | equals(this: IndexedDbQuery.DeletePartial<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1450 | return makeDelete({ |
| 1451 | delete: this as any, |
| 1452 | only: value |
| 1453 | }) |
| 1454 | }, |
| 1455 | gte(this: IndexedDbQuery.DeletePartial<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1456 | return makeDelete({ |
| 1457 | delete: this as any, |
| 1458 | lowerBound: value, |
| 1459 | excludeLowerBound: false |
| 1460 | }) |
| 1461 | }, |
| 1462 | lte(this: IndexedDbQuery.DeletePartial<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1463 | return makeDelete({ |
| 1464 | delete: this as any, |
| 1465 | upperBound: value, |
| 1466 | excludeUpperBound: false |
| 1467 | }) |
| 1468 | }, |
| 1469 | gt(this: IndexedDbQuery.DeletePartial<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1470 | return makeDelete({ |
| 1471 | delete: this as any, |
| 1472 | lowerBound: value, |
| 1473 | excludeLowerBound: true |
| 1474 | }) |
| 1475 | }, |
| 1476 | lt(this: IndexedDbQuery.DeletePartial<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1477 | return makeDelete({ |
| 1478 | delete: this as any, |
| 1479 | upperBound: value, |
| 1480 | excludeUpperBound: true |
| 1481 | }) |
| 1482 | }, |
| 1483 | between( |
| 1484 | this: IndexedDbQuery.DeletePartial<any, never>, |
| 1485 | lowerBound: IndexedDbQuery.ExtractIndexType<any, never>, |
| 1486 | upperBound: IndexedDbQuery.ExtractIndexType<any, never>, |
| 1487 | queryOptions?: { excludeLowerBound?: boolean; excludeUpperBound?: boolean } |
| 1488 | ) { |
| 1489 | return makeDelete({ |
| 1490 | delete: this as any, |
| 1491 | lowerBound, |
| 1492 | upperBound, |
| 1493 | excludeLowerBound: queryOptions?.excludeLowerBound ?? false, |
| 1494 | excludeUpperBound: queryOptions?.excludeUpperBound ?? false |
| 1495 | }) |
| 1496 | } |
| 1497 | } |
| 1498 | |
| 1499 | const makeDeletePartial = < |
| 1500 | Table extends IndexedDbTable.AnyWithProps, |
| 1501 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 1502 | >(options: { |
| 1503 | readonly from: IndexedDbQuery.From<Table> |
| 1504 | readonly index: Index | undefined |
| 1505 | }): IndexedDbQuery.DeletePartial<Table, Index> => { |
| 1506 | const self = Object.create(DeletePartialProto) |
| 1507 | self.from = options.from |
| 1508 | self.index = options.index |
| 1509 | return self as any |
| 1510 | } |
| 1511 | |
| 1512 | const DeleteProto: Omit< |
| 1513 | IndexedDbQuery.Delete<any, never>, |
| 1514 | | "delete" |
| 1515 | | "limitValue" |
| 1516 | | "only" |
| 1517 | | "lowerBound" |
| 1518 | | "upperBound" |
| 1519 | | "excludeLowerBound" |
| 1520 | | "excludeUpperBound" |
| 1521 | | "predicate" |
| 1522 | > = { |
| 1523 | ...CommonProto, |
| 1524 | ...Effectable.Prototype<IndexedDbQuery.Delete<any, never>>({ |
| 1525 | label: "IndexedDbQuery.Delete", |
| 1526 | evaluate() { |
| 1527 | return applyDelete(this) |
| 1528 | } |
| 1529 | }), |
| 1530 | limit(this: IndexedDbQuery.Delete<any, never>, limit: number) { |
| 1531 | return makeDelete({ |
| 1532 | ...this, |
| 1533 | limitValue: limit |
| 1534 | }) |
| 1535 | }, |
| 1536 | filter(this: IndexedDbQuery.Delete<any, never>, filter: (value: IndexedDbTable.Encoded<any>) => boolean) { |
| 1537 | const prev = this.predicate |
| 1538 | return makeDelete({ |
| 1539 | ...this, |
| 1540 | predicate: prev ? (item) => prev(item) && filter(item) : filter |
| 1541 | }) |
| 1542 | }, |
| 1543 | invalidate( |
| 1544 | this: IndexedDbQuery.Delete<any, never>, |
| 1545 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1546 | ) { |
| 1547 | keys ??= this.only !== undefined |
| 1548 | ? { [this.delete.from.table.tableName]: [this.only] } |
| 1549 | : [this.delete.from.table.tableName] |
| 1550 | return this.delete.from.reactivity.mutation(keys, this) |
| 1551 | } |
| 1552 | } |
| 1553 | |
| 1554 | const makeDelete = < |
| 1555 | Table extends IndexedDbTable.AnyWithProps, |
| 1556 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 1557 | >(options: { |
| 1558 | readonly delete: IndexedDbQuery.DeletePartial<Table, Index> |
| 1559 | readonly limitValue?: number | undefined |
| 1560 | readonly only?: IndexedDbQuery.ExtractIndexType<Table, Index> | undefined |
| 1561 | readonly lowerBound?: |
| 1562 | | IndexedDbQuery.ExtractIndexType<Table, Index> |
| 1563 | | undefined |
| 1564 | readonly upperBound?: |
| 1565 | | IndexedDbQuery.ExtractIndexType<Table, Index> |
| 1566 | | undefined |
| 1567 | readonly excludeLowerBound?: boolean | undefined |
| 1568 | readonly excludeUpperBound?: boolean | undefined |
| 1569 | readonly predicate?: ((item: IndexedDbTable.Encoded<Table>) => boolean) | undefined |
| 1570 | }): IndexedDbQuery.Delete<Table, Index> => { |
| 1571 | const self = Object.create(DeleteProto) |
| 1572 | self.delete = options.delete |
| 1573 | self.limitValue = options.limitValue |
| 1574 | self.only = options.only |
| 1575 | self.lowerBound = options.lowerBound |
| 1576 | self.upperBound = options.upperBound |
| 1577 | self.excludeLowerBound = options.excludeLowerBound ?? false |
| 1578 | self.excludeUpperBound = options.excludeUpperBound ?? false |
| 1579 | self.predicate = options.predicate |
| 1580 | return self |
| 1581 | } |
| 1582 | |
| 1583 | const CountProto: Omit< |
| 1584 | IndexedDbQuery.Count<any, never>, |
| 1585 | | "from" |
| 1586 | | "index" |
| 1587 | | "only" |
| 1588 | | "lowerBound" |
| 1589 | | "upperBound" |
| 1590 | | "excludeLowerBound" |
| 1591 | | "excludeUpperBound" |
| 1592 | > = { |
| 1593 | ...CommonProto, |
| 1594 | ...Effectable.Prototype<IndexedDbQuery.Count<any, never>>({ |
| 1595 | label: "IndexedDbQuery.Count", |
| 1596 | evaluate() { |
| 1597 | return getCount(this) |
| 1598 | } |
| 1599 | }), |
| 1600 | equals(this: IndexedDbQuery.Count<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1601 | return makeCount({ |
| 1602 | from: this.from, |
| 1603 | index: this.index, |
| 1604 | only: value |
| 1605 | }) |
| 1606 | }, |
| 1607 | gte(this: IndexedDbQuery.Count<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1608 | return makeCount({ |
| 1609 | from: this.from, |
| 1610 | index: this.index, |
| 1611 | lowerBound: value, |
| 1612 | excludeLowerBound: false |
| 1613 | }) |
| 1614 | }, |
| 1615 | lte(this: IndexedDbQuery.Count<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1616 | return makeCount({ |
| 1617 | from: this.from, |
| 1618 | index: this.index, |
| 1619 | upperBound: value, |
| 1620 | excludeUpperBound: false |
| 1621 | }) |
| 1622 | }, |
| 1623 | gt(this: IndexedDbQuery.Count<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1624 | return makeCount({ |
| 1625 | from: this.from, |
| 1626 | index: this.index, |
| 1627 | lowerBound: value, |
| 1628 | excludeLowerBound: true |
| 1629 | }) |
| 1630 | }, |
| 1631 | lt(this: IndexedDbQuery.Count<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1632 | return makeCount({ |
| 1633 | from: this.from, |
| 1634 | index: this.index, |
| 1635 | upperBound: value, |
| 1636 | excludeUpperBound: true |
| 1637 | }) |
| 1638 | }, |
| 1639 | between( |
| 1640 | this: IndexedDbQuery.Count<any, never>, |
| 1641 | lowerBound: IndexedDbQuery.ExtractIndexType<any, never>, |
| 1642 | upperBound: IndexedDbQuery.ExtractIndexType<any, never>, |
| 1643 | queryOptions?: { excludeLowerBound?: boolean; excludeUpperBound?: boolean } |
| 1644 | ) { |
| 1645 | return makeCount({ |
| 1646 | from: this.from, |
| 1647 | index: this.index, |
| 1648 | lowerBound, |
| 1649 | upperBound, |
| 1650 | excludeLowerBound: queryOptions?.excludeLowerBound ?? false, |
| 1651 | excludeUpperBound: queryOptions?.excludeUpperBound ?? false |
| 1652 | }) |
| 1653 | } |
| 1654 | } |
| 1655 | |
| 1656 | const makeCount = < |
| 1657 | Table extends IndexedDbTable.AnyWithProps, |
| 1658 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 1659 | >(options: { |
| 1660 | readonly from: IndexedDbQuery.From<Table> |
| 1661 | readonly index: Index | undefined |
| 1662 | readonly only?: IndexedDbQuery.ExtractIndexType<Table, Index> | undefined |
| 1663 | readonly lowerBound?: |
| 1664 | | IndexedDbQuery.ExtractIndexType<Table, Index> |
| 1665 | | undefined |
| 1666 | readonly upperBound?: |
| 1667 | | IndexedDbQuery.ExtractIndexType<Table, Index> |
| 1668 | | undefined |
| 1669 | readonly excludeLowerBound?: boolean | undefined |
| 1670 | readonly excludeUpperBound?: boolean | undefined |
| 1671 | }): IndexedDbQuery.Count<Table, Index> => { |
| 1672 | const self = Object.create(CountProto) |
| 1673 | self.from = options.from |
| 1674 | self.index = options.index |
| 1675 | self.only = options.only |
| 1676 | self.lowerBound = options.lowerBound |
| 1677 | self.upperBound = options.upperBound |
| 1678 | self.excludeLowerBound = options.excludeLowerBound |
| 1679 | self.excludeUpperBound = options.excludeUpperBound |
| 1680 | return self |
| 1681 | } |
| 1682 | |
| 1683 | const SelectProto: Omit< |
| 1684 | IndexedDbQuery.Select<any, never>, |
| 1685 | | "from" |
| 1686 | | "index" |
| 1687 | | "limitValue" |
| 1688 | | "reverseValue" |
| 1689 | | "only" |
| 1690 | | "lowerBound" |
| 1691 | | "upperBound" |
| 1692 | | "excludeLowerBound" |
| 1693 | | "excludeUpperBound" |
| 1694 | > = { |
| 1695 | ...CommonProto, |
| 1696 | ...Effectable.Prototype<IndexedDbQuery.Select<any, never>>({ |
| 1697 | label: "IndexedDbQuery.Select", |
| 1698 | evaluate() { |
| 1699 | return applySelect(this) |
| 1700 | } |
| 1701 | }), |
| 1702 | limit(this: IndexedDbQuery.Select<any, never>, limit: number) { |
| 1703 | return makeSelect({ |
| 1704 | ...this, |
| 1705 | limitValue: limit |
| 1706 | }) |
| 1707 | }, |
| 1708 | offset(this: IndexedDbQuery.Select<any, never>, offset: number) { |
| 1709 | return makeSelect({ |
| 1710 | ...this, |
| 1711 | offsetValue: offset |
| 1712 | }) |
| 1713 | }, |
| 1714 | equals(this: IndexedDbQuery.Select<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1715 | return makeSelect({ |
| 1716 | ...this, |
| 1717 | only: value |
| 1718 | }) |
| 1719 | }, |
| 1720 | gte(this: IndexedDbQuery.Select<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1721 | return makeSelect({ |
| 1722 | ...this, |
| 1723 | lowerBound: value, |
| 1724 | excludeLowerBound: false |
| 1725 | }) |
| 1726 | }, |
| 1727 | lte(this: IndexedDbQuery.Select<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1728 | return makeSelect({ |
| 1729 | ...this, |
| 1730 | upperBound: value, |
| 1731 | excludeUpperBound: false |
| 1732 | }) |
| 1733 | }, |
| 1734 | gt(this: IndexedDbQuery.Select<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1735 | return makeSelect({ |
| 1736 | ...this, |
| 1737 | lowerBound: value, |
| 1738 | excludeLowerBound: true |
| 1739 | }) |
| 1740 | }, |
| 1741 | lt(this: IndexedDbQuery.Select<any, never>, value: IndexedDbQuery.ExtractIndexType<any, never>) { |
| 1742 | return makeSelect({ |
| 1743 | ...this, |
| 1744 | upperBound: value, |
| 1745 | excludeUpperBound: true |
| 1746 | }) |
| 1747 | }, |
| 1748 | between( |
| 1749 | this: IndexedDbQuery.Select<any, never>, |
| 1750 | lowerBound: IndexedDbQuery.ExtractIndexType<any, never>, |
| 1751 | upperBound: IndexedDbQuery.ExtractIndexType<any, never>, |
| 1752 | queryOptions?: { excludeLowerBound?: boolean; excludeUpperBound?: boolean } |
| 1753 | ) { |
| 1754 | return makeSelect({ |
| 1755 | ...this, |
| 1756 | lowerBound, |
| 1757 | upperBound, |
| 1758 | excludeLowerBound: queryOptions?.excludeLowerBound ?? false, |
| 1759 | excludeUpperBound: queryOptions?.excludeUpperBound ?? false |
| 1760 | }) |
| 1761 | }, |
| 1762 | reverse(this: IndexedDbQuery.Select<any, never>) { |
| 1763 | return makeSelect({ |
| 1764 | ...this, |
| 1765 | reverseValue: true |
| 1766 | }) |
| 1767 | }, |
| 1768 | first(this: IndexedDbQuery.Select<any, never>) { |
| 1769 | return makeFirst({ select: this }) |
| 1770 | }, |
| 1771 | filter(this: IndexedDbQuery.Select<any, never>, filter: (value: IndexedDbTable.Encoded<any>) => boolean) { |
| 1772 | const prev = this.predicate |
| 1773 | return makeSelect({ |
| 1774 | ...this, |
| 1775 | predicate: prev ? (item) => prev(item) && filter(item) : filter |
| 1776 | }) |
| 1777 | }, |
| 1778 | stream(this: IndexedDbQuery.Select<any, never>, options?: { |
| 1779 | readonly chunkSize?: number | undefined |
| 1780 | }) { |
| 1781 | const limit = this.limitValue |
| 1782 | const chunkSize = Math.min(options?.chunkSize ?? 100, limit ?? Number.MAX_SAFE_INTEGER) |
| 1783 | const initialOffset = this.offsetValue ?? 0 |
| 1784 | return Stream.suspend(() => { |
| 1785 | let total = 0 |
| 1786 | const initial = this.limit(chunkSize) |
| 1787 | return Stream.paginate(initial, (select) => |
| 1788 | Effect.map( |
| 1789 | applySelect(select as any), |
| 1790 | (data) => { |
| 1791 | total += data.length |
| 1792 | const reachedLimit = limit && total >= limit |
| 1793 | const isPartial = data.length < chunkSize |
| 1794 | const next = makeSelect({ |
| 1795 | ...select, |
| 1796 | limitValue: limit === undefined ? chunkSize : Math.min(chunkSize, limit - total), |
| 1797 | offsetValue: initialOffset + total |
| 1798 | }) |
| 1799 | return [data, isPartial || reachedLimit ? Option.none() : Option.some(next)] as const |
| 1800 | } |
| 1801 | )) |
| 1802 | }) |
| 1803 | }, |
| 1804 | reactive( |
| 1805 | this: IndexedDbQuery.Select<any, never>, |
| 1806 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1807 | ) { |
| 1808 | keys ??= [this.from.table.tableName] |
| 1809 | return this.from.reactivity.stream(keys, this) |
| 1810 | }, |
| 1811 | reactiveQueue( |
| 1812 | this: IndexedDbQuery.Select<any, never>, |
| 1813 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1814 | ) { |
| 1815 | keys ??= [this.from.table.tableName] |
| 1816 | return this.from.reactivity.query(keys, this) |
| 1817 | } |
| 1818 | } |
| 1819 | |
| 1820 | const makeSelect = < |
| 1821 | Table extends IndexedDbTable.AnyWithProps, |
| 1822 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 1823 | >(options: { |
| 1824 | readonly from: IndexedDbQuery.From<Table> |
| 1825 | readonly index?: Index | undefined |
| 1826 | readonly limitValue?: number | undefined |
| 1827 | readonly offsetValue?: number | undefined |
| 1828 | readonly reverseValue?: boolean | undefined |
| 1829 | readonly only?: IndexedDbQuery.ExtractIndexType<Table, Index> | undefined |
| 1830 | readonly lowerBound?: |
| 1831 | | IndexedDbQuery.ExtractIndexType<Table, Index> |
| 1832 | | undefined |
| 1833 | readonly upperBound?: |
| 1834 | | IndexedDbQuery.ExtractIndexType<Table, Index> |
| 1835 | | undefined |
| 1836 | readonly excludeLowerBound?: boolean | undefined |
| 1837 | readonly excludeUpperBound?: boolean | undefined |
| 1838 | readonly predicate?: ((item: IndexedDbTable.Encoded<Table>) => boolean) | undefined |
| 1839 | }): IndexedDbQuery.Select<Table, Index> => { |
| 1840 | const self = Object.create(SelectProto) |
| 1841 | self.from = options.from |
| 1842 | self.index = options.index |
| 1843 | self.only = options.only |
| 1844 | self.limitValue = options.limitValue |
| 1845 | self.offsetValue = options.offsetValue |
| 1846 | self.reverseValue = options.reverseValue |
| 1847 | self.lowerBound = options.lowerBound |
| 1848 | self.upperBound = options.upperBound |
| 1849 | self.excludeLowerBound = options.excludeLowerBound |
| 1850 | self.excludeUpperBound = options.excludeUpperBound |
| 1851 | self.predicate = options.predicate |
| 1852 | return self as any |
| 1853 | } |
| 1854 | |
| 1855 | const FirstProto: Omit< |
| 1856 | IndexedDbQuery.First<any, never>, |
| 1857 | "select" |
| 1858 | > = { |
| 1859 | ...CommonProto, |
| 1860 | ...Effectable.Prototype<IndexedDbQuery.First<any, never>>({ |
| 1861 | label: "IndexedDbQuery.First", |
| 1862 | evaluate() { |
| 1863 | return applyFirst(this) |
| 1864 | } |
| 1865 | }), |
| 1866 | reactive( |
| 1867 | this: IndexedDbQuery.First<any, never>, |
| 1868 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1869 | ) { |
| 1870 | keys ??= this.select.only !== undefined |
| 1871 | ? [`${this.select.from.table.tableName}:${String(this.select.only)}`] |
| 1872 | : [this.select.from.table.tableName] |
| 1873 | return this.select.from.reactivity.stream(keys, this) |
| 1874 | }, |
| 1875 | reactiveQueue( |
| 1876 | this: IndexedDbQuery.First<any, never>, |
| 1877 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1878 | ) { |
| 1879 | keys ??= this.select.only !== undefined |
| 1880 | ? [`${this.select.from.table.tableName}:${this.select.only}`] |
| 1881 | : [this.select.from.table.tableName] |
| 1882 | return this.select.from.reactivity.query(keys, this) |
| 1883 | } |
| 1884 | } |
| 1885 | |
| 1886 | const makeFirst = < |
| 1887 | Table extends IndexedDbTable.AnyWithProps, |
| 1888 | Index extends IndexedDbDatabase.IndexFromTable<Table> |
| 1889 | >(options: { |
| 1890 | readonly select: IndexedDbQuery.Select<Table, Index> |
| 1891 | }): IndexedDbQuery.First<Table, Index> => { |
| 1892 | const self = Object.create(FirstProto) |
| 1893 | self.select = options.select |
| 1894 | return self as any |
| 1895 | } |
| 1896 | |
| 1897 | const ModifyProto: Omit< |
| 1898 | IndexedDbQuery.Modify<any>, |
| 1899 | | "from" |
| 1900 | | "value" |
| 1901 | | "operation" |
| 1902 | > = { |
| 1903 | ...CommonProto, |
| 1904 | ...Effectable.Prototype<IndexedDbQuery.Modify<any>>({ |
| 1905 | label: "IndexedDbQuery.Modify", |
| 1906 | evaluate() { |
| 1907 | return applyModify({ query: this, value: this.value }) |
| 1908 | } |
| 1909 | }), |
| 1910 | invalidate( |
| 1911 | this: IndexedDbQuery.Modify<any>, |
| 1912 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1913 | ) { |
| 1914 | const keyPath = this.from.table.keyPath |
| 1915 | keys ??= typeof keyPath === "string" && this.value[keyPath] !== undefined |
| 1916 | ? { [this.from.table.tableName]: [this.value[keyPath]] } |
| 1917 | : [this.from.table.tableName] |
| 1918 | return this.from.reactivity.mutation(keys, this) |
| 1919 | } |
| 1920 | } |
| 1921 | |
| 1922 | const makeModify = <Table extends IndexedDbTable.AnyWithProps>(options: { |
| 1923 | readonly from: IndexedDbQuery.From<Table> |
| 1924 | readonly value: IndexedDbTable.TableSchema<Table>["Type"] |
| 1925 | readonly operation: "add" | "put" |
| 1926 | }): IndexedDbQuery.Modify<Table> => { |
| 1927 | const self = Object.create(ModifyProto) |
| 1928 | self.from = options.from |
| 1929 | self.value = options.value |
| 1930 | self.operation = options.operation |
| 1931 | return self as any |
| 1932 | } |
| 1933 | |
| 1934 | const ModifyAllProto: Omit< |
| 1935 | IndexedDbQuery.ModifyAll<any>, |
| 1936 | | "from" |
| 1937 | | "values" |
| 1938 | | "operation" |
| 1939 | > = { |
| 1940 | ...CommonProto, |
| 1941 | ...Effectable.Prototype<IndexedDbQuery.ModifyAll<any>>({ |
| 1942 | label: "IndexedDbQuery.ModifyAll", |
| 1943 | evaluate() { |
| 1944 | return applyModifyAll({ query: this, values: this.values }) |
| 1945 | } |
| 1946 | }), |
| 1947 | invalidate( |
| 1948 | this: IndexedDbQuery.ModifyAll<any>, |
| 1949 | keys?: ReadonlyArray<unknown> | Record.ReadonlyRecord<string, ReadonlyArray<unknown>> | undefined |
| 1950 | ) { |
| 1951 | keys ??= [this.from.table.tableName] |
| 1952 | return this.from.reactivity.mutation(keys, this) |
| 1953 | } |
| 1954 | } |
| 1955 | |
| 1956 | const makeModifyAll = < |
| 1957 | Table extends IndexedDbTable.AnyWithProps |
| 1958 | >(options: { |
| 1959 | readonly from: IndexedDbQuery.From<Table> |
| 1960 | readonly values: Array<IndexedDbTable.TableSchema<Table>["Type"]> |
| 1961 | readonly operation: "add" | "put" |
| 1962 | }): IndexedDbQuery.ModifyAll<Table> => { |
| 1963 | const self = Object.create(ModifyAllProto) |
| 1964 | self.from = options.from |
| 1965 | self.values = options.values |
| 1966 | self.operation = options.operation |
| 1967 | return self as any |
| 1968 | } |
| 1969 | |
| 1970 | const QueryBuilderProto: Omit< |
| 1971 | IndexedDbQueryBuilder<any>, |
| 1972 | | "fromCache" |
| 1973 | | "tables" |
| 1974 | | "database" |
| 1975 | | "IDBKeyRange" |
| 1976 | | "IDBTransaction" |
| 1977 | | "reactivity" |
| 1978 | > = { |
| 1979 | use(this: IndexedDbQueryBuilder<any>, f: (database: globalThis.IDBDatabase) => any) { |
| 1980 | return Effect.try({ |
| 1981 | try: () => f(this.database.current), |
| 1982 | catch: (error) => |
| 1983 | new IndexedDbQueryError({ |
| 1984 | reason: "UnknownError", |
| 1985 | cause: error |
| 1986 | }) |
| 1987 | }) |
| 1988 | }, |
| 1989 | from(this: IndexedDbQueryBuilder<any>, table: any) { |
| 1990 | let cached = this.fromCache.get(table) |
| 1991 | if (cached === undefined) { |
| 1992 | cached = makeFrom({ |
| 1993 | database: this.database, |
| 1994 | IDBKeyRange: this.IDBKeyRange, |
| 1995 | table: this.tables.get(table)!, |
| 1996 | reactivity: this.reactivity |
| 1997 | }) |
| 1998 | this.fromCache.set(table, cached) |
| 1999 | } |
| 2000 | return cached as any |
| 2001 | }, |
| 2002 | get clearAll() { |
| 2003 | const self = this as IndexedDbQueryBuilder<any> |
| 2004 | return applyClearAll({ database: self.database.current }) |
| 2005 | }, |
| 2006 | ...CommonProto, |
| 2007 | withTransaction(this: IndexedDbQueryBuilder<any>, options: { |
| 2008 | readonly tables: NonEmptyReadonlyArray<any> |
| 2009 | readonly mode: globalThis.IDBTransactionMode |
| 2010 | readonly durability?: IDBTransactionDurability |
| 2011 | }) { |
| 2012 | return (effect) => |
| 2013 | Effect.suspend(() => { |
| 2014 | const transaction = this.database.current.transaction(options.tables, options.mode, options) |
| 2015 | return Effect.provideService(effect, IndexedDbTransaction, transaction).pipe( |
| 2016 | Effect.onExit((exit) => |
| 2017 | exit._tag === "Success" ? awaitTransaction(transaction) : abortTransaction(transaction) |
| 2018 | ) |
| 2019 | ) |
| 2020 | }).pipe( |
| 2021 | // To prevent async gaps between transaction queries |
| 2022 | Effect.provideService(References.PreventSchedulerYield, true) |
| 2023 | ) |
| 2024 | } |
| 2025 | } |
| 2026 | |
| 2027 | const abortTransaction = (transaction: globalThis.IDBTransaction) => |
| 2028 | Effect.try({ |
| 2029 | try: () => transaction.abort(), |
| 2030 | catch: () => undefined |
| 2031 | }).pipe(Effect.ignore) |
| 2032 | |
| 2033 | const awaitTransaction = (transaction: globalThis.IDBTransaction) => |
| 2034 | Effect.callback<void, IndexedDbQueryError>((resume) => { |
| 2035 | transaction.oncomplete = () => { |
| 2036 | resume(Effect.void) |
| 2037 | } |
| 2038 | transaction.onabort = () => { |
| 2039 | resume( |
| 2040 | Effect.fail( |
| 2041 | new IndexedDbQueryError({ |
| 2042 | reason: "TransactionError", |
| 2043 | cause: transaction.error |
| 2044 | }) |
| 2045 | ) |
| 2046 | ) |
| 2047 | } |
| 2048 | return abortTransaction(transaction) |
| 2049 | }) |
| 2050 | |
| 2051 | /** |
| 2052 | * Creates an `IndexedDbQueryBuilder` from an open database reference, key-range constructor, table map, and reactivity service. |
| 2053 | * |
| 2054 | * @stability unstable |
| 2055 | * @category constructors |
| 2056 | * @since 4.0.0 |
| 2057 | */ |
| 2058 | export const make = <Source extends IndexedDbVersion.AnyWithProps>({ |
| 2059 | IDBKeyRange, |
| 2060 | database, |
| 2061 | tables, |
| 2062 | reactivity |
| 2063 | }: { |
| 2064 | readonly database: MutableRef.MutableRef<globalThis.IDBDatabase> |
| 2065 | readonly IDBKeyRange: typeof globalThis.IDBKeyRange |
| 2066 | readonly tables: ReadonlyMap<string, IndexedDbVersion.Tables<Source>> |
| 2067 | readonly reactivity: Reactivity.Reactivity |
| 2068 | }): IndexedDbQueryBuilder<Source> => { |
| 2069 | const self = Object.create(QueryBuilderProto) |
| 2070 | self.tables = tables |
| 2071 | self.database = database |
| 2072 | self.reactivity = reactivity |
| 2073 | self.IDBKeyRange = IDBKeyRange |
| 2074 | self.fromCache = new Map() |
| 2075 | return self |
| 2076 | } |
| 2077 | |
| 2078 | const getOrCreateTransaction = ( |
| 2079 | database: globalThis.IDBDatabase, |
| 2080 | tables: ReadonlyArray<string>, |
| 2081 | mode: globalThis.IDBTransactionMode, |
| 2082 | options?: IDBTransactionOptions |
| 2083 | ) => { |
| 2084 | const fiber = Fiber.getCurrent()! |
| 2085 | return Context.getOrUndefined(fiber.context, IndexedDbTransaction) ?? database.transaction(tables, mode, options) |
| 2086 | } |