MCPcopy
hub / github.com/tldraw/tldraw / SQLiteSyncStorageTransaction

Class SQLiteSyncStorageTransaction

packages/sync-core/src/lib/SQLiteSyncStorage.ts:500–626  ·  view source on GitHub ↗

* Transaction implementation for SQLiteSyncStorage. * Provides access to documents, tombstones, and metadata within a transaction. * * @internal

Source from the content-addressed store, hash-verified

498 * @internal
499 */
500class SQLiteSyncStorageTransaction<R extends UnknownRecord> implements TLSyncStorageTransaction<R> {
501 private _clock: number
502 private _closed = false
503 private _didIncrementClock: boolean = false
504
505 constructor(
506 private storage: SQLiteSyncStorage<R>,
507 private stmts: SQLiteSyncStorage<R>['stmts']
508 ) {
509 this._clock = this.storage.getClock()
510 }
511
512 /** @internal */
513 close() {
514 this._closed = true
515 }
516
517 private assertNotClosed() {
518 assert(!this._closed, 'Transaction has ended, iterator cannot be consumed')
519 }
520
521 getClock(): number {
522 return this._clock
523 }
524
525 private getNextClock(): number {
526 if (!this._didIncrementClock) {
527 this._didIncrementClock = true
528 this.stmts.incrementDocumentClock.run()
529 this._clock = this.storage.getClock()
530 }
531 return this._clock
532 }
533
534 get(id: string): R | undefined {
535 this.assertNotClosed()
536 const row = this.stmts.getDocument.all(id)[0]
537 if (!row) return undefined
538 return decodeState<R>(row.state)
539 }
540
541 set(id: string, record: R): void {
542 this.assertNotClosed()
543 assert(id === record.id, `Record id mismatch: key does not match record.id`)
544 const clock = this.getNextClock()
545 // Automatically clear tombstone if it exists
546 this.stmts.deleteTombstone.run(id)
547 this.stmts.insertDocument.run(id, encodeState(record), clock)
548 }
549
550 delete(id: string): void {
551 this.assertNotClosed()
552 // Only create a tombstone if the record actually exists
553 const exists = this.stmts.documentExists.all(id)[0]
554 if (!exists) return
555 const clock = this.getNextClock()
556 this.stmts.deleteDocument.run(id)
557 this.stmts.insertTombstone.run(id, clock)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…