Created
March 9, 2024 19:40
-
-
Save borissov/25be4762d46400448567a51999795835 to your computer and use it in GitHub Desktop.
Simple MVCC Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MVCCDatabase { | |
constructor() { | |
this.data = {}; | |
this.versions = {}; | |
} | |
async read(key, transactionId) { | |
// Simulate read operation with MVCC | |
if (this.versions[key]) { | |
const version = this.versions[key].find(v => v.transactionId <= transactionId); | |
if (version) { | |
return version.value; | |
} | |
} | |
return null; // Key not found or not visible to the transaction | |
} | |
async write(key, value, transactionId) { | |
// Simulate write operation with MVCC | |
if (!this.versions[key]) { | |
this.versions[key] = []; | |
} | |
this.versions[key].push({ transactionId, value }); | |
// Update the latest value in the data store | |
this.data[key] = value; | |
} | |
async commit(transactionId) { | |
// Commit the transaction by removing old versions | |
for (const key of Object.keys(this.versions)) { | |
this.versions[key] = this.versions[key].filter(v => v.transactionId > transactionId); | |
} | |
} | |
} | |
async function exampleTransaction(database, transactionId) { | |
await database.write('foo', 'initial', transactionId); | |
console.log(await database.read('foo', transactionId)); // Should print 'initial' | |
// Another transaction writes to the same key | |
setTimeout(async () => { | |
await database.write('foo', 'updated', transactionId + 1); | |
console.log(await database.read('foo', transactionId)); // Should still print 'initial' | |
}, 100); | |
// Commit the transaction | |
await database.commit(transactionId); | |
console.log(await database.read('foo', transactionId)); // Should still print 'initial' | |
} | |
(async () => { | |
const db = new MVCCDatabase(); | |
await exampleTransaction(db, 1); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment