iBoxDB - 6 days ago
// iBoxDB Node.js Embedded NoSQL Database example 
// ver 1.2

// Download source code to compile 
// if running on win-x64 or linux-x64, download the compiled file.
// https://sourceforge.net/projects/benchmarksql3/files/

// import classes
const { JsBox, JsBoxConfig, db_root, db_debug_deletefile, print, pause } = require("./_load_iboxdb.js")

// set the database's files directory
db_root("../DBRoot")

// set the database's address, a Number.
const address = 10

// if in Debug, delete the old files.
db_debug_deletefile(address)

// new database
let jsbox = new JsBox(address)

// a prototype object to define what types of the fields
const proto = { "id": BigInt(0), "value": String("_"), "ver": BigInt(0), "other_fields": "..." }

// setup database
let cfg = jsbox.get_config()
// setup table
cfg.ensure_table(proto, "table", "id")
// setup index, [optional].
let isUnique = false;
cfg.ensure_index(proto, "table", isUnique, "value(32)")
// setup a version field, [optional].
cfg.ensure_increment(proto, "table", "ver")
// setup cache, [optional].
cfg.cache_length(1024 * 1024 * 512)

// open the database to use
jsbox.open()

// copy field from prototype
let obj = { ...proto }
// modify field
let id = jsbox.new_id()
obj.id = id
obj.value = 'v_' + String(id)
// insert object to table
jsbox.insert("table", obj)
obj = null

// get object from table
obj = jsbox.get("table", id)
// print the object
print(obj)
//modify the object
obj.value += "++";
jsbox.update("table", obj)
obj = null

// use sql-like to query objects
let objs = jsbox.select("from table where id==?", id)
obj = objs[0]
print(obj)

// delete the object
jsbox.delete("table", obj.id)

//count the table
let size = jsbox.count("from table where id>?", 0n)
print(`${size}`)



obj = { ...proto }
// modify field
id = jsbox.new_id()
obj.id = id
obj.value = 'v_' + String(id)
// a Array field
obj.items = [{ "name": "ABC" }]
//replace =  insert or update
jsbox.replace("table", obj)
obj = null
let lastId = 0n
for (x of jsbox.select("from table")) {
    print(x)
    lastId = x.id
}

// add one more item
obj = jsbox.get("table", lastId)
obj.items.push({ "name": "DEF" })
jsbox.replace("table", obj)

for (x of jsbox.select("from table")) {
    print(x)
}

//close database
jsbox.close()

print("end.")
 

Last edit: iBoxDB 6 days ago