Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Basalt

basaltdb — JavaScript/TypeScript client for Basalt

Use Basalt from Node or the browser. Two modes, one API:

  • Embedded (in-process, WebAssembly — like sql.js): the whole engine runs in your process, no server. The database lives in memory. Great for tests, demos, notebooks, and browser apps.
  • Client/server: talk to a running basalt server over HTTP for a persistent, disk-backed database.

The WASM binary is bundled inside the package (single file, base64-embedded), so there are no extra assets to host or fetch — it just works in Node and bundlers.

npm install basaltdb

Embedded (in-process)

import { Basalt } from 'basaltdb';

const db = await Basalt.create();            // in-memory, seeded with a demo dataset
db.exec('CREATE TABLE t (id BIGINT PRIMARY KEY, name VARCHAR, qty INT)');
db.exec("INSERT INTO t (id, name, qty) VALUES (1, 'widget', 5)");

db.query('SELECT * FROM t');                 // -> [{ id: 1, name: 'widget', qty: 5 }]
const r = db.exec('SELECT COUNT(*) AS c FROM t');
console.log(r.stats.ms, r.stats.access);     // timing + access method

exec() returns the full result object: { columns, types, rows, total_rows, truncated, stats, plan, message? }, plus .toObjects(). query() is shorthand for exec(sql).toObjects().

Client/server (HTTP)

import { BasaltClient } from 'basaltdb';

const db = new BasaltClient('http://127.0.0.1:8090', { db: 'mydb' });
await db.query('SELECT * FROM users ORDER BY id');
await db.databases();                        // list served databases
await db.schema();                           // tables + columns

In Node < 18 (no global fetch) pass one: new BasaltClient(url, { fetch }).

Need a server? The client/server mode talks to a running Basalt server. Set up and run the database engine from the main repo — basalt-db/basalt → Quickstart:

git clone https://github.com/basalt-db/basalt.git && cd basalt
make basalt-server
./basalt-server demo_root 8090     # HTTP API + Workbench on http://127.0.0.1:8090

(The embedded mode above needs no server — the engine runs in-process.)

Query builder (ORM-lite)

A small fluent builder that generates SQL. It works the same on both Basalt (sync) and BasaltClient (async) — await works in both cases:

await db.table('users').select('id', 'name').where('tier', '>', 1).orderBy('id', 'DESC').all();
await db.table('users').where('id', 1).first();
db.table('users').insert({ id: 4, name: 'dana', tier: 2 });
db.table('users').insert([{ id: 5, name: 'e' }, { id: 6, name: 'f' }]);
db.table('users').where('id', 6).update({ tier: 3 });
db.table('users').where('id', 6).delete();

Values are escaped (lit()); identifiers are never taken from user input. Call .toSQL() on any builder to see the generated statement.

Models (lightweight ORM)

Define a table as a model and do typed CRUD without hand-writing SQL. All model methods return Promises and work the same embedded or over HTTP.

import { Basalt } from 'basaltdb';
const db = await Basalt.create();

const User = db.model('users', {
  id:     { type: 'BIGINT', primaryKey: true },
  name:   'string',                       // string → VARCHAR
  tier:   { type: 'int', index: true },   // creates a secondary index on sync()
  active: 'boolean',
  joined: 'date',
});

await User.sync();                                  // CREATE TABLE (+ index) if absent
await User.insert([{ id: 1, name: 'alice', tier: 1, active: true, joined: '2024-01-02' },
                   { id: 2, name: 'bob',   tier: 2, active: false }]);

await User.find({ tier: 2 }, { orderBy: ['id', 'DESC'], limit: 10 });
await User.find({ tier: [1, 2] });                  // array → IN (expanded to OR)
await User.find({ id: { '>=': 1, '<': 100 } });     // operators
await User.findByPk(1);
await User.count({ active: true });
await User.update({ tier: 3 }, { id: 2 });
await User.delete({ id: 2 });
User.toCreateSQL();                                 // inspect the DDL

Where-spec: { col: value } (equality), { col: [a, b] } (IN), or { col: { op: value } } where op= != <> > >= < <= eq ne gt gte lt lte in between. Multiple keys are AND-ed. Types accept SQL names (BIGINT, VARCHAR, DECIMAL, TIMESTAMP, …) or friendly aliases (string, int, bool, date, datetime).

See ORM.md for what the model layer does and does not do compared to mongoose / Sequelize / Prisma, and why (it's honest about the gaps that come from the young engine).

What Basalt supports (and doesn't, yet)

This is a young, learning-oriented engine — the builder deliberately stays close to what the SQL engine actually does:

  • SELECT with WHERE / GROUP BY / aggregates / ORDER BY / LIMIT, INNER/LEFT JOIN, INSERT (positional or column-list), UPDATE, DELETE, CREATE/DROP TABLE, CREATE/DROP INDEX.
  • ⛔ No transactions, no subqueries/CTEs/window functions, no prepared statements yet (see the roadmap). That's why this is a query builder rather than a full ORM adapter — a Prisma / Sequelize / Drizzle dialect will land once transactions and richer SQL do.

API

  • Basalt.create()Promise<Basalt> — embedded in-memory engine.
  • db.exec(sql)Result · db.query(sql)object[] · db.schema() → tables.
  • new BasaltClient(url, { db, fetch }) — async exec / query / databases / schema / createDatabase / dropDatabase / use(db).
  • db.table(name) → builder: select, where, orderBy, limit, all, first, insert, update, delete, toSQL.
  • lit(value) — SQL literal formatting; BasaltError — thrown on engine errors.

Building src/engine.js

src/engine.js is the Basalt C++ engine compiled to a single-file ESM WebAssembly bundle (base64-embedded), vendored here so npm install needs no toolchain. It's generated from the engine sources in the main Basalt repo (src/) with emscripten:

# in a checkout of basalt-db/basalt
emcc -std=c++17 -O3 -fexceptions -I src \
  src/logical.cpp src/storage.cpp src/sql.cpp src/exec.cpp \
  src/exec_join.cpp src/database.cpp src/wasm.cpp \
  -sMODULARIZE=1 -sEXPORT_ES6=1 -sSINGLE_FILE=1 -sENVIRONMENT=web,node \
  -sEXPORT_NAME=createBasalt -sEXPORTED_RUNTIME_METHODS=ccall,cwrap \
  -sEXPORTED_FUNCTIONS=_hydb_exec,_hydb_schema,_hydb_init,_malloc,_free \
  -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=64MB -o engine.js
# then copy engine.js -> this repo's src/engine.js

Run the smoke test (embedded engine, no server): npm test.

MIT. Part of the Basalt project.

About

Official JavaScript/TypeScript client for Basalt — embedded WASM engine + HTTP client + query builder (npm: basaltdb)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages