1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-01-23 18:53:36 +02:00

Chore: Allow saving multiple note changes in one transaction

This commit is contained in:
Laurent Cozic 2024-01-04 17:37:26 +00:00
parent 0a2afdb010
commit 906b7c3a33

View File

@ -1,7 +1,7 @@
import BaseModel, { ModelType } from '../BaseModel';
import shim from '../shim';
import eventManager, { EventName } from '../eventManager';
import { ItemChangeEntity } from '../services/database/types';
import { ItemChangeEntity, SqlQuery } from '../services/database/types';
const Mutex = require('async-mutex').Mutex;
export interface ChangeSinceIdOptions {
@ -31,9 +31,11 @@ export default class ItemChange extends BaseModel {
return BaseModel.TYPE_ITEM_CHANGE;
}
public static async add(itemType: ModelType, itemId: string, type: number, changeSource: any = null, beforeChangeItemJson: string = null) {
public static async addMulti(itemType: ModelType, itemIds: string[], type: number, changeSource: any = null, beforeChangeItemJsons: string[] = null) {
if (!itemIds.length) return;
if (changeSource === null) changeSource = ItemChange.SOURCE_UNSPECIFIED;
if (!beforeChangeItemJson) beforeChangeItemJson = '';
if (beforeChangeItemJsons && beforeChangeItemJsons.length !== itemIds.length) throw new Error('beforeChangeItemJsons does not match itemIds');
ItemChange.saveCalls_.push(true);
@ -42,28 +44,42 @@ export default class ItemChange extends BaseModel {
const release = await ItemChange.addChangeMutex_.acquire();
try {
await this.db().transactionExecBatch([
{
const queries: SqlQuery[] = [];
for (let i = 0; i < itemIds.length; i++) {
const itemId = itemIds[i];
const beforeChangeItemJson = beforeChangeItemJsons ? beforeChangeItemJsons[i] : '';
queries.push({
sql: 'DELETE FROM item_changes WHERE item_id = ?',
params: [itemId],
},
{
});
queries.push({
sql: 'INSERT INTO item_changes (item_type, item_id, type, source, created_time, before_change_item) VALUES (?, ?, ?, ?, ?, ?)',
params: [itemType, itemId, type, changeSource, Date.now(), beforeChangeItemJson],
},
]);
});
}
await this.db().transactionExecBatch(queries);
} finally {
release();
ItemChange.saveCalls_.pop();
eventManager.emit(EventName.ItemChange, {
itemType: itemType,
itemId: itemId,
eventType: type,
});
for (const itemId of itemIds) {
eventManager.emit(EventName.ItemChange, {
itemType: itemType,
itemId: itemId,
eventType: type,
});
}
}
}
public static async add(itemType: ModelType, itemId: string, type: number, changeSource: any = null, beforeChangeItemJson: string = null) {
await this.addMulti(itemType, [itemId], type, changeSource, beforeChangeItemJson ? [beforeChangeItemJson] : null);
}
public static async lastChangeId() {
const row = await this.db().selectOne('SELECT max(id) as max_id FROM item_changes');
return row && row.max_id ? row.max_id : 0;