Node JS ORM
  • TypeScript 83.7%
  • JavaScript 12.2%
  • Handlebars 4.1%
Find a file
Richard Tyler Miles 48155c4546
All checks were successful
Publish to npm on version bump (registry check) / check (push) Successful in 8m51s
Publish to npm on version bump (registry check) / publish (push) Has been skipped
Merge pull request 'Make CarbonNode 7.1 declarations portable' (#1) from codex/ci-portable-declarations-20261021 into main
2026-10-21 05:16:48 +00:00
.githooks Harden REST identity, SQL verification, caches, and build tooling (#47) 2026-10-03 11:57:40 -06:00
.github/workflows Fix native MySQL service loopback transport 2026-10-20 22:24:46 -06:00
docs fix: resolve verification scan findings and release 7.0.2 2026-10-09 18:27:28 -06:00
scripts Fix native MySQL service loopback transport 2026-10-20 22:24:46 -06:00
src feat: register explicit MySQL writer pools (#57) 2026-10-16 01:34:50 -06:00
.DS_Store 6.0.8 2026-02-04 21:43:31 -07:00
.gitignore Harden REST identity, SQL verification, caches, and build tooling (#47) 2026-10-03 11:57:40 -06:00
.nvmrc updating interfaces 2024-04-28 17:49:55 -06:00
AGENTS.md correct datetime parsing 2026-02-16 14:45:33 -07:00
C6.config.example.json Add PostgreSQL dialect support 2026-05-23 20:35:59 -06:00
C6.config.example.ts Add PostgreSQL dialect support 2026-05-23 20:35:59 -06:00
C6.config.json im the only one using this right? 2026-03-02 17:34:31 -07:00
LICENSE Initial commit 2023-07-26 22:38:07 -06:00
package-lock.json Emit portable CarbonNode declarations and check packed PR artifacts 2026-10-20 21:58:46 -06:00
package.json Emit portable CarbonNode declarations and check packed PR artifacts 2026-10-20 21:58:46 -06:00
README.md feat: register explicit MySQL writer pools (#57) 2026-10-16 01:34:50 -06:00
rollup.config.mjs fix: resolve verification scan findings and release 7.0.2 2026-10-09 18:27:28 -06:00
tsconfig.json no js 2025-09-03 20:04:44 -06:00
tslint.json typescript base rollup config 2023-07-26 23:37:16 -06:00
vitest.config.ts test on every deployment 2025-09-03 10:04:00 -06:00

npm License Size Documentation Monthly Downloads All Downloads Star Github Actions Test and Publish to NPM

CarbonNode

CarbonNode is a typed SQL ORM runtime plus code generator for REST bindings, with MySQL support and PostgreSQL runtime/generator support.

It is built for:

  • full-stack teams that want one query shape across frontend and backend
  • explicit column references and safer query composition
  • JSON-serializable SQL expression payloads with predictable parsing
  • generated TypeScript bindings from live MySQL schema

It can run in two modes:

  • SQL executor (mysqlPool set): executes SQL directly in Node
  • HTTP executor (no pool, axios set): sends requests to a CarbonNode REST endpoint

Table of Contents

  1. Install
  2. Quickstart
  3. Execution Model
  4. C6 + CarbonReact State Management
  5. Canonical SQL Expression Grammar (6.1.0+)
  6. Clause-by-Clause Usage
  7. Helper Builders
  8. Singular vs Complex Requests
  9. HTTP Query-String Pitfalls
  10. Generator Output
  11. SQL Allowlist
  12. Lifecycle Hooks and Websocket Broadcast
  13. Testing
  14. Migration Notes (6.x -> 7.0)
  15. Migration Notes (6.0 -> 6.1)
  16. AI Interpretation Contract
  17. Git Hooks
  18. Support

Install

npm install @carbonorm/carbonnode

Peer dependencies:

  • mysql2 for SQL executor mode
  • axios for HTTP executor mode
  • express only if hosting the REST route in your app

Quickstart

1) Generate bindings

Generate C6.ts + C6.test.ts + dump artifacts into an output directory:

npx generateRestBindings \
  --config ./rest.config.json \
  --prefix "" \
  --output ./shared/rest

--config is optional if a C6.config.json, C6.config.ts, .C6.json, or .C6.ts exists in the current directory or any parent directory. If no config exists and the process is interactive (TTY), the CLI offers a guided prompt to create ./C6.config.json. Prefer C6.config.json for security/reproducibility; TS config files are executed as local code during generation. TS config may export a plain object, a function returning an object, or an async function/Promise resolving to the config object.

Config shape:

{
  "databases": [
    {
      "alias": "app",
      "host": "127.0.0.1",
      "port": 3306,
      "user": "root",
      "passEnv": "APP_DB_PASS",
      "dbnames": ["app"]
    },
    {
      "alias": "analytics",
      "host": "analytics-db.internal",
      "port": 3306,
      "user": "analytics_user",
      "passEnv": "ANALYTICS_DB_PASS",
      "dbnames": ["analytics", "app"]
    }
  ],
  "primaryAlias": "app"
}

Each dbnames entry creates a generated scoped namespace. If one entry has multiple schema names, aliases are generated as:

  • alias for the schema matching alias
  • alias_<dbname> for additional schema names

Example above yields C6.analytics and C6.analytics_app.

Starter template: ./C6.config.example.json. TS starter template: ./C6.config.example.ts.

Beginner-friendly TS setup (recommended when you want env/vault secrets):

  1. Copy the template.
cp ./C6.config.example.ts ./C6.config.ts
  1. Set password env vars in your shell.
export APP_DB_PASS='replace-me'
export BILLING_DB_PASS='replace-me'
export ANALYTICS_DB_PASS='replace-me'
  1. Open C6.config.ts and update host, user, dbnames, primaryAlias, and dialect for your databases. Use dialect: "postgresql" for PostgreSQL targets; omitted dialects default to MySQL.

  2. Generate bindings.

npx generateRestBindings --output ./shared/rest

Notes:

  • You can pass an explicit path too: npx generateRestBindings --config ./C6.config.ts --output ./shared/rest.
  • C6.config.ts can load secrets asynchronously (for example from Vault) before returning the config object.
  • Keep secret-bearing files out of git. Prefer local/private config names like .C6.ts or .C6.json.

Import from generated bindings:

import { C6, GLOBAL_REST_PARAMETERS, Actor } from "./shared/rest/C6";

2) Configure runtime

SQL executor mode (Node + direct DB)

import mysql from "mysql2/promise";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

GLOBAL_REST_PARAMETERS.mysqlPool = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "password",
  database: "sakila",
});

PostgreSQL runtime execution is available by providing a pg pool and selecting the PostgreSQL SQL dialect:

import { Pool } from "pg";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

GLOBAL_REST_PARAMETERS.postgresPool = new Pool({
  host: "127.0.0.1",
  user: "postgres",
  password: "password",
  database: "app",
});
GLOBAL_REST_PARAMETERS.sqlDialect = "postgresql";

Current PostgreSQL support covers runtime SQL building/execution for the canonical expression grammar, basic CRUD shapes, RETURNING * for inserts, ON CONFLICT upserts when primary-key metadata is available, and inner-join deletes via DELETE ... USING. MySQL-only forms such as REPLACE and MySQL index hints fail explicitly; non-inner or derived-table delete joins should use a WHERE subselect for now. Binding generation supports dialect: "postgresql" in C6.config.*, uses pg_dump/psql when available, and can reuse a prebuilt C6.pg_dump.sql in CI or no-database environments.

SQL executor mode with multiple databases (request-scoped)

Use GLOBAL_REST_PARAMETERS.databases to register connection targets. Then select one per request with [C6.DB].

import mysql from "mysql2/promise";
import { C6, GLOBAL_REST_PARAMETERS, Actor } from "./shared/rest/C6";

const appPool = mysql.createPool({ host: "10.0.0.10", user: "root", password: "password", database: "app" });
const billingPool = mysql.createPool({ host: "10.0.0.20", user: "root", password: "password", database: "billing" });

GLOBAL_REST_PARAMETERS.databases = {
  app: appPool,
  billing: billingPool,
};
GLOBAL_REST_PARAMETERS.defaultDatabase = "app";

await Actor.Get({
  [C6.DB]: "billing",
  [C6.PAGINATION]: { [C6.LIMIT]: 10 },
});

C6.DB is request-scoped and safe for parallel async requests.

If a key exists in GLOBAL_REST_PARAMETERS.databases, generated bindings also expose scoped namespaces:

await C6.billing.Actor.Get({
  [C6.PAGINATION]: { [C6.LIMIT]: 10 },
});

This is equivalent to calling Actor.Get({ [C6.DB]: "billing", ... }).

HTTP executor mode (frontend or remote client)

import { axiosInstance } from "@carbonorm/carbonnode";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

GLOBAL_REST_PARAMETERS.axios = axiosInstance;
GLOBAL_REST_PARAMETERS.restURL = "/api/rest/";

If you are using CarbonReact, wire reactBootstrap as described in C6 + CarbonReact State Management.

3) Host the REST endpoint (optional, Express)

