Kade 판매

Lucid is a full-featured SQL ORM for AdonisJS built on Knex, offering an Active Record pattern, fluent query builder, migrations, seeders, and model factories for backend developers.
This block provides the full Lucid ORM source for AdonisJS, including a Knex-based SQL query builder, Active Record models, schema migrations, database seeders, and model factories. It targets Node.js/TypeScript backend developers integrating a production-grade SQL data layer into an AdonisJS or standalone Express/Fastify project.
bindings/ - AdonisJS REPL, Vine.js validation, and transformer bindingsclients/ - LibSQL client adapter (CJS)connection/ - Database connection lifecycle, pooling, and logging via Knexdatabase/ - Core Database class, query builders, paginators, health checksdialects/ - Per-driver dialect implementations (pg, mysql, sqlite, mssql, libsql, etc.)factories/ - Model factory system for generating test datahelpers/ - Pretty-print utility for query outputmigration/ - Migration runner, schema dumper, and migration source loaderorm/ - Base model, decorators, adapter, and model key managementplugins/ - Knex plugin integrationsquery_client/ - QueryClient wrapping a connection for query executionquery_reporter/ - Query event reporting hooksquery_runner/ - Low-level query execution over a Knex connectionschema/ - Schema builder used inside migration filesseeders/ - Database seeder runnertest_utils/ - Test helpers for database setup/teardowntransaction_client/ - Transaction-aware query clienttypes/ - TypeScript type definitions for all contractsutils/ - Shared internal utilitiesdefine_config.ts - Config definition helper with type safetyerrors.ts - Named error classes thrown by Lucid internalsnpm install knex knex-dynamic-connection tarn @poppinss/macroable @poppinss/utils @poppinss/hooks @poppinss/qs @faker-js/faker deepmerge fast-deep-equal igniculus kleur pretty-hrtime slash
# Choose your database driver(s):
npm install pg # PostgreSQL / Redshift
npm install mysql2 # MySQL / MariaDB
npm install better-sqlite3 # SQLite (better-sqlite3)
npm install sqlite3 # SQLite (sqlite3)
npm install mssql # Microsoft SQL Server
npm install oracledb # Oracle
npm install @libsql/client # LibSQL / Turso
격리된 샌드박스를 띄워 서버에서 바로 실행하세요 — 로컬 설정 불필요.
이 버전에 대한 Tetrees AI Review
This Express backend / api 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 b876f172a246f379…
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을 받으세요.
아직 리뷰가 없습니다.
토론을 불러오는 중…
AdonisJS core peer packages (required if wiring into AdonisJS IoC):
npm install @adonisjs/core @adonisjs/presets
No native pod/Android linking steps are required. better-sqlite3 requires a C++ build toolchain (node-gyp); ensure python, make, and a C++ compiler are available.
source/ directory into your project, e.g. src/lucid/.tsconfig.json to include the source:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Bundler",
"target": "ES2022",
"strict": true
},
"include": ["src/**/*"]
}
clients/libsql.cjs is CommonJS, ensure your bundler or ts-node handles mixed ESM/CJS. With ts-node add:
{ "ts-node": { "esm": true } }
DB_CONNECTION=pg
PG_HOST=127.0.0.1
PG_PORT=5432
PG_USER=lucid
PG_PASSWORD=secret
PG_DB_NAME=myapp
db.ts bootstrap file (see examples below) that instantiates Database with a config object matching DatabaseConfig.MigrationRunner at your migrations directory and call run() during app startup or a CLI command.Databaseimport { Database } from './src/lucid/database/main.js'
const db = new Database(config, logger, emitter)
The central entry point. Manages multiple named connections via ConnectionManager, exposes query(), from(), insertQuery(), rawQuery(), transaction(), and connection(). Extend with Database.macro() for project-wide helpers. Use this as a singleton injected across your service layer.
Connectionimport { Connection } from './src/lucid/connection/index.js'
const conn = new Connection('primary', config, logger)
conn.open()
const knexClient: Knex = conn.client!
Wraps a single Knex connection with lifecycle events (connect, disconnect, error). Supports read/write replica splitting via hasReadWriteReplicas. Use directly only when you need low-level pool introspection; normally obtained through Database.
FactoryManager / factoryimport factory from './src/lucid/factories/main.js'
import { FactoryManager } from './src/lucid/factories/main.js'
const UserFactory = factory.define(User, ({ faker }) => ({
email: faker.internet.email(),
name: faker.person.fullName(),
}))
FactoryManager.define() registers a model factory that generates stub rows for tests. Call make() for in-memory instances or create() to persist. Use stubId() to override the auto-increment stub ID strategy.
MigrationRunnerimport { MigrationRunner } from './src/lucid/migration/main.js'
const runner = new MigrationRunner(db, app, { direction: 'up', dryRun: false })
await runner.run()
Discovers migration files, tracks their state in a adonis_schema table, and runs them in order. Supports up, down, and --dry-run. SchemaDumper (also exported from migration/main.ts) writes a SQL dump of the current schema.
Initialize Database with a PostgreSQL config and execute a raw SQL statement.
import { Database } from './src/lucid/database/main.js'
import { defineConfig } from './src/lucid/define_config.js'
const config = defineConfig({
connection: 'pg',
connections: {
pg: {
client: 'postgres',
connection: {
host: process.env.PG_HOST ?? '127.0.0.1',
port: Number(process.env.PG_PORT ?? 5432),
user: process.env.PG_USER ?? 'lucid',
password: process.env.PG_PASSWORD ?? '',
database: process.env.PG_DB_NAME ?? 'myapp',
},
},
},
})
// Provide AdonisJS-compatible logger and emitter stubs if outside AdonisJS
const db = new Database(config, logger, emitter)
const result = await db.rawQuery('SELECT NOW() as now')
console.log(result.rows[0].now)
await db.manager.closeAll()
Use FactoryManager to define a User factory, then create 10 persisted rows inside a test.
import factory from './src/lucid/factories/main.js'
import { User } from './src/models/user.js' // Your Lucid model
const UserFactory = factory
.define(User, ({ faker }) => {
return {
email: faker.internet.email(),
username: faker.internet.username(),
avatarUrl: faker.image.avatarGitHub(),
}
})
.build()
// Inside a test
const users = await UserFactory.createMany(10)
console.log(users.map((u) => u.email))
Invoke the migration runner from a standalone Node.js script (e.g., a Dockerfile entrypoint).
import { MigrationRunner } from './src/lucid/migration/main.js'
import { Database } from './src/lucid/database/main.js'
// Assume `db` and `app` are already initialised
const runner = new MigrationRunner(db, app, {
direction: 'up',
dryRun: false,
connectionName: 'pg',
})
await runner.run()
for (const file of runner.migratedFiles) {
console.log(`Migrated: ${file.file.name} — status: ${file.status}`)
}
process.exit(0)
connection/index.ts - Connection class; opens/closes the Knex pool, emits lifecycle events, supports R/W replicas.connection/manager.ts - ConnectionManager; maintains a registry of named Connection instances.connection/logger.ts - Thin wrapper adapting AdonisJS logger to Knex query logging.database/main.ts - Database façade; top-level API for all query/transaction/connection operations.database/query_builder/ - DatabaseQueryBuilder, InsertQueryBuilder, OnConflictQueryBuilder, RawQueryBuilder.database/static_builder/ - RawBuilder and ReferenceBuilder for pre-built SQL fragments.database/paginator/ - SimplePaginator for offset-based pagination results.database/checks/ - DbCheck and DbConnectionCountCheck health-check classes.dialects/index.ts - Maps client names to dialect classes; exports clientsToDialectsMapping.dialects/*.ts - Per-driver dialect logic (date handling, returning clauses, DDL quirks).factories/main.ts - FactoryManager singleton and factory default export.factories/factory_model.ts - FactoryModel with .make(), .create(), .makeMany(), .createMany().factories/relations/ - Factory helpers for hasOne, hasMany, belongsTo, manyToMany.migration/main.ts - Re-exports MigrationRunner and SchemaDumper.migration/runner.ts - Core runner that tracks and executes migration files.migration/source.ts - Discovers migration files from configured directories.migration/schema_dumper.ts - Dumps current schema to SQL for version control.orm/base_model/ - BaseModel with dirty tracking, lifecycle hooks, serialization.orm/decorators/ - @column, @hasMany, @belongsTo, and other relation decorators.orm/adapter/ - Adapter bridging models to QueryClient.schema/ - Schema base class used inside migration files to build DDL.seeders/ - Seeder runner that executes seed files in order.query_client/ - QueryClient selecting read or write Knex connection per query.transaction_client/ - TransactionClient wrapping a Knex transaction.types/ - All TypeScript interfaces and contract types.define_config.ts - defineConfig() helper for typed Lucid configuration objects.errors.ts - Named error subclasses (E_MISSING_MODEL_ATTRIBUTE, etc.).clients/libsql.cjs - Import it with createRequire or ensure your bundler treats .cjs files as CommonJS; do not rename to .js.knex-dynamic-connection version pin - patchKnex API changes between minor versions; pin knex-dynamic-connection to the version specified in the upstream package.json lock file.@adonisjs/core logger/emitter - Database constructor expects AdonisJS Logger and Emitter shapes; outside AdonisJS, pass a minimal stub implementing .debug(), .error(), .emit() or the constructor will throw at runtime.better-sqlite3 native build failure - Run npm rebuild better-sqlite3 after switching Node.js versions; ensure node-gyp dependencies (python3, make, C++ compiler) are installed.dialectName deprecation warning - The Connection.dialectName property is deprecated; use Connection.clientName in all new code to avoid future breakage.Database.connectionGlobalTransactions holds live TransactionClient references; always commit() or rollback() inside finally blocks or the pool will exhaust open connections.I have dropped the Lucid ORM source from @adonisjs/lucid@22.4.2 into `src/lucid/`
of my Node.js TypeScript project. The integration guide is in `USAGE.md`.
Please help me integrate it step by step:
1. Read `USAGE.md` and `src/lucid/define_config.ts` to understand the config shape.
2. Create `src/db.ts` that instantiates `Database` from `src/lucid/database/main.ts`
using environment variables for the connection (postgres by default).
3. Wire the `Database` instance as a singleton exportable from `src/db.ts`.
4. Create a sample migration file under `database/migrations/` using the `Schema`
base class from `src/lucid/schema/`.
5. Create a `User` model extending `BaseModel` from `src/lucid/orm/base_model/`
with `@column` decorators for `id`, `email`, and `createdAt`.
6. Create a `UserFactory` in `database/factories/user_factory.ts` using
`factory.define` from `src/lucid/factories/main.ts`.
7. Show how to run migrations programmatically using `MigrationRunner` from
`src/lucid/migration/main.ts`.
8. Add a health check using `DbCheck` from `src/lucid/database/main.ts`.
Use only the APIs documented in `USAGE.md`. Do not invent method names.
AdonisJS Lucid is released under the MIT License. See source/LICENSE.md if present, or refer to the upstream repository. The upstream npm package is @adonisjs/lucid maintained by Harminder Virk and the AdonisJS core team.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
전체 설치 가이드와 연동 프롬프트는 구매 후 열람할 수 있습니다.
Automation, Utilities & Developer Tools
무료