akanjs 3.1.0-rc.24 → 3.1.0-rc.25

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.
@@ -96,6 +96,8 @@ type QueryMethodOfKey<
96
96
  [K in `remove${CapitalizedK}`]: (...args: _Args) => Promise<UpdateResult>;
97
97
  } & {
98
98
  [K in `removeOne${CapitalizedK}`]: (...args: _Args) => Promise<UpdateResult>;
99
+ } & {
100
+ [K in `purge${CapitalizedK}`]: (...args: _Args) => Promise<number>;
99
101
  } & {
100
102
  [K in `update${CapitalizedK}`]: (...args: _Args) => UpdateChain<Doc>;
101
103
  } & {
@@ -154,6 +156,7 @@ export type DatabaseInstanceWithQuerySort<
154
156
  __remove: (id: string) => Promise<Doc>;
155
157
  __removeMany: (query: _QueryOfDoc) => Promise<UpdateResult>;
156
158
  __removeOne: (query: _QueryOfDoc) => Promise<UpdateResult>;
159
+ __purgeMany: (query: _QueryOfDoc) => Promise<number>;
157
160
  __updateMany: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
158
161
  __updateOne: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
159
162
  __list(query: _QueryOfDoc, queryOption?: _ListQueryOption): Promise<Doc[]>;
package/document/into.ts CHANGED
@@ -83,6 +83,8 @@ export type Mdl<
83
83
  ): Promise<UpdateResult>;
84
84
  removeOne(query: _RawQuery): Promise<UpdateResult>;
85
85
  removeMany(query: _RawQuery): Promise<UpdateResult>;
86
+ /** Deletes every row the query matches, removed ones too, and answers how many: no hook, cascade or undo. */
87
+ purgeMany(query: _RawQuery): Promise<number>;
86
88
  updateById(id: string, update: DocumentUpdateInput<_RawDoc>, options?: DocumentUpdateOptions): Promise<UpdateResult>;
87
89
  removeById(id: string): Promise<UpdateResult>;
88
90
  /**
@@ -14,15 +14,17 @@ import type {
14
14
  SliceCls,
15
15
  } from "akanjs/signal";
16
16
 
17
- type ExtendedEndpointReturn<ClientReturns, Full, Light, Insight> = ClientReturns extends (infer R)[]
18
- ? ExtendedEndpointReturn<R, Full, Light, Insight>[]
19
- : Full extends ClientReturns
20
- ? Full
21
- : Light extends ClientReturns
22
- ? Light
23
- : Insight extends ClientReturns
24
- ? Insight
25
- : ClientReturns;
17
+ type ExtendedEndpointReturn<ClientReturns, Full, Light, Insight> = unknown extends ClientReturns
18
+ ? ClientReturns
19
+ : ClientReturns extends (infer R)[]
20
+ ? ExtendedEndpointReturn<R, Full, Light, Insight>[]
21
+ : Full extends ClientReturns
22
+ ? Full
23
+ : Light extends ClientReturns
24
+ ? Light
25
+ : Insight extends ClientReturns
26
+ ? Insight
27
+ : ClientReturns;
26
28
 
27
29
  type EndpointClientReturns<E, SlceCls extends SliceCls | never> = [SlceCls] extends [never]
28
30
  ? EndpInfoClientReturns<E>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.1.0-rc.24",
3
+ "version": "3.1.0-rc.25",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -291,6 +291,7 @@ export class DatabaseResolver {
291
291
  timedQuery(() => store.updateManyByQuery(query, update, ...scopeArgs(options))),
292
292
  removeOne: (query: QueryOf<any>) => timedQuery(() => store.removeOneByQuery(query)),
293
293
  removeMany: (query: QueryOf<any>) => timedQuery(() => store.removeManyByQuery(query)),
294
+ purgeMany: (query: QueryOf<any>) => timedQuery(() => store.purgeManyByQuery(query)),
294
295
  updateById: (id: string, update: DocumentUpdateInput, options?: DocumentUpdateOptions) =>
295
296
  timedQuery(() => store.updateOneByQuery({ id }, update, options)),
296
297
  removeById: (id: string) => timedQuery(() => store.removeOneByQuery({ id })),
@@ -397,6 +398,9 @@ export class DatabaseResolver {
397
398
  async __removeOne(query: QueryOf<any>) {
398
399
  return await timedQuery(() => this.__store.removeOneByQuery(query));
399
400
  }
401
+ async __purgeMany(query: QueryOf<any>) {
402
+ return await timedQuery(() => this.__store.purgeManyByQuery(query));
403
+ }
400
404
  async __updateMany(query: QueryOf<any>, update: DocumentUpdateInput) {
401
405
  return await timedQuery(() => this.__store.updateManyByQuery(query, update));
402
406
  }
@@ -35,6 +35,9 @@ export class ServiceResolver {
35
35
  async __removeOne(this: DatabaseService, query: QueryOf<any>) {
36
36
  return await this.__databaseModel.__removeOne(query);
37
37
  },
38
+ async __purgeMany(this: DatabaseService, query: QueryOf<any>) {
39
+ return await this.__databaseModel.__purgeMany(query);
40
+ },
38
41
  async __updateMany(this: DatabaseService, query: QueryOf<any>, update: DocumentUpdateInput) {
39
42
  return await this.__databaseModel.__updateMany(query, update);
40
43
  },
@@ -91,6 +91,7 @@ export class SqlDocumentStore {
91
91
  static readonly #storedRow = Symbol("akan.storedRow");
92
92
  /** Set on a document read as removed, which only a `withRemoved` read hands out. */
