Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Version
✓ import { Version } from 'rik-database';
✗ const { Version } = require('rik-database');
Primary classes are imported as named exports. ESM is the standard, CJS 'require' may not work correctly or provide type inference.
DbSettings
✓ import { DbSettings } from 'rik-database';
✗ import DbSettings from 'rik-database';
Configuration utility for setting database connection parameters. It's a named export, not a default.
INetworkInterfaceSettings
✓ import { INetworkInterfaceSettings } from 'rik-database';
Type-only imports for interfaces providing schema definition for models like NetworkInterfaceSettings. It's a named export.
Rik
✓ import { Rik } from 'rik-database';
Provides utilities like `Rik.raw()` for custom SQL expressions within queries.
This quickstart demonstrates basic CRUD (Create, Read, Update, Delete) operations using the `rik-database` ORM, including configuring the database connection, interacting with `Version` and `NetworkInterfaceSettings` models, and handling multiple inserts. It shows how to use named imports and instantiate models for data insertion.
import { DbSettings, Version, IVersion, NetworkInterfaceSettings } from 'rik-database';
import { createRequire } from 'module';
// Emulate CommonJS require for .env support in ESM context, or use dotenv directly
const require = createRequire(import.meta.url);
require('dotenv').config();
const dbConfig = {
client: process.env.DB_CLIENT || 'pg',
connection: {
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'user',
password: process.env.DB_PASSWORD || 'password',
database: process.env.DB_NAME || 'databaseName',
port: process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : 5432
},
pool: {
min: 2,
max: 10
}
};
// Initialize database settings
DbSettings.setConfig(dbConfig);
class DatabaseOperations {
public async demonstrateOperations(): Promise<void> {
console.log('--- Demonstrating RIK Database ORM Operations ---');
// Get current version data
let currentVersion = await Version.query().orderBy('id', 'desc').first();
console.log('\n+------- Current Version -------+');
if (currentVersion) {
console.log(currentVersion);
} else {
console.log('Version table is empty. Adding initial version.');
const initialVersion: IVersion = { id: 1, name: 'Initial Version', number: '1.0.0', date: new Date().toISOString() };
await Version.query().insert(initialVersion);
currentVersion = await Version.query().orderBy('id', 'desc').first();
console.log(currentVersion);
}
// Add a new version
const newVersionData: IVersion = { name: 'Feature Update', number: '1.1.0', date: new Date().toISOString() };
const newVersion = await Version.query().insert(newVersionData);
console.log('\nNew version has been added. Version ID:', newVersion.id);
// Update a version
if (currentVersion) {
const updatedVersionData: Partial<IVersion> = { name: 'Patched Feature Update' };
const updatedVersion = await Version.query().patchAndFetchById(newVersion.id, updatedVersionData);
console.log('\nVersion has been updated. Version:', updatedVersion);
}
// Insert multiple network settings with model instantiation
try {
const settingsToInsert = [
new NetworkInterfaceSettings({
name: 'eth0', method_name: 'dhcp', ip_address: '0.0.0.0', gateway: '0.0.0.0'
}),
new NetworkInterfaceSettings({
name: 'eth1', method_name: 'static', ip_address: '192.168.1.100', gateway: '192.168.1.1'
})
];
const insertedSettings = await NetworkInterfaceSettings.query().insert(settingsToInsert);
console.log('\nInserted Network Settings:', insertedSettings);
} catch (error) {
console.error('[DatabaseOperations:demonstrateOperations]: Error inserting settings:', error);
}
// Delete a version
if (newVersion) {
const deletedCount = await Version.query().deleteById(newVersion.id);
console.log(`\nDeleted ${deletedCount} version(s) with ID ${newVersion.id}.`);
}
console.log('\n--- RIK Database ORM Operations Complete ---');
}
}
// To run this example, ensure you have a .env file with DB_CLIENT, DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT.
// Example .env:
// DB_CLIENT=pg
// DB_HOST=localhost
// DB_USER=myuser
// DB_PASSWORD=mypassword
// DB_NAME=mydb
// DB_PORT=5432
const app = new DatabaseOperations();
app.demonstrateOperations().catch(console.error);
Errors
Common errors & fixes
KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
The database connection pool is exhausted, often due to long-running queries, unreleased connections, or missing `await` for database operations within transactions.
fixIncrease the connection pool size in `DbSettings.setConfig` (e.g., `{ pool: { min: 2, max: 20 } }`). Ensure all database queries are `await`ed, especially within `Promise.all()`. For transactions, make sure `transacting(trx)` is correctly applied to all queries within that transaction, and the transaction is explicitly committed or rolled back. Error: connect ECONNREFUSED
The application could not establish a connection with the PostgreSQL server, typically due to incorrect host, port, firewall, or the database server not running.
fixVerify that `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, and `DB_NAME` in your `.env` or configuration are correct. Ensure the PostgreSQL server is running and accessible from the application's environment. Check firewall rules blocking the connection.
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "table_name" does not exist
The database table corresponding to a model (e.g., `Version` expecting a 'versions' table) does not exist in the connected database.
fixEnsure your database schema has been created and migrated correctly. If using Knex migrations, run `knex migrate:latest`. If `rik-database` expects a specific schema, verify your database matches it.
Undefined binding(s) detected when compiling UPDATE query. Set 'debug: true' in your Knex config to see the bindings.
A query is attempting to use a variable or object property that is `undefined` as a binding value in an update or insert operation, often due to typos or missing data.
fixInspect the data object being passed to `insert`, `update`, or `patch` methods. Ensure all properties intended for database columns have defined values and match the expected types. Add `debug: true` to the Knex configuration for more detailed error messages.
Audit
Dependencies
knexrequiredUnderlying SQL query builder for database interactions. `rik-database` appears to wrap Knex.js functionality.
pgrequiredPostgreSQL client driver, explicitly configured in the database settings (`client: 'pg'`).