由 Kade 出售

Objection.js is a powerful relational query builder and ORM for Node.js built on knex, supporting SQLite3, Postgres, and MySQL with eager loading, graph inserts, transactions, and TypeScript.
This block delivers the full Objection.js 3.1.5 library source (lib/) — a relational query builder and ORM layer built on top of knex. It exposes Model, QueryBuilder, relation classes, validators, graph upsert/insert operations, and transaction helpers. Target buyers are Node.js backend engineers who need fine-grained SQL control with first-class relation support.
model/ - Core Model class, validation, graph traversal, cloning, ID helpers, relation parsingmodel/graph/ - ModelGraph, ModelGraphBuilder, ModelGraphEdge, ModelGraphNode for object-graph operationsqueryBuilder/ - QueryBuilder, QueryBuilderBase, RelationExpression, raw/ref/val/fn buildersqueryBuilder/graph/ - Graph upsert, insert, patch, delete orchestration (insert, patch, delete, recursiveUpsert sub-dirs)queryBuilder/join/ - RelationJoiner, TableTree, JoinResultParser for join-based eager loadingqueryBuilder/operations/ - Atomic query builder operations (internal)queryBuilder/parsers/ - Expression parsers used by QueryBuilderqueryBuilder/transformations/ - Post-build SQL transformations (e.g. MySQL subquery wrapping)relations/ - HasOneRelation, HasManyRelation, BelongsToOneRelation, HasOneThroughRelation, ManyToManyRelationutils/ - promiseUtils, identifierMapping, mixin, objectUtils, classUtilsobjection.js - Main entry point; re-exports all public symbolstransaction.js - transaction() helper for knex-based transactionsinitialize.js - initialize() to prefetch table metadata for multiple modelsnpm install knex
npm install user@example.com
npm install ajv ajv-formats
npm install db-errors
# Choose one database driver:
npm install pg # PostgreSQL
npm install mysql2 # MySQL / MariaDB
npm install better-sqlite3 # SQLite
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This JavaScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 c30ab956cf465546…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
No native build steps, CocoaPods, or Android linking required. This is a pure Node.js library.
Copy the source/ directory into your project, e.g. src/lib/objection/.
Point your require/import alias at the entry point:
tsconfig.json (TypeScript path alias):
{
"compilerOptions": {
"paths": {
"objection-src/*": ["src/lib/objection/*"]
}
}
}
Configure knex before using any model:
import Knex from 'knex';
const knex = Knex({ client: 'pg', connection: process.env.DATABASE_URL });
Set Model.knex(knex) once at application bootstrap (see examples below).
Environment variables required:
DATABASE_URL — your full database connection string (no built-in fallback).No Babel transform is required when running on Node 14+. The source uses CommonJS (require/module.exports) throughout.
Modelimport { Model } from './source/objection';
class Person extends Model {
static tableName: string;
static relationMappings: Record<string, RelationMapping>;
}
Subclass Model to define a table-backed entity. Declare tableName and optionally jsonSchema for validation, and relationMappings for typed relationships. All query methods (query(), $query(), $relatedQuery()) are inherited.
transactionimport { transaction } from './source/objection';
transaction(ModelA, ModelB, async (BoundA, BoundB, trx) => Promise<T>): Promise<T>;
transaction(knexInstance, callback): Promise<T>;
Wraps one or more model classes (or a raw knex instance) in a database transaction. All models passed as leading arguments are rebound to the transaction object; the last argument must be the async callback. Rejects if model classes are bound to different databases.
initializeimport { initialize } from './source/objection';
initialize(knex: Knex, modelClasses: typeof Model[]): Promise<void>;
initialize(modelClasses: typeof Model[]): Promise<void>;
Prefetches table metadata (column names, types) for all supplied model classes in parallel. Call once at startup before serving requests to avoid per-query metadata round-trips.
refimport { ref } from './source/objection';
ref(expression: string): ReferenceBuilder;
Creates a safe column reference for use inside query builder calls (e.g. where(ref('table.col'))) without raw string interpolation.
rawimport { raw } from './source/objection';
raw(sql: string, ...bindings: any[]): RawBuilder;
Wraps a raw SQL fragment with bindings. Use inside QueryBuilder methods when the query builder DSL is insufficient.
Define a Person model, bind knex, then run typed queries using the bundled QueryBuilder.
import Knex from 'knex';
// Import directly from the source entry point
const { Model } = require('./src/lib/objection/objection');
const knex = Knex({
client: 'pg',
connection: process.env.DATABASE_URL,
});
Model.knex(knex);
class Person extends Model {
static tableName = 'persons';
static get jsonSchema() {
return {
type: 'object',
required: ['name'],
properties: {
id: { type: 'integer' },
name: { type: 'string', minLength: 1 },
age: { type: 'integer' },
},
};
}
}
async function run() {
const people = await Person.query().where('age', '>', 18).orderBy('name');
console.log(people);
const inserted = await Person.query().insert({ name: 'Alice', age: 30 });
console.log(inserted.id);
}
run().finally(() => knex.destroy());
Wire a HasManyRelation and load it with a relation expression.
const { Model, HasManyRelation } = require('./src/lib/objection/objection');
class Animal extends Model {
static tableName = 'animals';
}
class Person extends Model {
static tableName = 'persons';
static get relationMappings() {
return {
pets: {
relation: HasManyRelation,
modelClass: Animal,
join: { from: 'persons.id', to: 'animals.owner_id' },
},
};
}
}
async function loadWithPets() {
// Fetch persons with their pets eagerly
const persons = await Person.query().withGraphFetched('pets');
console.log(persons[0].pets);
}
Use the transaction helper to coordinate inserts across two models atomically.
const { transaction, Model, HasManyRelation } = require('./src/lib/objection/objection');
// (Assume Person and Animal are defined as above and knex is bound)
async function createPersonWithPet(personData, animalData) {
return transaction(Person, Animal, async (BoundPerson, BoundAnimal, trx) => {
const person = await BoundPerson.query(trx).insert(personData);
const animal = await BoundAnimal.query(trx).insert({
...animalData,
owner_id: person.id,
});
return { person, animal };
});
}
createPersonWithPet({ name: 'Bob', age: 25 }, { name: 'Rex' })
.then(console.log)
.catch(console.error);
const Knex = require('knex');
const { initialize, Model } = require('./src/lib/objection/objection');
const knex = Knex({ client: 'pg', connection: process.env.DATABASE_URL });
Model.knex(knex);
// Assume Person and Animal models are defined and imported
async function bootstrap() {
await initialize(knex, [Person, Animal]);
console.log('Table metadata cached — server ready');
}
bootstrap().catch((err) => { console.error(err); process.exit(1); });
objection.js — Single entry point; re-exports every public class and helper. Import from here unless you need internal internals.transaction.js — Implements the transaction() function; handles both knex-instance and model-class overloads.initialize.js — Runs fetchTableMetadata on all models in parallel to warm the metadata cache.model/Model.js — The Model base class; all ORM functionality (query, validation, hooks, relations) anchors here.model/AjvValidator.js — Default JSON Schema validator backed by ajv + ajv-formats.model/Validator.js — Abstract validator base; subclass to replace Ajv with custom validation.model/ValidationError.js / NotFoundError.js — Typed errors thrown by model operations.model/graph/ — Builds an internal graph of model instances and edges for graph insert/upsert traversal.queryBuilder/QueryBuilder.js — Full-featured query builder; extends QueryBuilderBase with relation and graph methods.queryBuilder/RelationExpression.js — Parses eager-load strings like 'pets.vaccinations'.queryBuilder/RawBuilder.js / ReferenceBuilder.js / ValueBuilder.js / FunctionBuilder.js — Typed wrappers for SQL fragments used inside queries.queryBuilder/graph/ — Orchestrates graph upsert/insert/patch/delete across the model graph.queryBuilder/join/ — Implements join-based eager loading (joinRelated, withGraphJoined).queryBuilder/transformations/ — Applies post-build transformations (currently wraps MySQL modify subqueries).queryBuilder/operations/ — Internal operation objects that compose to form a final SQL query.relations/ — All five relation types: HasOneRelation, HasManyRelation, BelongsToOneRelation, HasOneThroughRelation, ManyToManyRelation.utils/ — Shared utilities: promise helpers, identifier case mappers, mixin/compose, object utilities.Model.knex() not called before queries — every query will throw; call Model.knex(knex) once at app startup before any query is executed.initialize() skipped in production — first queries will trigger per-model metadata fetches under load; always await initialize(knex, [...models]) during startup.require/module.exports); if your project uses ESM, import via createRequire or set "type": "commonjs" in the source package.json.AjvValidator uses ajv@8; if your project also uses ajv, pin both to ^8 to avoid duplicate validator instances.transaction() — all model classes passed to transaction() must share the same knex instance or the call rejects with a clear error; use Model.bindKnex(knex) per model if needed.WrapMysqlModifySubqueryTransformation in transformations/ is applied automatically; do not apply it manually or queries will be double-wrapped.I have the Objection.js ORM library source (objection@3.1.5) located at `src/lib/objection/`
and a usage guide at `USAGE.md`. My project is a Node.js/TypeScript Express API using knex
for database access.
Please help me integrate this source step-by-step:
1. Read `USAGE.md` for all real export names, file paths, and working examples.
2. Create a `src/db.ts` that initializes knex and calls `Model.knex()` using the source at
`src/lib/objection/objection.js`.
3. Create at least two Model subclasses matching my schema (I will describe them below).
4. Wire relation mappings using the relation classes exported from `src/lib/objection/objection.js`
(HasManyRelation, BelongsToOneRelation, etc.).
5. Add a startup call to `initialize()` from `src/lib/objection/initialize.js` before the
Express server begins listening.
6. Show a sample Express route that uses `transaction()` from `src/lib/objection/transaction.js`
to insert related records atomically.
Only use exports that appear in USAGE.md or the source files. Do not invent new APIs.
Upstream package reference: user@example.com
Objection.js is released under the MIT License. See source/LICENSE if present, or refer to the official repository. Upstream npm package: user@example.com.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费