93
93
  static readonly #readRemoved = Symbol("akan.readRemoved");
94
+ static readonly #purgeBatchRows = 1000;
94
95
 
95
96
  constructor(
96
97
  private readonly owner: DocumentDatabaseOwner,
@@ -397,6 +398,43 @@ export class SqlDocumentStore {
397
398
  return await this.#updateOne(query, { removedAt: dayjs() }, {}, "removeOneByQuery");
398
399
  }
399
400
 
401
+ async purgeManyByQuery(query: DocumentQuery) {
402
+
403
+ if (SqlDocumentStore.#matchesEveryRow(query))
404
+ throw new Error(
405
+ `purgeManyByQuery on "${this.table}" matches every row; a purge cannot be undone, so name a condition`,
406
+ );
407
+ const { where, params, joins } = this.compiler.compile(query);
408
+ if (joins.length)
409
+ throw new Error(
410
+ `q.search() cannot be used in purgeManyByQuery on "${this.table}"; query-level writes take no join.`,
411
+ );
412
+ const table = quoteIdent(this.table);
413
+ const batch = SqlDocumentStore.#purgeBatchRows;
414
+
415
+ const statement = this.owner
416
+ .getConnection()
417
+ .prepare(
418
+ `DELETE FROM ${table} WHERE ${quoteIdent("id")} IN (SELECT ${quoteIdent("id")} FROM ${table} WHERE ${where} LIMIT ${batch}) AND (${where})`,
419
+ );
420
+ let purged = 0;
421
+ for (;;) {
422
+ const changes = this.dialect.affectedRows(await statement.run(...params, ...params));
423
+ purged += changes;
424
+ if (changes < batch) return purged;
425
+
426
+ await new Promise((resolve) => setTimeout(resolve, 0));
427
+ }
428
+ }
429
+
430
+ static #matchesEveryRow(query: DocumentQuery): boolean {
431
+ if (!isDocumentQueryNode(query)) return Object.keys(query).length === 0;
432
+ if (query.kind === "all") return query.queries.every((sub) => SqlDocumentStore.#matchesEveryRow(sub));
433
+ if (query.kind === "any")
434
+ return !query.queries.length || query.queries.some((sub) => SqlDocumentStore.#matchesEveryRow(sub));
435
+ return false;
436
+ }
437
+
400
438
  private compiledUpdate(update: DocumentUpdate) {
401
439
  for (const raw of Object.values(update))
402
440
  assertStorableJson(jsonStr(isDocumentUpdateNode(raw) ? raw.value : raw), this.table);
@@ -74,6 +74,7 @@ export interface DocumentStore {
74
74
  removeOneByQuery(
75
75
  query: DocumentQuery,
76
76
  ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }>;
77
+ purgeManyByQuery(query: DocumentQuery): Promise<number>;
77
78
  bulkWrite(
78
79
  operations: { updateOne: { filter: DocumentQuery; update: DocumentUpdateInput; upsert?: boolean } }[],
79
80
  ): Promise<{ acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }>;
@@ -202,6 +202,9 @@ export class ServiceModel<
202
202
  [`removeOne${key}`]: async function (this: DatabaseService, ...args: any) {
203
203
  return this.__removeOne(queryOf(args));
204
204
  },
205
+ [`purge${key}`]: async function (this: DatabaseService, ...args: any) {
206
+ return this.__purgeMany(queryOf(args));
207
+ },
205
208
  [`update${key}`]: function (this: DatabaseService, ...args: any): UpdateChain {
206
209
  const query = queryOf(args);
207
210
  return { set: (update) => this.__updateMany(query, update) };
package/service/types.ts CHANGED
@@ -105,6 +105,7 @@ export type DatabaseService<
105
105
  __remove: (id: string) => Promise<Doc>;
106
106
  __removeMany: (query: _QueryOfDoc) => Promise<UpdateResult>;
107
107
  __removeOne: (query: _QueryOfDoc) => Promise<UpdateResult>;
108
+ __purgeMany: (query: _QueryOfDoc) => Promise<number>;
108
109
  __updateMany: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
109
110
  __updateOne: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
110
111
  __list(query?: _QueryOfDoc, queryOption?: _ListQueryOption): Promise<Doc[]>;
@@ -55,6 +55,8 @@ type QueryMethodOfKey<CapitalizedK extends string, Doc, Insight, _Args extends a
55
55
  [K in `remove${CapitalizedK}`]: (...args: _Args) => Promise<UpdateResult>;
56
56
  } & {
57
57
  [K in `removeOne${CapitalizedK}`]: (...args: _Args) => Promise<UpdateResult>;
58
+ } & {
59
+ [K in `purge${CapitalizedK}`]: (...args: _Args) => Promise<number>;
58
60
  } & {
59
61
  [K in `update${CapitalizedK}`]: (...args: _Args) => UpdateChain<Doc>;
60
62
  } & {
@@ -83,6 +85,7 @@ export type DatabaseInstanceWithQuerySort<T extends string = string, Input = any
83
85
  __remove: (id: string) => Promise<Doc>;
84
86
  __removeMany: (query: _QueryOfDoc) => Promise<UpdateResult>;
85
87
  __removeOne: (query: _QueryOfDoc) => Promise<UpdateResult>;
88
+ __purgeMany: (query: _QueryOfDoc) => Promise<number>;
86
89
  __updateMany: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
87
90
  __updateOne: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
88
91
  __list(query: _QueryOfDoc, queryOption?: _ListQueryOption): Promise<Doc[]>;
@@ -55,6 +55,8 @@ export type Mdl<Doc, Raw, _RawDoc = DocumentModel<Raw>, _RawQuery extends Docume
55
55
  updateMany(query: _RawQuery, update: DocumentUpdateInput<_RawDoc>, options?: DocumentScopeOptions): Promise<UpdateResult>;
56
56
  removeOne(query: _RawQuery): Promise<UpdateResult>;
57
57
  removeMany(query: _RawQuery): Promise<UpdateResult>;
58
+ /** Deletes every row the query matches, removed ones too, and answers how many: no hook, cascade or undo. */
59
+ purgeMany(query: _RawQuery): Promise<number>;
58
60
  updateById(id: string, update: DocumentUpdateInput<_RawDoc>, options?: DocumentUpdateOptions): Promise<UpdateResult>;
59
61
  removeById(id: string): Promise<UpdateResult>;
60
62
  /**
@@ -1,7 +1,7 @@
1
1
  import type { ENDPOINT_META, PromiseOrObject } from "akanjs/base";
2
2
  import type { FetchPolicy } from "akanjs/common";
3
3
  import type { EndpInfoArgs, EndpInfoClientReturns, EndpInfoNullable, EndpInfoReqType, EndpointCls, EndpointInfo, PromptMessage, SlceCnstFull, SlceCnstInsight, SlceCnstLight, SliceCls } from "akanjs/signal";
4
- type ExtendedEndpointReturn<ClientReturns, Full, Light, Insight> = ClientReturns extends (infer R)[] ? ExtendedEndpointReturn<R, Full, Light, Insight>[] : Full extends ClientReturns ? Full : Light extends ClientReturns ? Light : Insight extends ClientReturns ? Insight : ClientReturns;
4
+ type ExtendedEndpointReturn<ClientReturns, Full, Light, Insight> = unknown extends ClientReturns ? ClientReturns : ClientReturns extends (infer R)[] ? ExtendedEndpointReturn<R, Full, Light, Insight>[] : Full extends ClientReturns ? Full : Light extends ClientReturns ? Light : Insight extends ClientReturns ? Insight : ClientReturns;
5
5
  type EndpointClientReturns<E, SlceCls extends SliceCls | never> = [SlceCls] extends [never] ? EndpInfoClientReturns<E> : ExtendedEndpointReturn<EndpInfoClientReturns<E>, SlceCnstFull<SlceCls>, SlceCnstLight<SlceCls>, SlceCnstInsight<SlceCls>>;
6
6
  type OrNull<T, Nullable> = Nullable extends true ? T | null : T;
7
7
  type EndpInfoReturns<E, SlceCls extends SliceCls | never> = OrNull<EndpointClientReturns<E, SlceCls>, EndpInfoNullable<E>>;
@@ -50,6 +50,7 @@ export declare class SqlDocumentStore {
50
50
  modifiedCount: number;
51
51
  upsertedId: any;
52
52
  }>;
53
+ purgeManyByQuery(query: DocumentQuery): Promise<number>;
53
54
  private compiledUpdate;
54
55
  bulkWrite(operations: {
55
56
  updateOne: {
@@ -68,6 +68,7 @@ export interface DocumentStore {
68
68
  modifiedCount: number;
69
69
  upsertedId: string | null;
70
70
  }>;
71
+ purgeManyByQuery(query: DocumentQuery): Promise<number>;
71
72
  bulkWrite(operations: {
72
73
  updateOne: {
73
74
  filter: DocumentQuery;
@@ -33,6 +33,7 @@ export type DatabaseService<T extends string = string, Input = any, Doc = any, O
33
33
  __remove: (id: string) => Promise<Doc>;
34
34
  __removeMany: (query: _QueryOfDoc) => Promise<UpdateResult>;
35
35
  __removeOne: (query: _QueryOfDoc) => Promise<UpdateResult>;
36
+ __purgeMany: (query: _QueryOfDoc) => Promise<number>;
36
37
  __updateMany: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
37
38
  __updateOne: (query: _QueryOfDoc, update: DocumentUpdateInput<Doc>) => Promise<UpdateResult>;
38
39
  __list(query?: _QueryOfDoc, queryOption?: _ListQueryOption): Promise<Doc[]>;
@@ -0,0 +1,4 @@
1
+ export declare class EditSeed {
2
+ #private;
3
+ static keyOf(edit: Record<string, unknown>, modelObjKey: string, viewAtKey: string): string;
4
+ }
@@ -14,6 +14,7 @@ import type { ModalSurfaceProps } from "../Dialog/modalSurface";
14
14
  import { Modal } from "../Modal";
15
15
  import DraftBar from "./DraftBar";
16
16
  import { type DraftProp, editDraftScope, newDraftScope } from "./draftScope";
17
+ import { EditSeed } from "./editSeed";
17
18
  import { NewFormOrigin } from "./newFormOrigin";
18
19
 
19
20
  const EDIT_PAYLOAD_MAX_AGE_MS = 60_000;
@@ -206,10 +207,15 @@ export default function EditModal<Full extends { id: string }>({
206
207
  Date.now() - viewAt.getTime() > EDIT_PAYLOAD_MAX_AGE_MS
207
208
  );
208
209
  }, []);
210
+ const filledSeedRef = useRef<string | null>(null);
209
211
  useEffect(() => {
210
212
  if (!modelEdit) return;
211
213
  const refName = (modelEdit as ServerEdit<string, Full>).refName;
212
214
  const editType: "edit" | "new" = refName && (modelEdit as DynamicRecord)[names.modelObj] ? "edit" : "new";
215
+ const seedKey = EditSeed.keyOf(modelEdit as DynamicRecord, names.modelObj, names.modelViewAt);
216
+
217
+ if (seedKey === filledSeedRef.current && (st.get() as unknown as DynamicRecord)[names.modelModal]) return;
218
+ filledSeedRef.current = seedKey;
213
219
  const cnst = ConstantRegistry.getDatabase(modelName);
214
220
  const modelRef = cnst.full;
215
221
  if (editType === "edit") {
@@ -0,0 +1,28 @@
1
+ import { deepObjectify } from "akanjs/common";
2
+
3
+ export class EditSeed {
4
+ static keyOf(edit: Record<string, unknown>, modelObjKey: string, viewAtKey: string): string {
5
+ const modelObj = edit[modelObjKey] as { id: string; updatedAt?: unknown } | undefined;
6
+ if (edit.refName && modelObj)
7
+
8
+ return `edit:${modelObj.id}@${EditSeed.#timeOf(modelObj.updatedAt) ?? EditSeed.#timeOf(edit[viewAtKey])}`;
9
+ return `new:${EditSeed.#stableStringify(deepObjectify(edit, { serializable: true, convertDate: "string" }))}`;
10
+ }
11
+
12
+ static #timeOf(value: unknown): number | null {
13
+ if (value === null || value === undefined) return null;
14
+ const time = new Date(value as string).getTime();
15
+ return Number.isNaN(time) ? null : time;
16
+ }
17
+
18
+ static #stableStringify(value: unknown): string {
19
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
20
+ if (Array.isArray(value)) return `[${value.map((item) => EditSeed.#stableStringify(item)).join(",")}]`;
21
+ const source = value as Record<string, unknown>;
22
+ const entries = Object.keys(source)
23
+ .filter((key) => source[key] !== undefined)
24
+ .sort()
25
+ .map((key) => `${JSON.stringify(key)}:${EditSeed.#stableStringify(source[key])}`);
26
+ return `{${entries.join(",")}}`;
27
+ }
28
+ }