Skip to content

Commit

Permalink
fix(storage-engine): auto_increment issue
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD committed Nov 20, 2022
1 parent 31dc122 commit ff7bdca
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
21 changes: 14 additions & 7 deletions packages/core/storage-engine/src/storage-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,12 @@ export class AlwatrStorageEngine<DocumentType extends DocumentObject> {
* Get next auto increment id for numerical document id.
*/
get nextAutoIncrementId(): string {
const id = this._storage.meta ? +this._storage.meta.lastUpdatedId : 0;
let id = +(this._storage.meta?.lastAutoId ?? -1);
if (isNaN(id)) throw new Error('doc_id_is_nan');
return (id + 1).toString();
do {
id++;
} while (this._storage.data[id.toString()] != null);
return id.toString();
}

protected get _newStorage(): DataStorage<DocumentType> {
Expand Down Expand Up @@ -251,12 +254,18 @@ export class AlwatrStorageEngine<DocumentType extends DocumentObject> {
documentObject = JSON.parse(JSON.stringify(documentObject));
}

if (documentObject._id === 'auto_increment') {
const autoIncrement = documentObject._id === 'auto_increment';

if (autoIncrement) {
documentObject._id = this.nextAutoIncrementId;
}

const oldData = this._storage.data[documentObject._id];

if (oldData == null) {
this._keys = null; // Clear cached keys
}

// update meta
documentObject._updatedAt = Date.now();
documentObject._createdAt = oldData?._createdAt ?? documentObject._updatedAt;
Expand All @@ -266,16 +275,14 @@ export class AlwatrStorageEngine<DocumentType extends DocumentObject> {
this._storage.meta ??= {
formatVersion: AlwatrStorageEngine.formatVersion,
reversion: 0,
lastCreatedId: documentObject._id,
lastUpdatedId: '',
lastUpdatedAt: 0,
};
this._storage.meta.reversion++;
this._storage.meta.lastUpdatedId = documentObject._id;
this._storage.meta.lastUpdatedAt = documentObject._updatedAt;
if (oldData == null) {
this._keys = null; // Clear cached keys
this._storage.meta.lastCreatedId = documentObject._id;
if (autoIncrement) {
this._storage.meta.lastAutoId = documentObject._id;
}

this._storage.data[documentObject._id] = documentObject;
Expand Down
4 changes: 2 additions & 2 deletions packages/core/storage-engine/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ export type DataStorage<T extends DocumentObject> = {
reversion: number;
lastUpdatedAt: number;
lastUpdatedId: string;
lastCreatedId: string;
lastAutoId?: string;
};
data: Record<string, T | undefined>;
}
};

export type AlwatrStorageEngineConfig = {
/**
Expand Down

0 comments on commit ff7bdca

Please sign in to comment.