VesperDB
A flexible, portable, and easy-to-use SQL query builder for Node.js
Features
- Support for multiple SQL dialects (PostgreSQL, MySQL, SQLite, MSSQL)
- Fluent API for query building
- Transactions
- Connection pooling
- Promise API
- Schema building and migrations
- Raw queries
New Features
Schema Validation
VesperDB now includes a robust schema validation system that allows you to validate your data before inserting or updating it in the database
const userSchema = db.Schema.create({
type: db.Schema.TYPES.OBJECT,
properties: {
id: { type: db.Schema.TYPES.UUID, required: true },
name: { type: db.Schema.TYPES.STRING, minLength: 2 },
email: { type: db.Schema.TYPES.EMAIL, required: true }
}
});
const result = userSchema.validate(data);
if (result.valid) {
} else {
console.error(result.errors);
}
await db('users')
.insert(data)
.validateSchema(userSchema)
.run();
Advanced JSON Operations
VesperDB now offers advanced support for JSON operations, particularly useful with PostgreSQL and its JSONB type
const result = await db.json.get('products', 'details', 'brand', { id: 1 });
await db.json.set('products', 'details', 'specifications.ram', '16GB', { id: 1 });
const exists = await db.json.exists('products', 'details', 'specifications.storage', { id: 1 });
await db.json.append('products', 'details', 'colors', 'red', { id: 1 });
await db.json.merge('products', 'details', { price: 999, available: true }, { id: 1 });
await db.json.remove('products', 'details', 'oldField', { id: 1 });
const products = await db.json.contains('products', 'details', 'red', 'colors').select().run();
Intelligent Query Cache
VesperDB integrates a caching system that significantly improves the performance of repeated queries
const db = VesperDB({
client: 'pg',
connection: { },
cache: {
enabled: true,
options: {
max: 500,
ttl: 60000
}
}
});
const users = await db('users').select().where('active', true).run();
await db('users').update({ active: false }).where('id', 1).run();
const stats = db.cache.getStats();
console.log(`Hit rate: ${stats.hitRate}%`);
db.cache.clear();
db.cache.invalidateByTables(['users']);
Installation
npm install vesperdb
Basic Usage
const vesperDB = require('vesperdb');
const db = vesperDB({
client: 'pg',
connection: {
host: 'localhost',
user: 'username',
password: 'password',
database: 'mydatabase'
}
});
async function getUsers() {
return await db('users')
.select('id', 'name', 'email')
.where('active', true)
.orderBy('name', 'asc');
}
async function createUser(user) {
return await db('users').insert(user);
}
async function updateUser(id, data) {
return await db('users')
.where('id', id)
.update(data);
}
async function deleteUser(id) {
return await db('users')
.where('id', id)
.delete();
}
async function getPostsWithAuthors() {
return await db('posts')
.join('users', 'posts.user_id', '=', 'users.id')
.select(
'posts.id',
'posts.title',
'users.name as author'
);
}
Schema and Migrations
await db.schema.createTable('users', (table) => {
table.increments('id');
table.string('name', 100).notNullable();
table.string('email', 100).notNullable();
table.integer('age');
table.boolean('active').defaultTo(true);
table.timestamp('created_at').defaultTo(new Date());
table.unique('email');
table.index('name');
});
await db.schema.alterTable('users', (table) => {
table.string('phone', 20);
});
await db.schema.dropTable('users');
Transactions
await db.transaction(async (trx) => {
const userId = await trx('users').insert({
name: 'John Doe',
email: 'john@example.com'
});
await trx('profiles').insert({
user_id: userId,
bio: 'My biography...'
});
});
Query Building API
SELECT
db('users');
db('users').select('name', 'email');
db('users').where('id', 1);
db('users').where('id', 1).where('active', true);
db('users').where('id', 1).orWhere('id', 2);
db('users').limit(10).offset(20);
db('users').orderBy('name', 'asc').orderBy('age', 'desc');
INSERT
db('users').insert({
name: 'John',
email: 'john@example.com'
});
db('users').insert([
{ name: 'John', email: 'john@example.com' },
{ name: 'Mary', email: 'mary@example.com' }
]);
UPDATE
db('users')
.where('id', 1)
.update({ email: 'new@example.com' });
DELETE
db('users')
.where('id', 1)
.delete();
JOIN
db('posts')
.join('users', 'posts.user_id', 'users.id')
.select('posts.*', 'users.name');
db('posts')
.leftJoin('comments', 'posts.id', 'comments.post_id')
.select('posts.*', 'comments.content');
Column Types
VesperDB supports several column types for schema definition:
table.increments('id')
- INTEGER AUTO_INCREMENT
table.integer('age')
- INTEGER
table.text('description')
- TEXT
table.string('name', 100)
- VARCHAR(100)
table.float('score')
- FLOAT
table.decimal('price', 8, 2)
- DECIMAL(8,2)
table.boolean('active')
- BOOLEAN
table.date('birth_date')
- DATE
table.datetime('appointment')
- DATETIME/TIMESTAMP
table.timestamp('created_at')
- TIMESTAMP