MCPcopy
hub / github.com/streetwriters/notesnook / SQLCollection

Class SQLCollection

packages/core/src/database/sql-collection.ts:68–374  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

66export const MAX_SQL_PARAMETERS = 200;
67
68export class SQLCollection<
69 TCollectionType extends keyof DatabaseSchema,
70 T extends DatabaseSchema[TCollectionType] = DatabaseSchema[TCollectionType]
71> implements DatabaseCollection<SQLiteItem<T>, true>
72{
73 constructor(
74 private readonly db: DatabaseAccessor,
75 _startTransaction: (
76 executor: (tr: Kysely<DatabaseSchema>) => Promise<void>
77 ) => Promise<void>,
78 public readonly type: TCollectionType,
79 private readonly eventManager: EventManager,
80 private readonly sanitizer: Sanitizer
81 ) {}
82
83 async clear() {
84 await this.db().deleteFrom(this.type).execute();
85 }
86
87 async init() {}
88
89 async upsert(item: SQLiteItem<T>) {
90 if (!item.id) throw new Error("The item must contain the id field.");
91 if (!item.deleted) item.dateCreated = item.dateCreated || Date.now();
92
93 // if item is newly synced, remote will be true.
94 if (!item.remote) {
95 item.dateModified = Date.now();
96 item.synced = false;
97 }
98 // the item has become local now, so remove the flags
99 delete item.remote;
100
101 if (!this.sanitizer.sanitize(this.type, item)) return;
102
103 await this.db()
104 .replaceInto<keyof DatabaseSchema>(this.type)
105 .values(item)
106 .execute();
107
108 this.eventManager.publish(EVENTS.databaseUpdated, <UpsertEvent>{
109 type: "upsert",
110 collection: this.type,
111 item
112 });
113 }
114
115 async softDelete(ids: string[]) {
116 await this.db()
117 .transaction()
118 .execute(async (tx) => {
119 for (const chunk of toChunks(ids, MAX_SQL_PARAMETERS)) {
120 await tx
121 .replaceInto<keyof DatabaseSchema>(this.type)
122 .values(
123 chunk.map((id) => ({
124 id,
125 deleted: true,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected