{"id":17931,"library":"rik-database","title":"RIK Database ORM","description":"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.","status":"active","version":"1.4.5","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","database","typescript","PostgreSQL","ORM"],"install":[{"cmd":"npm install rik-database","lang":"bash","label":"npm"},{"cmd":"yarn add rik-database","lang":"bash","label":"yarn"},{"cmd":"pnpm add rik-database","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Underlying SQL query builder for database interactions. `rik-database` appears to wrap Knex.js functionality.","package":"knex","optional":false},{"reason":"PostgreSQL client driver, explicitly configured in the database settings (`client: 'pg'`).","package":"pg","optional":false}],"imports":[{"note":"Primary classes are imported as named exports. ESM is the standard, CJS 'require' may not work correctly or provide type inference.","wrong":"const { Version } = require('rik-database');","symbol":"Version","correct":"import { Version } from 'rik-database';"},{"note":"Configuration utility for setting database connection parameters. It's a named export, not a default.","wrong":"import DbSettings from 'rik-database';","symbol":"DbSettings","correct":"import { DbSettings } from 'rik-database';"},{"note":"Type-only imports for interfaces providing schema definition for models like NetworkInterfaceSettings. It's a named export.","symbol":"INetworkInterfaceSettings","correct":"import { INetworkInterfaceSettings } from 'rik-database';"},{"note":"Provides utilities like `Rik.raw()` for custom SQL expressions within queries.","symbol":"Rik","correct":"import { Rik } from 'rik-database';"}],"quickstart":{"code":"import { DbSettings, Version, IVersion, NetworkInterfaceSettings } from 'rik-database';\nimport { createRequire } from 'module';\n\n// Emulate CommonJS require for .env support in ESM context, or use dotenv directly\nconst require = createRequire(import.meta.url);\nrequire('dotenv').config();\n\nconst dbConfig = {\n    client: process.env.DB_CLIENT || 'pg',\n    connection: {\n        host: process.env.DB_HOST || 'localhost',\n        user: process.env.DB_USER || 'user',\n        password: process.env.DB_PASSWORD || 'password',\n        database: process.env.DB_NAME || 'databaseName',\n        port: process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : 5432\n    },\n    pool: {\n        min: 2,\n        max: 10\n    }\n};\n\n// Initialize database settings\nDbSettings.setConfig(dbConfig);\n\nclass DatabaseOperations {\n    public async demonstrateOperations(): Promise<void> {\n        console.log('--- Demonstrating RIK Database ORM Operations ---');\n\n        // Get current version data\n        let currentVersion = await Version.query().orderBy('id', 'desc').first();\n        console.log('\\n+------- Current Version -------+');\n        if (currentVersion) {\n            console.log(currentVersion);\n        } else {\n            console.log('Version table is empty. Adding initial version.');\n            const initialVersion: IVersion = { id: 1, name: 'Initial Version', number: '1.0.0', date: new Date().toISOString() };\n            await Version.query().insert(initialVersion);\n            currentVersion = await Version.query().orderBy('id', 'desc').first();\n            console.log(currentVersion);\n        }\n\n        // Add a new version\n        const newVersionData: IVersion = { name: 'Feature Update', number: '1.1.0', date: new Date().toISOString() };\n        const newVersion = await Version.query().insert(newVersionData);\n        console.log('\\nNew version has been added. Version ID:', newVersion.id);\n\n        // Update a version\n        if (currentVersion) {\n            const updatedVersionData: Partial<IVersion> = { name: 'Patched Feature Update' };\n            const updatedVersion = await Version.query().patchAndFetchById(newVersion.id, updatedVersionData);\n            console.log('\\nVersion has been updated. Version:', updatedVersion);\n        }\n\n        // Insert multiple network settings with model instantiation\n        try {\n            const settingsToInsert = [\n                new NetworkInterfaceSettings({\n                    name: 'eth0', method_name: 'dhcp', ip_address: '0.0.0.0', gateway: '0.0.0.0'\n                }),\n                new NetworkInterfaceSettings({\n                    name: 'eth1', method_name: 'static', ip_address: '192.168.1.100', gateway: '192.168.1.1'\n                })\n            ];\n            const insertedSettings = await NetworkInterfaceSettings.query().insert(settingsToInsert);\n            console.log('\\nInserted Network Settings:', insertedSettings);\n        } catch (error) {\n            console.error('[DatabaseOperations:demonstrateOperations]: Error inserting settings:', error);\n        }\n\n        // Delete a version\n        if (newVersion) {\n            const deletedCount = await Version.query().deleteById(newVersion.id);\n            console.log(`\\nDeleted ${deletedCount} version(s) with ID ${newVersion.id}.`);\n        }\n\n        console.log('\\n--- RIK Database ORM Operations Complete ---');\n    }\n}\n\n// To run this example, ensure you have a .env file with DB_CLIENT, DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT.\n// Example .env:\n// DB_CLIENT=pg\n// DB_HOST=localhost\n// DB_USER=myuser\n// DB_PASSWORD=mypassword\n// DB_NAME=mydb\n// DB_PORT=5432\n\nconst app = new DatabaseOperations();\napp.demonstrateOperations().catch(console.error);\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Review the source code and model definitions to understand the expected database schema. Be prepared to create a compatible schema or extend/modify the models for your specific project.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always check the release notes for `rik-database` for any mentions of underlying dependency updates. Pin exact versions of `rik-database`, `knex`, and `pg` to ensure stability and carefully test when upgrading.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Only use `Rik.raw()` with static SQL strings or with values that are guaranteed to be safe (e.g., from an allow-list). For dynamic values, use Knex's parameter binding capabilities within `Rik.raw()` or, preferably, the ORM's query builder methods.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always wrap database operations that need to be atomic within a transaction block. Ensure that `commit` is called on success and `rollback` is called in the event of any error (e.g., using `try...catch...finally` or `transaction.on('error')`). Consider using Knex's transaction helper for simpler transaction management.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Increase 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.","cause":"The database connection pool is exhausted, often due to long-running queries, unreleased connections, or missing `await` for database operations within transactions.","error":"KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?"},{"fix":"Verify 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.","cause":"The application could not establish a connection with the PostgreSQL server, typically due to incorrect host, port, firewall, or the database server not running.","error":"Error: connect ECONNREFUSED"},{"fix":"Ensure 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.","cause":"The database table corresponding to a model (e.g., `Version` expecting a 'versions' table) does not exist in the connected database.","error":"SQLSTATE[42P01]: Undefined table: 7 ERROR: relation \"table_name\" does not exist"},{"fix":"Inspect 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.","cause":"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.","error":"Undefined binding(s) detected when compiling UPDATE query. Set 'debug: true' in your Knex config to see the bindings."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}