import express from "express";
import mysql from "mysql2/promise";
import { restExpressRequest } from "@carbonorm/carbonnode";
import { C6 } from "./shared/rest/C6";

const app = express();
app.set("query parser", "extended");
app.use(express.json());

const mysqlPool = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "password",
  database: "sakila",
});

restExpressRequest({
  router: app,
  routePath: "/api/rest/:table{/:primary}",
  C6,
  mysqlPool,
});

4) Query data

import { C6, Actor } from "./shared/rest/C6";

const result = await Actor.Get({
  [C6.SELECT]: [
    Actor.ACTOR_ID,
    Actor.FIRST_NAME,
    Actor.LAST_NAME,
  ],
  [C6.WHERE]: {
    [Actor.LAST_NAME]: [C6.LIKE, [C6.LIT, "%PITT%"]],
  },
  [C6.PAGINATION]: {
    [C6.LIMIT]: 10,
    [C6.PAGE]: 1,
    [C6.ORDER]: [[Actor.ACTOR_ID, C6.DESC]],
  },
});

Execution Model

flowchart LR
    Client["App Code\nActor.Get(...)"] --> Request["restRequest facade"]
    Request -->|"mysqlPool/postgresPool configured"| SQL["SqlExecutor"] --> DB[("SQL Database")]
    Request -->|"no SQL pool"| HTTP["HttpExecutor"] --> REST["/api/rest/:table"]
    REST --> Express["ExpressHandler"] --> SQL

restRequest chooses SQL executor when mysqlPool or postgresPool is present; otherwise it uses HTTP executor.

C6 + CarbonReact State Management

If your app uses CarbonReact, CarbonNode can keep table state in sync automatically after requests.

Set:

import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

GLOBAL_REST_PARAMETERS.reactBootstrap = yourCarbonReactInstance;

State sync behavior:

  • HTTP executor path:
    • GET: updates table state with response rows
    • POST: inserts created row(s) into state
    • PUT: updates matching row(s) by primary key
    • DELETE: removes matching row(s) by primary key
  • SQL executor path:
    • GET: updates table state when reactBootstrap is set
    • write sync is typically handled by your websocket/event layer

How C6 identifies rows:

  • stateKey is table name (restModel.TABLE_NAME)
  • uniqueObjectId is table primary keys (restModel.PRIMARY_SHORT)

Per-request escape hatch:

await SomeTable.Get({
  /* query */
  skipReactBootstrap: true,
});

This lets you opt out of automatic state writes when a call is read-only for the UI or you are running a background sync pass.

Canonical SQL Expression Grammar (6.1.0+)

6.1.0 unifies expression parsing across SELECT, WHERE, HAVING, ORDER, and expression-capable UPDATE/INSERT values.

Purpose Canonical form
Known function [C6.FUNCTION_NAME, ...args]
Custom function [C6.CALL, "FUNCTION_NAME", ...args]
Alias [C6.AS, expression, "alias"]
DISTINCT [C6.DISTINCT, expression]
Literal binding [C6.LIT, value]
ORDER term [expression, "ASC" | "DESC"]

Normative rules:

  • Bare strings are references only (table.column or valid aliases in context).
  • Non-reference strings must be wrapped with [C6.LIT, value].
  • AS and DISTINCT are wrappers, not positional tokens.
  • PAGINATION.ORDER must be an array of order terms.
  • CarbonNode normalizes a top-level ORDER into PAGINATION.ORDER for compatibility, but new code should prefer PAGINATION.ORDER.
  • Use C6.CALL for unknown/custom function names.

Removed legacy syntax (throws):

  • [fn, ..., C6.AS, alias]
  • [column, C6.AS, alias]
  • object-rooted function expressions like { [C6.COUNT]: [...] }
  • implicit string literals in function arguments
  • ORDER object-map syntax (now array terms only)

