1 import assert from 'assert'
2 import fsPromises from 'fs/promises'
3 import Database from './Database.mjs'
4 import LazyValue from './LazyValue.mjs'
5 import LazyArray from './LazyArray.mjs'
6 import LazyObject from './LazyObject.mjs'
7 import logjson from './index.mjs'
10 constructor(database, value) {
11 assert(database instanceof Database)
12 this.database = database
18 let value = await this.database.read(ptr_len)
19 assert(typeof value === 'object' && value !== null)
21 value instanceof Array ?
22 new LazyArray(this, ptr_len, value) :
23 new LazyObject(this, ptr_len, value)
27 async get(default_value) {
28 if (this.value === undefined) {
29 if (default_value === undefined)
31 this.set(this.json_to_logjson(default_value))
34 if (this.value instanceof Array)
35 this.value = await this.read(this.value)
39 async get_json(default_value) {
40 return /*await*/ logjson.logjson_to_json(
41 await this.get(default_value)
48 typeof value !== 'object' ||
50 (value instanceof LazyValue && value.transaction === this)
56 this.set(this.json_to_logjson(value))
60 //console.log('commit transaction', this.serial)
61 assert(this.value !== undefined)
63 if (this.value instanceof LazyValue) {
64 if (await this.value.commit())
66 this.value = this.value.ptr_len
70 await this.database.write_root(this.value)
71 this.database.value = this.value
74 if (this.database.write_list_len && this.database.write_count === 0) {
75 if (this.database.write_timeout === 0)
76 await this.database.flush()
78 this.database.write_count = this.database.write_timeout
81 this.database.mutex.release()
85 //console.log('rollback transaction', this.serial)
86 this.database.mutex.release()
90 return new LazyArray(this, null, ...args)
94 return new LazyObject(this, null, ...args)
97 json_to_logjson(value) {
98 if (typeof value === 'object' && value !== null) {
100 if (value instanceof Array) {
101 new_value = new LazyArray(this)
102 for (let i = 0; i < value.length; ++i)
103 new_value.push(this.json_to_logjson(value[i]))
106 new_value = new LazyObject(this)
108 new_value.set(i, this.json_to_logjson(value[i]))
116 export default Transaction