RIK Database ORM
raw JSON →RIK Database is a TypeScript-first Object-Relational Mapper (ORM) designed specifically for a project named 'RIK'. It provides a structured, object-oriented interface for interacting with PostgreSQL databases, leveraging an underlying SQL query builder (likely Knex.js). The library offers models such as `Version`, `NetworkInterfaceSettings`, and `Plst`, along with associated interfaces, to manage database operations including querying, insertion, updating, and deletion. Currently at version 1.4.5, it appears to be actively maintained, offering type-safe interactions for its specific domain. Its key differentiator is its tailored design for the 'RIK' project, meaning it might come with predefined schema assumptions or conventions that align with that project's needs, distinguishing it from general-purpose ORMs.
Common errors
error KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call? ↓
DbSettings.setConfig (e.g., { pool: { min: 2, max: 20 } }). Ensure all database queries are awaited, 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 Error: connect ECONNREFUSED ↓
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. error SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "table_name" does not exist ↓
knex migrate:latest. If rik-database expects a specific schema, verify your database matches it. error Undefined binding(s) detected when compiling UPDATE query. Set 'debug: true' in your Knex config to see the bindings. ↓
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. Warnings
gotcha This library is explicitly designed for a 'specific project named RIK'. While it uses standard ORM patterns, its models and conventions might be tightly coupled to the RIK project's database schema, making it less suitable for general-purpose use without significant adaptation. ↓
breaking As `rik-database` is built on top of Knex.js, major version updates of the underlying Knex library or PostgreSQL driver (`pg`) can introduce breaking changes. Although `rik-database` abstracts this, internal changes might manifest as unexpected behavior or errors. ↓
gotcha Direct use of `Rik.raw()` for SQL expressions introduces a risk of SQL injection if user-provided input is not properly sanitized. This bypasses the ORM's built-in escaping mechanisms. ↓
gotcha Improper transaction management can lead to data inconsistencies or deadlocks. While `setSettingsWithTransaction` is shown, fully robust error handling with `rollback` and `commit` for all paths is crucial but not fully demonstrated in the excerpt. ↓
Install
npm install rik-database yarn add rik-database pnpm add rik-database Imports
- Version wrong
const { Version } = require('rik-database');correctimport { Version } from 'rik-database'; - DbSettings wrong
import DbSettings from 'rik-database';correctimport { DbSettings } from 'rik-database'; - INetworkInterfaceSettings
import { INetworkInterfaceSettings } from 'rik-database'; - Rik
import { Rik } from 'rik-database';
Quickstart
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);