MCPcopy
hub / github.com/electerm/electerm / action

Function action

test/unit/db-concurrency.spec.js:56–117  ·  view source on GitHub ↗
(dbName, op, ...args)

Source from the content-addressed store, hash-verified

54 }
55
56 async function action (dbName, op, ...args) {
57 if (op === 'compactDatafile') return
58 if (!tables.includes(dbName)) {
59 throw new Error(`Table ${dbName} does not exist`)
60 }
61 const db = getDatabase(dbName)
62 if (op === 'find') {
63 const stmt = db.prepare(`SELECT * FROM \`${dbName}\``)
64 const rows = stmt.all()
65 return (rows || []).map(row => {
66 const r = JSON.parse(row.data || '{}')
67 return { ...r, _id: row._id }
68 })
69 } else if (op === 'findOne') {
70 const query = args[0] || {}
71 const stmt = db.prepare(`SELECT * FROM \`${dbName}\` WHERE _id = ? LIMIT 1`)
72 const row = stmt.get(query._id)
73 if (!row) return null
74 const r = JSON.parse(row.data || '{}')
75 return { ...r, _id: row._id }
76 } else if (op === 'insert') {
77 const inserts = Array.isArray(args[0]) ? args[0] : [args[0]]
78 const inserted = []
79 for (const doc of inserts) {
80 const _id = doc._id || doc.id || uid()
81 const copy = { ...doc }
82 delete copy._id
83 delete copy.id
84 const data = JSON.stringify(copy)
85 const stmt = db.prepare(`INSERT OR REPLACE INTO \`${dbName}\` (_id, data) VALUES (?, ?)`)
86 stmt.run(_id, data)
87 inserted.push({ ...doc, _id })
88 }
89 return Array.isArray(args[0]) ? inserted : inserted[0]
90 } else if (op === 'remove') {
91 const query = args[0] || {}
92 const stmt = db.prepare(`DELETE FROM \`${dbName}\` WHERE _id = ?`)
93 const res = stmt.run(query._id)
94 return res.changes
95 } else if (op === 'update') {
96 const query = args[0]
97 const updateObj = args[1]
98 const options = args[2] || {}
99 const { upsert = false } = options
100 const qid = query._id || query.id
101 const newData = updateObj.$set || updateObj
102 const _id = qid
103 const copy = { ...newData }
104 delete copy._id
105 delete copy.id
106 const data = JSON.stringify(copy)
107 let res
108 if (upsert) {
109 const stmt = db.prepare(`REPLACE INTO \`${dbName}\` (_id, data) VALUES (?, ?)`)
110 res = stmt.run(_id, data)
111 } else {
112 const stmt = db.prepare(`UPDATE \`${dbName}\` SET data = ? WHERE _id = ?`)
113 res = stmt.run(data, qid)

Callers 12

simulateWatcherOldFunction · 0.85
createWatcherNewFunction · 0.85
ProfileFormElemFunction · 0.85
onDropFunction · 0.85
on-tree-drop.jsFile · 0.85
applyChangesMethod · 0.85
TabClass · 0.85
bookmark-upload.jsFile · 0.85
ItemListTreeClass · 0.85
tab.jsFile · 0.85
common.jsFile · 0.85
bookmark-group.jsFile · 0.85

Calls 4

uidFunction · 0.85
parseMethod · 0.80
getDatabaseFunction · 0.70
getMethod · 0.45

Tested by

no test coverage detected