Clause-by-Clause Usage

SELECT with wrappers

import { C6, Actor } from "./shared/rest/C6";

const response = await Actor.Get({
  [C6.SELECT]: [
    [C6.AS, [C6.DISTINCT, Actor.FIRST_NAME], "distinct_name"],
    [C6.AS, [C6.COUNT, Actor.ACTOR_ID], "cnt"],
    [C6.CALL, "COALESCE", [C6.LIT, "Unknown"], Actor.LAST_NAME],
  ],
});

WHERE with literals, BETWEEN, IN, AND/OR

import { C6, Actor } from "./shared/rest/C6";

const response = await Actor.Get({
  [C6.WHERE]: {
    [C6.AND]: [
      { [Actor.LAST_NAME]: [C6.LIKE, [C6.LIT, "S%"]] },
      { [Actor.ACTOR_ID]: [C6.BETWEEN, [5, 50]] },
      { [Actor.FIRST_NAME]: [C6.IN, [[C6.LIT, "NICK"], [C6.LIT, "ED"]]] },
    ],
  },
});

JOIN

import { C6, Actor, Film_Actor } from "./shared/rest/C6";

const response = await Actor.Get({
  [C6.SELECT]: [Actor.ACTOR_ID, Actor.FIRST_NAME],
  [C6.JOIN]: {
    [C6.INNER]: {
      [Film_Actor.TABLE_NAME]: {
        [Film_Actor.ACTOR_ID]: [C6.EQUAL, Actor.ACTOR_ID],
      },
    },
  },
});

ORDER and pagination

import { C6, Actor } from "./shared/rest/C6";

const response = await Actor.Get({
  [C6.PAGINATION]: {
    [C6.ORDER]: [
      [Actor.LAST_NAME, C6.ASC],
      [Actor.FIRST_NAME, C6.DESC],
    ],
    [C6.LIMIT]: 25,
    [C6.PAGE]: 1,
  },
});

PAGE is 1-based:

  • PAGE = 1 -> first page
  • PAGE = 2 -> second page
  • PAGE = 0 is coerced to 1

UPDATE expression values

import { C6, Actor } from "./shared/rest/C6";

await Actor.Put({
  [Actor.ACTOR_ID]: 42,
  [C6.UPDATE]: {
    [Actor.FIRST_NAME]: [C6.CONCAT, [C6.LIT, "Mr. "], Actor.LAST_NAME],
  },
});

Helper Builders

CarbonNode exports typed builders for canonical expression tuples and common literal-safe WHERE / HAVING predicates:

import { fn, call, alias, distinct, lit, eqLit, inLit, notInLit, betweenLit, asc, desc } from "@carbonorm/carbonnode";
import { C6, Actor } from "./shared/rest/C6";

const response = await Actor.Get({
  [C6.SELECT]: [
    alias(distinct(Actor.FIRST_NAME), "distinct_name"),
    alias(fn(C6.COUNT, Actor.ACTOR_ID), "cnt"),
    call("COALESCE", lit("N/A"), Actor.LAST_NAME),
  ],
  [C6.WHERE]: {
    [Actor.FIRST_NAME]: eqLit("NICK"),
    [Actor.LAST_NAME]: inLit(["WAHLBERG", "CHASE"]),
    [Actor.ACTOR_ID]: notInLit([1, 2]),
    0: {
      [Actor.LAST_UPDATE]: betweenLit("2006-02-15", "2006-02-16"),
    },
  },
  [C6.PAGINATION]: {
    [C6.ORDER]: [desc(fn(C6.COUNT, Actor.ACTOR_ID)), asc(Actor.FIRST_NAME)],
    [C6.LIMIT]: 5,
  },
});

Use eqLit(), inLit(), notInLit(), and betweenLit() when the comparison value is a string or other non-reference literal that should be wrapped with C6.LIT automatically. Use asc() / desc() for the common one-direction ORDER terms.

Singular vs Complex Requests

Singular requests (primary key at root) are normalized into complex query format.

await Actor.Get({ [Actor.ACTOR_ID]: 42 });
await Actor.Put({ [Actor.ACTOR_ID]: 42, [Actor.LAST_NAME]: "Updated" });
await Actor.Delete({ [Actor.ACTOR_ID]: 42 });

Behavior:

  • GET with missing PKs remains a collection query.
  • PUT/DELETE singular forms require full PK coverage.

