### Start db-model-router development server Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md After scaffolding and configuring your .env file, start the development server using this command. ```bash npm run dev ``` -------------------------------- ### Start DB Manager with SQLite Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Launch the DB Manager for SQLite. No Docker is required for this setup. ```bash npx db-model-router db-manager --env ./db-manager/demo/sqlite3.env ``` -------------------------------- ### Install db-model-router with Oracle Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the core package and the Oracle database driver. ```bash npm install db-model-router oracledb ``` -------------------------------- ### Install db-model-router with DynamoDB Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the core package and the DynamoDB database drivers. ```bash npm install db-model-router @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb ``` -------------------------------- ### Install db-model-router with SQLite3 Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the core package and the SQLite3 database driver. ```bash npm install db-model-router better-sqlite3 ``` -------------------------------- ### Install db-model-router with framework and driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install the db-model-router package along with the necessary framework and database driver. The specific driver depends on the chosen database adapter. ```bash npm install db-model-router ``` -------------------------------- ### Install db-model-router with Redis Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the core package and the Redis database driver. ```bash npm install db-model-router ioredis ``` -------------------------------- ### Initialize Project with Options Source: https://context7.com/avinashskaranth/db-model-router/llms.txt Scaffolds a new project with specified framework, database, session, and security features. Use --yes for non-interactive setup. ```bash db-model-router init \ --framework express \ --database postgres \ --session redis \ --rateLimiting \ --helmet \ --logger \ --yes ``` ```bash db-model-router init --database postgres --logger --loki --yes ``` ```bash db-model-router init --from dbmr.schema.json --yes --no-install ``` ```bash db-model-router init --from dbmr.schema.json --dry-run ``` -------------------------------- ### Install db-model-router with ioredis driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `ioredis` driver for the Redis database adapter. ```bash npm i db-model-router ioredis ``` -------------------------------- ### Scaffold a new db-model-router project interactively Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Use the CLI to interactively scaffold a new project. This is the fastest way to start. ```bash npx db-model-router init ``` -------------------------------- ### Initialize and Connect to Oracle Database Source: https://github.com/avinashskaranth/db-model-router/blob/master/docs/adapters/oracle.md Initializes the router with the Oracle adapter and establishes a connection to the database using provided credentials. Ensure Oracle Instant Client is installed. ```javascript const { init, db, model, route } = require("db-model-router"); init("oracle"); db.connect({ host: "localhost", port: 1521, database: "XEPDB1", user: "system", password: "oracle", }); ``` -------------------------------- ### Install ultimate-express and db-model-router with PostgreSQL Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the high-performance ultimate-express framework and the PostgreSQL database driver. ```bash npm install ultimate-express npm install db-model-router pg ``` -------------------------------- ### Start All Docker Services Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Initiate all database containers defined in the Docker Compose file. ```bash docker compose up -d ``` -------------------------------- ### Install db-model-router with mssql driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `mssql` driver for the MSSQL database adapter. ```bash npm i db-model-router mssql ``` -------------------------------- ### Install Express and db-model-router with MySQL Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the core package, Express framework, and the MySQL database driver. ```bash npm install express npm install db-model-router mysql2 ``` -------------------------------- ### Install db-model-router with mongodb driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `mongodb` driver for the MongoDB database adapter. ```bash npm i db-model-router mongodb ``` -------------------------------- ### Install db-model-router with oracledb driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `oracledb` driver for the Oracle database adapter. ```bash npm i db-model-router oracledb ``` -------------------------------- ### Install db-model-router with pg driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `pg` driver for PostgreSQL or CockroachDB database adapters. ```bash npm i db-model-router pg ``` -------------------------------- ### Start Database Manager UI Source: https://context7.com/avinashskaranth/db-model-router/llms.txt Launches a local web UI for database management, including browsing tables, editing data, running SQL queries, and viewing history. Reads configuration from .env. ```bash # Start on default port 4000 db-model-router db-manager --env .env ``` -------------------------------- ### Install db-model-router with better-sqlite3 driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `better-sqlite3` driver for the SQLite3 database adapter. ```bash npm i db-model-router better-sqlite3 ``` -------------------------------- ### Start Specific Docker Service Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start a single database service container using Docker Compose. ```bash docker compose up -d mysql ``` ```bash docker compose up -d postgres ``` ```bash docker compose up -d mssql ``` ```bash docker compose up -d mongodb ``` ```bash docker compose up -d redis ``` ```bash docker compose up -d cockroachdb ``` ```bash docker compose up -d oracle ``` ```bash docker compose up -d dynamodb ``` -------------------------------- ### Install KafkaJS Driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Install the necessary Kafka client library using npm. This is a prerequisite for enabling Kafka event production. ```bash npm install kafkajs ``` -------------------------------- ### Install db-model-router with mysql2 driver Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the `mysql2` driver for MySQL or MariaDB database adapters. ```bash npm i db-model-router mysql2 ``` -------------------------------- ### Get DB Model Router Help Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md The 'help' command provides general overview and detailed help for specific commands. You can get help for a command directly or by appending '--help' to a command. ```bash db-model-router help # general overview with per-command flags ``` ```bash db-model-router help init # detailed help for init ``` ```bash db-model-router init --help # same as above ``` -------------------------------- ### Launch DB Manager UI Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Start the built-in database management UI with the `db-manager` command. Specify the environment file with `--env` and the port with `--port`. ```bash db-model-router db-manager [--env .env] [--port 4000] ``` -------------------------------- ### Install db-model-router with AWS SDK drivers for DynamoDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install db-model-router and the necessary AWS SDK packages (`@aws-sdk/client-dynamodb` and `@aws-sdk/lib-dynamodb`) for the DynamoDB database adapter. ```bash npm i db-model-router @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb ``` -------------------------------- ### Initialize and Connect to CockroachDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/references/cockroachdb.md Initializes the db-model-router for CockroachDB and establishes a connection using provided credentials. Ensure the 'pg' driver is installed. ```javascript const { init, db, model, route } = require("db-model-router"); init("cockroachdb"); db.connect({ host: "localhost", port: 26257, database: "defaultdb", user: "root", password: "", }); ``` -------------------------------- ### Launch DB Manager for PostgreSQL Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to a PostgreSQL database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/postgres.env ``` -------------------------------- ### Launch DB Manager for DynamoDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to a DynamoDB database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/dynamodb.env ``` -------------------------------- ### Launch DB Manager for Oracle Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to an Oracle database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/oracle.env ``` -------------------------------- ### Launch DB Manager for MongoDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to a MongoDB database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/mongodb.env ``` -------------------------------- ### Launch DB Manager for MySQL Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to a MySQL database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/mysql.env ``` -------------------------------- ### Launch DB Manager for CockroachDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to a CockroachDB database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/cockroachdb.env ``` -------------------------------- ### Launch DB Manager for Redis Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to a Redis database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/redis.env ``` -------------------------------- ### Launch DB Manager for MSSQL Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Start the DB Manager connected to an MSSQL database using its environment file. ```bash npx db-model-router db-manager --env ./db-manager/demo/mssql.env ``` -------------------------------- ### Example dbmr.schema.json Structure Source: https://context7.com/avinashskaranth/db-model-router/llms.txt An example JSON schema file defining database adapter, framework, options, and table structures including columns, primary keys, and relationships. ```json { "adapter": "postgres", "framework": "express", "options": { "session": "redis", "rateLimiting": true, "helmet": true, "logger": true }, "tables": { "products": { "columns": { "product_id": "auto_increment", "name": "required|string", "price": "required|numeric", "stock": "required|integer", "is_deleted": "boolean", "created_at": "datetime", "updated_at": "datetime" }, "pk": "product_id", "unique": ["name"], "softDelete": "is_deleted", "timestamps": { "created_at": "created_at", "modified_at": "updated_at" }, "parent": null }, "reviews": { "columns": { "review_id": "auto_increment", "product_id": "required|integer", "user_id": "required|integer", "rating": "required|integer", "body": "string" }, "pk": "review_id", "unique": ["review_id"], "parent": "products" } } } ``` -------------------------------- ### Install KafkaJS for Kafka Integration Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Install the `kafkajs` package as a peer dependency if you plan to use the built-in Kafka event production feature. This is only required when a `KAFKA_BROKER` environment variable is set. ```bash npm install kafkajs ``` -------------------------------- ### Seed SQLite Database Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Use this command to seed the demo SQLite database before starting the DB Manager. ```bash sqlite3 ./db-manager/demo/demo.sqlite < ./db-manager/demo/seeds/sqlite3.sql ``` -------------------------------- ### Scaffold a new db-model-router project from schema file Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Generate a new project non-interactively using a schema file. Includes options to skip installation. ```bash db-model-router init --from dbmr.schema.json --yes --no-install ``` -------------------------------- ### Run Kafka Docker Compose Services Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Deploy Zookeeper, Kafka, and Kafka UI using Docker Compose. This command starts the necessary services for a local Kafka environment. ```bash docker compose up -d zookeeper kafka kafka-ui ``` -------------------------------- ### DBMR Schema Configuration Example Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md This JSON defines the database adapter, framework, and options, including session management, rate limiting, and security middleware. It also outlines table structures with columns, primary keys, unique constraints, soft deletes, and timestamps. ```json { "adapter": "postgres", "framework": "express", "options": { "session": "redis", "rateLimiting": true, "helmet": true, "logger": true }, "tables": { "users": { "columns": { "user_id": "auto_increment", "name": "required|string", "email": "required|string", "is_deleted": "boolean", "created_at": "datetime", "updated_at": "datetime" }, "pk": "user_id", "unique": ["email"], "softDelete": "is_deleted", "timestamps": { "created_at": "created_at", "modified_at": "updated_at" }, "parent": null }, "posts": { "columns": { "post_id": "auto_increment", "title": "required|string", "user_id": "required|integer", "created_at": "datetime" }, "pk": "post_id", "unique": ["post_id"], "parent": null }, "comments": { "columns": { "comment_id": "auto_increment", "post_id": "required|integer", "user_id": "required|integer", "body": "required|string" }, "pk": "comment_id", "unique": ["comment_id"], "parent": "posts" } } } ``` -------------------------------- ### Create DynamoDB Table using AWS CLI Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/references/dynamodb.md Example command to create a DynamoDB table named 'users' with a primary key 'id' of type String. It configures the table for provisioned throughput and sets the endpoint URL for local DynamoDB. ```bash aws dynamodb create-table \ --table-name users \ --attribute-definitions AttributeName=id,AttributeType=S \ --key-schema AttributeName=id,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --endpoint-url http://localhost:8000 ``` -------------------------------- ### Initialize and Connect to a Database Adapter Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Call `init()` with the desired adapter name before `db.connect()` to switch databases. Connection options vary per adapter. ```javascript const { init, db, model, route } = require("db-model-router"); init("postgres"); // or "mongodb", "sqlite3", "mssql", etc. db.connect({ host: "localhost", port: 5432, user: "postgres", password: "password", database: "my_app", }); ``` -------------------------------- ### Initialization and Connection Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Demonstrates the correct order for initializing the library and connecting to the database. Emphasizes calling `init()` before `db.connect()`. ```APIDOC ## Initialization and Connection ### Description Initialize the library and connect to the database. Ensure `init()` is called before `db.connect()`. ### Usage ```js // CJS const { init, db, model, route } = require("db-model-router"); // ESM (generated projects) import dbModelRouter from "db-model-router"; const { init, db, model, route } = dbModelRouter; init("postgres"); // Call BEFORE db.connect() db.connect({ host, port: 5432, user, password, database }); ``` ### Critical Notes - Call `init()` before `db.connect()`. - Default adapter is `mysql`. - Do NOT destructure `db` before `init()` as it is a getter. ``` -------------------------------- ### Initialize Project with Dry Run Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Use the `init` command with the `--dry-run` flag to preview the generated project structure without creating actual files. Specify the schema file using `--from`. ```bash db-model-router init --from dbmr.schema.json --dry-run ``` -------------------------------- ### CLI Reference - init Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Scaffolds a new project using the `init` command. Supports various configurations for frameworks, databases, and additional features. ```APIDOC ## CLI Reference ```bash db-model-router [options] db-model-router help ``` ### `init` — Scaffold project ```bash # Fully non-interactive (LLM-friendly) db-model-router init --framework express --database postgres --session redis \ --rateLimiting --helmet --logger --yes # With Loki/Grafana logging db-model-router init --database postgres --logger --loki --yes # From schema file db-model-router init --from dbmr.schema.json --yes --no-install ``` Key flags: `--framework`, `--database` (or `--db`), `--session`, `--output`, `--rateLimiting`, `--helmet`, `--logger`, `--loki`, `--yes`, `--no-install` Generated structure (ESM, `"type":"module"`): ``` app.js Express entry point .env / .env.example Env config (random passwords) docker-compose.yml DB + CloudBeaver + optional Loki/Grafana /commons/db.js Database init + global.db /commons/migrate.js Migration runner /route/index.js Central route mounting /route/health.js GET /health endpoint /migrations/ Initial migration files ``` Docker services auto-generated: database, Redis (if session=redis), CloudBeaver (SQL/MongoDB, port 8978), Loki + Grafana (if --loki). Scripts: `start`, `dev`, `test`, `migrate`, `add_migration`, `docker:build`, `docker:up`, `docker:down`. ``` -------------------------------- ### CLI: Initialize Project Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Scaffolds a new project using the db-model-router CLI. Supports various configurations for frameworks, databases, sessions, logging, and more. ```bash db-model-router init --framework express --database postgres --session redis \ --rateLimiting --helmet --logger --yes ``` ```bash db-model-router init --database postgres --logger --loki --yes ``` ```bash db-model-router init --from dbmr.schema.json --yes --no-install ``` -------------------------------- ### Initialize Project with Loki Logging Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Scaffold a new project with a specified database and enable both request logging and Grafana Loki integration. The `--yes` flag bypasses interactive prompts. ```bash db-model-router init --database postgres --logger --loki --yes ``` -------------------------------- ### Initialize Project Non-Interactively Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Scaffold a new project with specified framework, database, and output directory. The `--yes` flag bypasses interactive prompts. ```bash db-model-router init --framework express --database postgres --output backend --yes ``` -------------------------------- ### Kafka Initialization Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Demonstrates how to initialize the Kafka producer, either automatically using environment variables or explicitly with options. ```APIDOC ## Initialize Kafka Producer ```js import dbModelRouter from "db-model-router"; const { init, db, kafka } = dbModelRouter; init("postgres"); db.connect({ host: "localhost", database: "my_app" }); // Connect Kafka producer await kafka.init(); // Or with explicit options: await kafka.init({ broker: "localhost:9092", clientId: "my-app", topicPrefix: "dbmr", }); ``` ``` -------------------------------- ### Initialize DB Model Router with Various Database Adapters Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Use the `init` and `db.connect` methods to establish connections to different database types. Ensure correct connection parameters are provided for each adapter. Note that MSSQL's `db.connect` is asynchronous and requires `await`. ```javascript // MySQL / MariaDB (default adapter) init("mysql"); db.connect({ host, port: 3306, user, password, database, connectionLimit: 100, }); // PostgreSQL — see references/postgres.md init("postgres"); db.connect({ host, port: 5432, user, password, database }); // SQLite3 — see references/sqlite3.md init("sqlite3"); db.connect({ database: "./file.db" }); // or ":memory:" // MongoDB — see references/mongodb.md init("mongodb"); db.connect({ host, port: 27017, username, password, database }); // or: db.connect({ uri: "mongodb://user:pass@host:27017/db" }) // MSSQL — see references/mssql.md (db.connect is async — use await) init("mssql"); await db.connect({ server: host, port: 1433, user, password, database, options: { encrypt: false, trustServerCertificate: true }, }); // Oracle — see references/oracle.md init("oracle"); db.connect({ host, port: 1521, user, password, database }); // Redis — see references/redis.md init("redis"); db.connect({ host, port: 6379, password }); // DynamoDB — see references/dynamodb.md init("dynamodb"); db.connect({ region, endpoint, accessKeyId, secretAccessKey }); // CockroachDB — see references/cockroachdb.md init("cockroachdb"); db.connect({ host, port: 26257, user, password, database }); ``` -------------------------------- ### Initialize and Connect to MSSQL Database Source: https://github.com/avinashskaranth/db-model-router/blob/master/docs/adapters/mssql.md Initializes the MSSQL adapter and establishes a connection to the database. Use 'await' as db.connect() is asynchronous for MSSQL. ```javascript const { init, db, model, route } = require("db-model-router"); init("mssql"); await db.connect({ server: "localhost", port: 1433, database: "master", user: "sa", password: "Password123!", options: { encrypt: false, trustServerCertificate: true, }, }); ``` -------------------------------- ### Quick Workflow: Introspect and Generate Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Steps to introspect an existing database, generate artifacts from the schema, and verify synchronization. ```bash # 1. Introspect an existing database into a schema file db-model-router inspect --type postgres --env .env # 2. (Optional) Edit dbmr.schema.json to add relationships, tweak columns, etc. # 3. Generate all artifacts from the schema db-model-router generate --from dbmr.schema.json # 4. Check everything is in sync db-model-router doctor --from dbmr.schema.json # 5. Preview what a regeneration would change db-model-router diff --from dbmr.schema.json ``` -------------------------------- ### Quick Workflow: Scaffold and Generate Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Combines scaffolding a new project with generating all artifacts from a schema file in a single execution. ```bash # Scaffold project + generate everything in one go db-model-router init --from dbmr.schema.json --yes --no-install db-model-router generate --from dbmr.schema.json ``` -------------------------------- ### Initialize Database Adapter with init() Source: https://context7.com/avinashskaranth/db-model-router/llms.txt Selects the database adapter before connecting. Must be called before db.connect(). Default adapter is mysql. Supported values include postgres, sqlite3, mongodb, dynamodb, redis, and mssql. ```javascript const { init, db, model, route } = require("db-model-router"); // Select PostgreSQL adapter init("postgres"); // Now connect — db is a getter, do NOT destructure before init() db.connect({ host: "localhost", port: 5432, user: "postgres", password: "secret", database: "my_app", connectionLimit: 50, }); // SQLite3 (no Docker needed) init("sqlite3"); db.connect({ database: ":memory:" }); // MongoDB init("mongodb"); db.connect({ uri: "mongodb://admin:secret@localhost:27017/my_app" }); // DynamoDB (local dev) init("dynamodb"); db.connect({ region: "us-east-1", endpoint: "http://localhost:8000", accessKeyId: "fakeAccessKey", secretAccessKey: "fakeSecretKey", primaryKey: "id", }); // Redis init("redis"); db.connect({ host: "localhost", port: 6379, password: "", db: 0 }); // MSSQL (async connect) init("mssql"); await db.connect({ server: "localhost", port: 1433, user: "sa", password: "Password1!", database: "my_app", options: { encrypt: false, trustServerCertificate: true }, }); ``` -------------------------------- ### Initialize and Connect to Redis Source: https://github.com/avinashskaranth/db-model-router/blob/master/docs/adapters/redis.md Initializes the db-model-router with the Redis adapter and establishes a connection to the Redis server. Ensure Redis is running and accessible. ```javascript const { init, db, model, route } = require("db-model-router"); init("redis"); db.connect({ host: "localhost", port: 6379, password: "", // optional db: 0, // Redis DB index, optional primaryKey: "id", // field used as the hash key suffix }); ``` -------------------------------- ### Initialize and Connect to SQLite3 Database Source: https://github.com/avinashskaranth/db-model-router/blob/master/docs/adapters/sqlite3.md Initializes the adapter and establishes a connection to a SQLite database file or an in-memory database. ```javascript const { init, db, model, route } = require("db-model-router"); init("sqlite3"); db.connect({ database: "./data.db" }); // or in-memory: db.connect({ database: ":memory:" }); ``` -------------------------------- ### init(DB_TYPE) — Select Database Adapter Source: https://context7.com/avinashskaranth/db-model-router/llms.txt Selects the database adapter before connecting. Must be called before `db.connect()`. Supported values include `mysql`, `mariadb`, `postgres`, `sqlite3`, `mongodb`, `mssql`, `cockroachdb`, `oracle`, `redis`, and `dynamodb`. ```APIDOC ## init(DB_TYPE) — Select Database Adapter Selects the database adapter before connecting. Must be called before `db.connect()`. ### Parameters #### Path Parameters - **DB_TYPE** (string) - Required - The type of database adapter to use. Supported values: `mysql`, `mariadb`, `postgres`, `sqlite3`, `mongodb`, `mssql`, `cockroachdb`, `oracle`, `redis`, `dynamodb`. ### Request Example ```js const { init, db, model, route } = require("db-model-router"); // Select PostgreSQL adapter init("postgres"); // Now connect — db is a getter, do NOT destructure before init() db.connect({ host: "localhost", port: 5432, user: "postgres", password: "secret", database: "my_app", connectionLimit: 50, }); // SQLite3 (no Docker needed) init("sqlite3"); db.connect({ database: ":memory:" }); // MongoDB init("mongodb"); db.connect({ uri: "mongodb://admin:secret@localhost:27017/my_app" }); // DynamoDB (local dev) init("dynamodb"); db.connect({ region: "us-east-1", endpoint: "http://localhost:8000", accessKeyId: "fakeAccessKey", secretAccessKey: "fakeSecretKey", primaryKey: "id", }); // Redis init("redis"); db.connect({ host: "localhost", port: 6379, password: "", db: 0 }); // MSSQL (async connect) init("mssql"); await db.connect({ server: "localhost", port: 1433, user: "sa", password: "Password1!", database: "my_app", options: { encrypt: false, trustServerCertificate: true }, }); ``` ``` -------------------------------- ### Find First Matching Record Source: https://context7.com/avinashskaranth/db-model-router/llms.txt Use `model.findOne()` to retrieve a single record or `false` if no match is found. Useful for checking existence or getting a specific item. ```javascript const user = await users.findOne({ email: "alice@example.com" }); // => { id: 1, name: "Alice", email: "alice@example.com", age: 30 } or false if (!user) { console.log("User not found"); } else { console.log(`Found: ${user.name}`); } ``` -------------------------------- ### Initialize and Connect to MongoDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/docs/adapters/mongodb.md Initializes the router with the MongoDB adapter and establishes a connection to the database. Supports various connection methods including host/port, authentication, and full URI. ```javascript const { init, db, model, route } = require("db-model-router"); init("mongodb"); db.connect({ host: "localhost", port: 27017, database: "my_app", // or with auth: username: "admin", password: "secret", // or with a full URI: uri: "mongodb://admin:secret@localhost:27017", }); ``` -------------------------------- ### Initialize db-model-router with Kafka Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Initialize the database connection and then connect the Kafka producer. The Kafka producer initialization is asynchronous and only proceeds if KAFKA_BROKER is set. ```javascript const { init, db, kafka } = require("db-model-router"); init("postgres"); db.connect({ host: "localhost", database: "my_app" }); // Connect Kafka producer (only if KAFKA_BROKER is set) await kafka.init(); ``` -------------------------------- ### Paginated List with Filtering Source: https://context7.com/avinashskaranth/db-model-router/llms.txt Use `model.list()` for paginated results. Supports filtering, sorting, and custom page sizes. Can also be accessed via HTTP GET requests. ```javascript // Basic pagination const page0 = await users.list({ page: 0, size: 10 }); // => { data: [{...}, ...], count: 100 } ``` ```javascript // With filter and sort const filtered = await users.list({ age: 30, page: 0, size: 5, sort: [["-created_at"]], // descending }); ``` ```bash // Via HTTP GET /users/ with query params // curl "http://localhost:3000/users/?page=0&size=10&age=30" // curl "http://localhost:3000/users/?name=%25alice%25" # LIKE '%alice%' // curl "http://localhost:3000/users/?age=>25" # age > 25 // curl "http://localhost:3000/users/?status=in(active,pending)" # IN // curl "http://localhost:3000/users/?name=!bob" # != bob // curl "http://localhost:3000/users/?output_content_type=csv" # CSV download // curl "http://localhost:3000/users/?select_columns=id,name,email" ``` -------------------------------- ### Example Schema Definition Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Defines the structure for database tables, including columns, primary keys, and parent-child relationships for route nesting. Use this to configure your database models and their corresponding API routes. ```json { "adapter": "postgres", "framework": "express", "options": { "session": "redis", "rateLimiting": true, "helmet": true, "logger": true, "loki": false }, "tables": { "users": { "columns": { "user_id": "auto_increment", "name": "required|string", "email": "required|string", "age": "integer", "is_deleted": "boolean", "created_at": "datetime", "updated_at": "datetime" }, "pk": "user_id", "unique": ["email"], "softDelete": "is_deleted", "timestamps": { "created_at": "created_at", "modified_at": "updated_at" }, "parent": null }, "posts": { "columns": { "post_id": "auto_increment", "title": "required|string", "body": "string", "user_id": "required|integer", "created_at": "datetime", "modified_at": "datetime" }, "pk": "post_id", "unique": ["post_id"], "parent": null }, "comments": { "columns": { "comment_id": "auto_increment", "post_id": "required|integer", "user_id": "required|integer", "body": "required|string", "created_at": "datetime" }, "pk": "comment_id", "unique": ["comment_id"], "parent": "posts" } } } ``` -------------------------------- ### Query Parameter Filter Operators Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Control filtering behavior for GET / list endpoints using special prefixes and patterns in query parameters. Supports equality, inequality, range, LIKE, and IN operators. ```text ?name=john ?name=!john ?age=>25 ?age=>%3D25 ?age=<25 ?age=<%3D25 ?name=%25john%25 ?name=!%25john%25 ?status=in(active,pending) ?status=!in(active,pending) ``` -------------------------------- ### Mount REST Routes with Express Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Mounts the generated REST routes for a given model using Express. Requires express and express.json middleware. This setup creates 9 standard CRUD endpoints. ```javascript const express = require("express"); // or require("ultimate-express") const app = express(); app.use(express.json()); app.use("/users", route(users)); app.listen(3000); ``` -------------------------------- ### Connect to MySQL Database Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Establish a connection to a MySQL database using the provided credentials. The 'mysql' adapter is the default, so 'init()' is optional if using default settings. ```javascript const { init, db, model, route } = require("db-model-router"); // Default adapter is mysql, so init() is optional db.connect({ host: "localhost", port: 3306, user: "root", password: "password", database: "my_app", connectionLimit: 100, charset: "utf8mb4", }); ``` -------------------------------- ### Kafka Event Format Example Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md This is the structure of events produced to Kafka topics. The topic name follows the pattern `{KAFKA_TOPIC_PREFIX}.{table_name}`. Events include table name, operation type, data, and timestamp. ```json { "table_name": "users", "operation_type": "insert", "data": { "id": 1, "name": "Alice", "email": "alice@example.com" }, "timestamp": "2026-05-09T12:00:00.000Z" } ``` -------------------------------- ### Filter Syntax Examples Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Construct complex queries using a nested array structure for OR groups, AND conditions, column comparisons, and operators like `=`, `!=`, `>`, `<`, `LIKE`, and `IN`. The `LIKE` operator automatically wraps values with '%' for wildcard matching. ```javascript // AND: age > 25 AND type = 1 [ [ ["age", ">", 25], ["type", "=", 1], ], ][ // OR: name = "A" OR name = "B" ([["name", "=", "A"]], [["name", "=", "B"]]) ][ // IN [["type", "in", [1, 2, 3]]] ][ // LIKE (auto-wraps with %) [["name", "like", "Ali"]] ]; ``` -------------------------------- ### Initialize Kafka with Explicit Options Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Alternatively, initialize the Kafka producer by providing explicit configuration options. This allows for more control over the connection parameters. ```javascript await kafka.init({ broker: "localhost:9092", clientId: "my-app", topicPrefix: "dbmr", }); ``` -------------------------------- ### Initialize DB Model Router and Connect to Database Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Call `init()` before `db.connect()`. The default adapter is `mysql`. Do not destructure `db` before `init()` as it is a getter. Supports both CommonJS (CJS) and ECMAScript Modules (ESM) import styles. ```javascript // CJS const { init, db, model, route } = require("db-model-router"); // ESM (generated projects) import dbModelRouter from "db-model-router"; const { init, db, model, route } = dbModelRouter; init("postgres"); // call BEFORE db.connect() — do NOT destructure db before init() db.connect({ host, port: 5432, user, password, database }); const users = model( db, "users", { name: "required|string", email: "required|string", age: "integer", meta: "object", }, "id", // primary key column ["email"], // unique columns (for upsert conflict) { safeDelete: "is_deleted", // soft-delete column created_at: "created_at", // auto-managed timestamp modified_at: "updated_at", // auto-managed timestamp }, ); app.use("/users", route(users)); ``` -------------------------------- ### Initialize and Connect to DynamoDB Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/references/dynamodb.md Initializes the db-model-router with the 'dynamodb' adapter and establishes a connection. Configure region, endpoint for local development, and authentication details. The primaryKey option specifies the attribute name for the primary key. ```javascript const { init, db, model, route } = require("db-model-router"); init("dynamodb"); db.connect({ region: "us-east-1", // For local development (DynamoDB Local): endpoint: "http://localhost:8000", accessKeyId: "fakeAccessKey", secretAccessKey: "fakeSecretKey", primaryKey: "id", }); ``` -------------------------------- ### Unified CLI Entry Point Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md The main command for interacting with the db-model-router tool. Use with a subcommand and optional flags. ```bash db-model-router [flags] ``` -------------------------------- ### Initialize DB Model Router and Kafka Producer Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md After initializing the database connection, connect the Kafka producer using `kafka.init()`. You can provide explicit options or rely on environment variables. ```javascript import dbModelRouter from "db-model-router"; const { init, db, kafka } = dbModelRouter; init("postgres"); db.connect({ host: "localhost", database: "my_app" }); // Connect Kafka producer await kafka.init(); // Or with explicit options: await kafka.init({ broker: "localhost:9092", clientId: "my-app", topicPrefix: "dbmr", }); ``` -------------------------------- ### Run Adapter-Specific Tests Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Execute tests for individual database adapters using `npm run test:` commands. These commands utilize specific `.env` files located in the `env/` directory. ```bash npm run test:mysql # uses env/.env.mysql ``` ```bash npm run test:postgres # uses env/.env.postgres ``` ```bash npm run test:mongodb # uses env/.env.mongodb ``` ```bash npm run test:redis # uses env/.env.redis ``` ```bash npm run test:mssql # uses env/.env.mssql ``` ```bash npm run test:cockroachdb # uses env/.env.cockroachdb ``` ```bash npm run test:dynamodb # uses env/.env.dynamodb ``` ```bash npm run test:sqlite3 # uses env/.env.sqlite3 (in-memory, no Docker needed) ``` -------------------------------- ### Scaffold a new Node.js/Express project with db-model-router Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md Use this command to scaffold a new project with specified framework, database, session, and middleware options. The `--yes` flag bypasses interactive prompts. ```bash db-model-router init --framework express --database postgres --session redis --rateLimiting --helmet --logger --yes ``` -------------------------------- ### Generate db-model-router project from schema file Source: https://github.com/avinashskaranth/db-model-router/blob/master/README.md Generate project files from a schema definition file without interactive prompts. ```bash db-model-router generate --from dbmr.schema.json ``` -------------------------------- ### Run All Tests Source: https://github.com/avinashskaranth/db-model-router/blob/master/db-manager/README.md Execute all available tests, including unit, integration, and property tests. ```bash npm test ``` -------------------------------- ### Initialize PostgreSQL Connection Source: https://github.com/avinashskaranth/db-model-router/blob/master/docs/adapters/postgres.md Initializes the router with the PostgreSQL adapter and configures the database connection with pooling options. Ensure all connection parameters are correctly set for your environment. ```javascript const { init, db, model, route } = require("db-model-router"); init("postgres"); db.connect({ host: "localhost", port: 5432, user: "postgres", password: "password", database: "my_app", connectionLimit: 50, // pool max dateStrings: false, // set true to return dates as strings }); ``` -------------------------------- ### Generate SaaS Multi-Tenant Structure with db-model-router Source: https://context7.com/avinashskaranth/db-model-router/llms.txt The --saas-structure flag (enabled by default) generates a complete multi-tenant backend. Do not add users, tenants, roles, or role_permissions to the schema as they are auto-generated. ```bash db-model-router generate --from dbmr.schema.json # Generates SaaS tables: tenants, users, roles, role_permissions, webhooks, webhook_logs # Generates middleware: authenticate.js, tenantIsolation.js, hasPermission.js # Generates auth routes: POST /api/auth/login, POST /api/auth/logout # Generates CRUD routes: /api/users, /api/tenants, /api/roles, /api/roles/:id/permissions # Generates utilities: commons/password.js (scrypt), commons/webhook.js (retry delivery) # Generates seeds: Super Admin user + Tenant Admin role template ``` ```bash # To skip SaaS generation: db-model-router generate --from dbmr.schema.json --saas-structure=false ``` -------------------------------- ### Generate models, routes, tests, and OpenAPI spec from schema Source: https://github.com/avinashskaranth/db-model-router/blob/master/skill/SKILL.md After inspecting a database and generating `dbmr.schema.json`, use this command to generate all necessary components: models, routes, tests, and an OpenAPI specification. ```bash db-model-router generate --from dbmr.schema.json # → models, routes, tests, OpenAPI ```