const primaryKey = "id"; const allData: IItem[] = []; interface IItem { id?: number; timestamp: string; [key: string]: any; // 允许任意其他字段 } interface IPartialItem { id?: number; timestamp?: string; [key: string]: any; // 允许任意其他字段 } let key = 0; // 添加记录 function addRecord(data: IItem): IItem { const id = data.id ?? ++key; const existingIndex = allData.findIndex((v) => v.id === id); if (existingIndex === -1) { const newRecord = { id, ...data, timestamp: data.timestamp || String(Date.now()) }; allData.push(newRecord); return newRecord; } else { throw new Error(`Record with id ${id} already exists`); } } // 查询所有记录*- function getAllRecords(): IItem[] { return [...allData]; // 返回副本以避免外部修改 } // 根据ID查询单条记录 function getRecordById(id: number): IItem | undefined { return allData.find((v) => v.id === id); } // 更新记录 function updateRecord(id: number, updates: IPartialItem): IItem | undefined { const index = allData.findIndex((v) => v.id === id); if (index !== -1) { const updatedRecord = { ...allData[index], ...updates, id // 确保ID不会被更新 }; allData[index] = updatedRecord; return updatedRecord; } return undefined; } // 删除记录 function deleteRecord(id: number): boolean { const index = allData.findIndex((v) => v.id === id); if (index !== -1) { allData.splice(index, 1); return true; } return false; } // 查询记录 (简单条件) function queryRecords(conditions: IPartialItem): IItem[] { return allData.filter(item => { return Object.entries(conditions).every(([key, value]: any) => { return item[key] === value; }); }); } // 事务支持 function transaction(operations: (() => void)[]): boolean { const originalData = [...allData]; try { operations.forEach(op => op()); return true; } catch (error) { // 回滚 allData.length = 0; allData.push(...originalData); console.error('Transaction failed:', error); return false; } } // 示例使用 try { // 添加记录 addRecord({ timestamp: String(Date.now()), name: 'Item 1', price: 100 }); addRecord({ timestamp: String(Date.now()), name: 'Item 2', price: 200 }); // 更新记录 transaction([ () => updateRecord(1, { price: 150 }), () => addRecord({ timestamp: String(Date.now()), name: 'Item 3' }) ]); // 查询 const expensiveItems = queryRecords({ price: 200 }); console.log(expensiveItems); // 删除 deleteRecord(2); console.log(getAllRecords()); } catch (error) { console.error('Database operation failed:', error); }