HTTP Query-String Pitfalls

If you are manually building URLs, nested arrays must preserve tuple shape exactly.

Common failure:

  • WHERE[job_runs.job_type][0]=LIT&WHERE[job_runs.job_type][1]=avm_print
  • This is interpreted as operator tuple [LIT, "avm_print"], and fails with:
    • Invalid or unsupported SQL operator detected: 'LIT'

Correct structure:

  • WHERE[job_runs.job_type][0]==
  • WHERE[job_runs.job_type][1][0]=LIT
  • WHERE[job_runs.job_type][1][1]=avm_print

Also ensure ORDER is under PAGINATION:

  • correct: PAGINATION[ORDER][0][0]=job_runs.created_at
  • compatible but non-canonical: ORDER[0][0]=job_runs.created_at

Recommendation: use generated bindings + axios executor, not manual URL construction.

Generator Output

generateRestBindings writes:

  • C6.ts (stable compatibility facade and public entrypoint)
  • C6.generated/core.ts (shared runtime state such as TABLES, COLUMNS, initialRestfulObjectsState, and GLOBAL_REST_PARAMETERS)
  • C6.generated/tables/*.ts (one generated table module per table, including the interface, primary-key type, base model, and REST binding)
  • C6.generated/views/*.ts (one generated read-only view module per SQL view, with Get only)
  • C6.generated/scoped.ts (scoped database bindings)
  • C6.test.ts (generated test suite)
  • C6.mysqldump.sql for MySQL generation, or C6.pg_dump.sql for PostgreSQL generation
  • C6.mysqldump.json
  • C6.mysql.cnf for MySQL generation
  • C6.<databaseKey>.mysqldump.sql or C6.<databaseKey>.pg_dump.sql for each resolved non-primary config database alias

C6.ts re-exports the selected public symbols from C6.generated/**, so existing imports such as import { C6, Actor, type iActor, TABLES } from "./rest/C6" remain the public contract. Auto-barrel tools should exclude C6.generated/** to avoid publishing noisy internals. Correctness does not depend on that exclusion: re-exporting both C6.ts and an individual generated table module resolves to the same table export.

SQL views are emitted as readonly relations with RELATION_TYPE: "VIEW" and READ_ONLY: true. They are registered in TABLES for query composition and VIEWS for view-only discovery, so a view can be used anywhere a selectable relation is valid, including JOIN; generated REST bindings only expose Get, and runtime request resolution rejects write methods against read-only models.

Template sources:

  • scripts/assets/handlebars/C6.ts.handlebars
  • scripts/assets/handlebars/C6.core.ts.handlebars
  • scripts/assets/handlebars/C6.table.ts.handlebars
  • scripts/assets/handlebars/C6.tablesIndex.ts.handlebars
  • scripts/assets/handlebars/C6.view.ts.handlebars
  • scripts/assets/handlebars/C6.viewsIndex.ts.handlebars
  • scripts/assets/handlebars/C6.scoped.ts.handlebars
  • scripts/assets/handlebars/C6.test.ts.handlebars

SQL Allowlist

To enforce a SQL allowlist in production:

import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

GLOBAL_REST_PARAMETERS.sqlAllowListPath = "/path/to/C6.sqlAllowList.json";

Optional: add a project-specific normalizer for allowlist matching:

import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

GLOBAL_REST_PARAMETERS.sqlQueryNormalizer = (normalizedSql) =>
  normalizedSql.toLowerCase();

sqlQueryNormalizer runs after CarbonNode's built-in normalization. Use it to enforce house-style matching (for example lowercase-only allowlist entries).

Allowlist file format:

[
  "SELECT * FROM `actor` LIMIT 1"
]

Normalization behavior (important):

CarbonNode normalizes both:

  • each SQL entry in your allowlist file
  • each runtime SQL statement before matching

So you should treat allowlist entries as normalized query shapes, not exact byte-for-byte logs.

Normalization includes:

  • stripping ANSI color codes
  • collapsing whitespace
  • removing trailing ;
  • normalizing common geo function names (ST_DISTANCE_SPHERE, ST_GEOMFROMTEXT, MBRCONTAINS)
  • normalizing LIMIT/OFFSET numeric literals to placeholders
  • collapsing bind groups (for example IN (?, ?, ?) -> IN (? ×*))
  • collapsing repeated VALUES bind rows to a wildcard row shape

Example (conceptual):

-- runtime SQL
SELECT * FROM `actor` WHERE actor.actor_id IN (?, ?, ?) LIMIT 100

-- normalized shape used for matching
SELECT * FROM `actor` WHERE actor.actor_id IN (? ×*) LIMIT ?

When enabled:

  • missing allowlist file -> error
  • SQL not in allowlist -> blocked

Practical workflow:

  1. Run representative queries in tests/integration.
  2. Collect normalized SQL statements.
  3. Save them into your allowlist JSON.
  4. Set GLOBAL_REST_PARAMETERS.sqlAllowListPath.

Lifecycle Hooks and Websocket Broadcast

Generated models include lifecycle hook groups per method:

  • beforeProcessing
  • beforeExecution
  • afterExecution
  • afterCommit

Unlike other CarbonORM language bindings, C6.ts is not semi-persistent. Modifications to the C6 object should be done at runtime, not by editing the generated file.

Websocket payloads for writes are supported via:

GLOBAL_REST_PARAMETERS.websocketBroadcast = async (payload) => {
  // broadcast payload to your websocket infrastructure
};

Real-time communication explained (no websocket background required)

HTTP is request/response. A browser asks, server answers, done.

Real-time systems add server push: when data changes, the server proactively notifies connected clients so they can refresh or patch state immediately.

In CarbonNode:

  • POST, PUT, DELETE can trigger websocketBroadcast
  • GET does not broadcast
  • CarbonNode does not run a websocket server for you
  • you provide the websocketBroadcast function and route payloads into your existing websocket layer (ws, Socket.IO, SSE bridge, etc.)

Payload shape (high level):

  • table + method metadata
  • request body
  • request primary key (when detectable)
  • response row(s) and response primary key when available

Why this matters:

  • keeps multiple tabs/users aligned without polling
  • reduces stale UI after writes
  • enables event-driven cache invalidation (table + primary key)

Minimal ws example:

import { WebSocketServer } from "ws";
import { GLOBAL_REST_PARAMETERS } from "./shared/rest/C6";

const wss = new WebSocketServer({ server: httpServer });

GLOBAL_REST_PARAMETERS.websocketBroadcast = async (payload) => {
  const message = JSON.stringify({ type: "db.write", payload });
  for (const client of wss.clients) {
    if (client.readyState === 1) {
      client.send(message);
    }
  }
};

Client handling pattern:

  1. listen for db.write events
  2. inspect payload.REST.TABLE_NAME and primary keys
  3. invalidate/refetch relevant queries or patch local state

Testing

Run full validation:

npm test

This includes:

  • build
  • binding generation
  • test suite

Migration Notes (6.x -> 7.0)

generateRestBindings is now config-first and this is a breaking change.

Before (6.x):

npx generateRestBindings \
  --user root \
  --pass password \
  --host 127.0.0.1 \
  --port 3306 \
  --dbname sakila \
  --output ./shared/rest

After (7.0):

npx generateRestBindings \
  --config ./rest.config.json \
  --output ./shared/rest

Flag migration:

  • --user -> databases[].user
  • --pass -> databases[].pass (or passEnv, recommended)
  • --host -> databases[].host
  • --port -> databases[].port
  • --dbname -> databases[].dbname / databases[].dbnames[]
  • --databases (legacy alias map) -> explicit databases[] entries in config
  • PostgreSQL targets should also set databases[].dialect to "postgresql".

Behavior changes:

  • Config discovery checks .C6.ts, .C6.json, C6.config.local.json, C6.config.ts, and C6.config.json from CWD upward.
  • Guided setup scaffolds ignored C6.config.local.json with mode 0600 and a passEnv reference (default C6_DB_PASSWORD). Export that environment variable before generation; the wizard never collects a password.
  • Multi-schema aliases are explicit via dbnames and emitted as C6.<alias> / C6.<alias>_<dbname>.

Security recommendation:

  • Prefer passEnv over inline pass.
  • Keep secret-bearing config files out of source control (.gitignore), for example:
    • .C6.json
    • .C6.ts
    • C6.config.local.json
    • rest.config.json
    • rest.config.local.json

Migration Notes (6.0 -> 6.1)

Before:

[C6.COUNT, Actor.ACTOR_ID, C6.AS, "cnt"]

After:

[C6.AS, [C6.COUNT, Actor.ACTOR_ID], "cnt"]

Before:

[C6.PAGINATION]: {
  [C6.ORDER]: { [Actor.LAST_NAME]: C6.ASC }
}

After:

[C6.PAGINATION]: {
  [C6.ORDER]: [[Actor.LAST_NAME, C6.ASC]]
}

Before:

[C6.ST_GEOMFROMTEXT, ["POINT(-104.89 39.39)", 4326]]

After:

[C6.ST_GEOMFROMTEXT, [C6.LIT, "POINT(-104.89 39.39)"], 4326]

AI Interpretation Contract

Use this section as a strict contract for automated query generation.

carbonnode:
  version: "6.1.0+"
  grammar:
    known_function: "[C6C.<KNOWN_FN>, ...args]"
    custom_function: "[C6C.CALL, 'FUNCTION_NAME', ...args]"
    alias: "[C6C.AS, expression, 'alias']"
    distinct: "[C6C.DISTINCT, expression]"
    literal: "[C6C.LIT, value]"
    order_term: "[expression, 'ASC' | 'DESC']"
  required_rules:
    - "Bare strings are references only."
    - "Wrap non-reference strings with C6C.LIT."
    - "PAGINATION.ORDER must be an array of order terms."
    - "Use C6C.CALL for unknown function names."
  forbidden_legacy:
    - "[fn, ..., C6C.AS, alias]"
    - "[column, C6C.AS, alias]"
    - "{ [C6C.COUNT]: [...] }"
    - "Implicit string literals in function args"
    - "ORDER object-map syntax"

Git Hooks

This project uses Git hooks via postinstall:

  • pre-commit: builds project and blocks commits on build failure
  • post-push: publishes to npm when version changes
  • npm install runs postinstall to ensure hooks are configured

Support

Report issues at:

Security behavior and migration

Version 7.0.0 includes the new repository-scan remediation. Version 7.0.1 also prevents deeply nested expression tokens from triggering recursive string conversion inside request validation; the iterative budget rejects them first. Version 7.0.2 closes the eight verification-scan findings, including SQL/browser transport budgets, MySQL write cancellation, and trusted generator tooling. This major bump reflects stricter request defaults and rejection of previously accepted unsafe or ambiguous inputs. Regenerate bindings and review these changes:

  • HTTP lifecycle phases are awaited. A rejected beforeExecution hook prevents dispatch. HTTP primary keys must be scalar, nonempty URL segments. Delimiters, percent escapes, control characters, and dot segments are rejected; remaining characters are encoded.
  • Composite identities use complete payload keys or WHERE with a table-only URL. /rest/:table/:primary is rejected for composite-key models, even with complete body keys.
  • Every supplied pagination object retains a limit: default 100, maximum 1000, maximum offset 100000. LIMIT/PAGE must be positive safe integers (decimal query-string values are accepted). Trusted maxPageSize and maxPageOffset can adjust these caps.
  • Generic REST denies custom CALLs unless trusted restFunctionAllowlist approves them. Delay, file, lock, and listed side-effect functions remain denied. Trusted direct ORM CALL grammar remains available. REST sets statementTimeoutMs to 5000 by default: MySQL read execution uses max_execution_time; PostgreSQL uses statement_timeout. Previous session settings are restored; PostgreSQL mutations use transaction-local settings. MySQL writes reserve a separate cancellation connection before execution and terminate the target session on deadline. Custom MySQL drivers must supply trusted mysqlCancellation.
  • All request trees have shared iterative budgets: depth 32, 10000 nodes, 1000 items per collection, 1 MiB input, 1000 SQL parameters, and 256 KiB generated SQL. Trusted queryLimits can adjust individual budgets; request JSON cannot raise them. maxResponseBytes defaults to 8 MiB. SQL results and HTTP payloads are checked; Native mysql2/pg receipt is bounded before row parsing; unsupported REST transports fail closed. Browser Axios fetch streams are bounded before decoding/JSON parsing; Node uses the capped HTTP adapter. Custom SQL drivers must expose sqlResponseStream; compressed MySQL needs a decoded stream. HTTP requests retain a 30-second default timeout.
  • Response cache storage is bounded to 1000 entries, 16 MiB total, 1 MiB per entry, and a nonrenewable 60-second TTL. LRU eviction, expired entries, oversized/unserializable responses, and rejected promises force a fresh request. Existing trusted scopes remain required.
  • Generator relation names must map to safe identifiers and noncolliding filenames. Reserved names, separators, traversal, and symbolic links fail before generated-source writes. Generated typecheck failures are fatal unless explicitly skipped for a controlled offline workflow. The compiler is a pinned local runtime dependency. Database clients come from trusted fixed paths or absolute --mysql-client, --mysqldump-client, --psql-client, --pg-dump-client flags. Failed online schema/metadata acquisition is fatal; existing dumps require explicit --no-db 1 reuse.
  • Warning/error string fields escape terminal controls, line breaks, and Unicode record controls.

The October 2026 finding review distinguishes historical findings, intentional SQL grammar, SQL-allowlist mitigations, and fixes.

  • GET response caching now requires a nonempty cacheScope in trusted runtime configuration. Use a scope unique to the authenticated principal, tenant, and permission version, and rotate it when any of those change. Do not take it from request JSON. Keys also distinguish SQL pools/HTTP clients and REST URLs. SQL requests with lifecycle hooks bypass result caching so authorization hooks always run. Both SQL and HTTP GET requests require cacheResults: true to enable caching; a scope alone does not opt in. Database aliases also partition cache entries when they share a transport.
  • Generic Express REST routes exclude generated views by default, including JOINs and scalar/derived subqueries. To expose an authorized view, set trusted restViewAllowlist: ['view_name'] in the server configuration. Request JSON cannot opt in. Direct server ORM reads of views remain available.
  • GROUP_BY accepts the same expression grammar as SELECT. A single tuple (for example [C6C.CALL, 'COALESCE', column, [C6C.LIT, 'unknown']]) and a list of expressions are both supported. Bare strings remain references.
  • UPDATE and DELETE require a nonempty WHERE predicate. Trusted server code may set allowUnfilteredWrites: true for intentional unfiltered writes. A client JSON field cannot grant this permission. URL primary keys constrain complex requests with AND and are always bound as literal values.
  • SQL allowlisting remains optional and should be configured on production REST endpoints. The final SQL is checked again after mutable execution hooks. An allowlist constrains query shapes; applications must still authorize users and bind ownership/tenant values. Bare strings remain references in the SQL expression grammar; wrap literal data in [C6C.LIT, value] or use eqLit.
  • Express responses omit SQL metadata and internal exception messages. Logs retain the server error. Request debug cannot raise the configured log level; INFO SQL logs contain status indicators, with SQL text available at DEBUG.
  • Websocket broadcasts contain identity/invalidation metadata by default, with empty REQUEST and no RESPONSE row data. Set trusted websocketIncludeRows: true only for callbacks that authorize recipients and redact sensitive fields.
  • Dependency fetching rejects traversals exceeding 8 levels or 100 requests and skips repeated table/filter requests. Pagination next() advances the page.
  • Generator credentials use private temporary files and are removed on exit. Schema-derived names are escaped as TypeScript string literals, including table, view, and database-scoped templates. C6_NO_DB=1 or --no-db 1 uses existing dumps without invoking database tools; CI alone does not disable database generation. Trigger bodies and definers are omitted by default; --includeTriggerDefinitions 1 is an explicit opt-in for server-only generated artifacts. Raw schema dumps still contain schema details and should not be shipped to browsers.
  • Generator expressions such as restUrlExpression, custom imports, and override expressions are trusted source code. Do not populate them from untrusted input. SQL views remain generated read-only relations; only approve intended view query shapes in the SQL allowlist and enforce caller authorization separately.
  • The CommonJS export uses a .cjs extension. Regenerate bindings to receive generator fixes. Existing installed applications do not change merely because this repository's fixes merge.

Explicit MySQL writer registration

Register mysqlWriterPool alongside mysqlPool when reads use a replica:

GLOBAL_REST_PARAMETERS.mysqlPool = guardedReaderPool;
GLOBAL_REST_PARAMETERS.mysqlWriterPool = writerPool;

GET uses mysqlPool (or the writer when no read pool is registered). POST, PUT, PATCH and DELETE acquire mysqlWriterPool, falling back to mysqlPool for existing single-pool applications. The complete mutation lifecycle, including transaction and session settings, stays on that writer connection. Register these trusted options globally or per database; never accept pools from request input. Replica health, replication fences and read-after-write policy belong to the registered pool provider.