bun-query-builder 0.1.2 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/actions/benchmark.d.ts +12 -0
  2. package/dist/actions/cache.d.ts +6 -0
  3. package/dist/actions/console.d.ts +2 -0
  4. package/dist/actions/data.d.ts +15 -0
  5. package/dist/actions/db-info.d.ts +17 -0
  6. package/dist/actions/db-optimize.d.ts +11 -0
  7. package/dist/actions/db-wipe.d.ts +10 -0
  8. package/dist/actions/file.d.ts +2 -1
  9. package/dist/actions/index.d.ts +25 -8
  10. package/dist/actions/inspect.d.ts +24 -0
  11. package/dist/actions/introspect.d.ts +2 -1
  12. package/dist/actions/make-model.d.ts +7 -0
  13. package/dist/actions/migrate-generate.d.ts +5 -0
  14. package/dist/actions/migrate-rollback.d.ts +6 -0
  15. package/dist/actions/migrate-status.d.ts +9 -0
  16. package/dist/actions/migrate.d.ts +13 -3
  17. package/dist/actions/model-show.d.ts +20 -0
  18. package/dist/actions/query-explain-all.d.ts +14 -0
  19. package/dist/actions/relation-diagram.d.ts +11 -0
  20. package/dist/actions/seed.d.ts +8 -0
  21. package/dist/actions/sql.d.ts +2 -1
  22. package/dist/actions/unsafe.d.ts +2 -1
  23. package/dist/actions/validate.d.ts +16 -0
  24. package/dist/actions/wait-ready.d.ts +2 -1
  25. package/dist/client.d.ts +230 -158
  26. package/dist/config.d.ts +2 -1
  27. package/dist/db.d.ts +10 -0
  28. package/dist/drivers/index.d.ts +12 -0
  29. package/dist/drivers/mysql.d.ts +187 -0
  30. package/dist/drivers/postgres.d.ts +173 -0
  31. package/dist/drivers/sqlite.d.ts +175 -0
  32. package/dist/factory.d.ts +3 -6
  33. package/dist/index.d.ts +11 -9
  34. package/dist/index.js +5444 -869
  35. package/dist/loader.d.ts +3 -2
  36. package/dist/meta.d.ts +10 -2
  37. package/dist/migrations.d.ts +43 -43
  38. package/dist/schema.d.ts +36 -177
  39. package/dist/seeder.d.ts +21 -0
  40. package/dist/types.d.ts +60 -143
  41. package/package.json +18 -27
  42. package/LICENSE.md +0 -21
  43. package/README.md +0 -150
package/dist/types.d.ts CHANGED
@@ -1,158 +1,80 @@
1
- /**
2
- * # `TransactionBackoffConfig`
3
- *
4
- * Controls exponential backoff between transaction retry attempts.
5
- *
6
- * - `baseMs`: Initial delay in milliseconds used for the first retry.
7
- * - `factor`: Multiplicative growth factor applied per attempt (e.g., 2 = doubles).
8
- * - `maxMs`: Maximum delay cap in milliseconds; backoff never exceeds this value.
9
- * - `jitter`: When true, adds a small randomization to the delay to reduce thundering herds.
10
- *
11
- * The delay for attempt n (1-indexed) is roughly: min(maxMs, baseMs * factor^(n-1)),
12
- * optionally adjusted by jitter.
13
- */
14
- export declare interface TransactionBackoffConfig {
1
+ export declare type SupportedDialect = 'postgres' | 'mysql' | 'sqlite'
2
+
3
+ export interface TransactionBackoffConfig {
15
4
  baseMs: number
16
5
  factor: number
17
6
  maxMs: number
18
7
  jitter: boolean
19
8
  }
20
- /**
21
- * # `TransactionDefaultsConfig`
22
- *
23
- * Default settings applied to transactional operations.
24
- *
25
- * - `retries`: Number of times a transaction may be retried on retriable errors
26
- * (e.g., deadlocks, serialization failures).
27
- * - `isolation`: Transaction isolation level.
28
- * - 'read committed': Prevents dirty reads; non-repeatable reads possible.
29
- * - 'repeatable read': Ensures stable snapshot for a transaction; phantom reads may vary by DB.
30
- * - 'serializable': Highest isolation; transactions appear to run one-by-one.
31
- * - `sqlStates`: Additional vendor error codes considered retriable.
32
- * - `backoff`: Backoff configuration applied between retries.
33
- */
34
- export declare interface TransactionDefaultsConfig {
9
+
10
+ export interface TransactionDefaultsConfig {
35
11
  retries: number
36
12
  isolation?: 'read committed' | 'repeatable read' | 'serializable'
37
13
  sqlStates: string[]
38
14
  backoff: TransactionBackoffConfig
39
15
  }
40
- /**
41
- * # `TimestampConfig`
42
- *
43
- * Column naming conventions for timestamp fields used by helpers.
44
- *
45
- * - `createdAt`: Column name for row creation time (e.g., 'created_at').
46
- * - `updatedAt`: Column name for last update time (e.g., 'updated_at').
47
- * - `defaultOrderColumn`: Column used by helpers like `latest()`/`oldest()`.
48
- */
49
- export declare interface TimestampConfig {
16
+
17
+ export interface TimestampConfig {
50
18
  createdAt: string
51
19
  updatedAt: string
52
20
  defaultOrderColumn: string
53
21
  }
54
- /**
55
- * # `PaginationConfig`
56
- *
57
- * Defaults for result pagination helpers.
58
- *
59
- * - `defaultPerPage`: Default LIMIT used by paginate helpers when not specified.
60
- * - `cursorColumn`: Default column used for cursor-based pagination (e.g., 'id').
61
- */
62
- export declare interface PaginationConfig {
22
+
23
+ export interface PaginationConfig {
63
24
  defaultPerPage: number
64
25
  cursorColumn: string
65
26
  }
66
- /**
67
- * # `AliasingConfig`
68
- *
69
- * Controls how selected columns from joined relations are aliased.
70
- *
71
- * - `relationColumnAliasFormat`:
72
- * - 'table_column': Aliases as `${table}_${column}` (e.g., `posts_title`).
73
- * - 'table.dot.column': Aliases with dot notation (e.g., `posts.title`).
74
- * - 'camelCase': Aliases as camelCase from `${table}_${column}` (e.g., `postsTitle`).
75
- */
76
- export declare interface AliasingConfig {
27
+
28
+ export interface AliasingConfig {
77
29
  relationColumnAliasFormat: 'table_column' | 'table.dot.column' | 'camelCase'
78
30
  }
79
- /**
80
- * # `RelationsConfig`
81
- *
82
- * Conventions for inferring foreign key names and singularization.
83
- *
84
- * - `foreignKeyFormat`:
85
- * - 'singularParent_id': Uses `${singular(parent)}_id` (e.g., `user_id`).
86
- * - 'parentId': Uses camelCase `parentId` (e.g., `userId`).
87
- * - `singularizeStrategy`:
88
- * - 'stripTrailingS': Naively remove trailing 's' when singularizing (default behavior when enabled elsewhere).
89
- * - 'none': Do not singularize relation/table names.
90
- */
91
- export declare interface RelationsConfig {
31
+
32
+ export interface RelationsConfig {
92
33
  foreignKeyFormat: 'singularParent_id' | 'parentId'
93
34
  singularizeStrategy?: 'stripTrailingS' | 'none'
35
+ maxDepth?: number
36
+ maxEagerLoad?: number
37
+ detectCycles?: boolean
94
38
  }
95
- /**
96
- * # `SqlConfig`
97
- *
98
- * Dialect-specific SQL toggles.
99
- *
100
- * - `randomFunction`:
101
- * - 'RANDOM()': PostgreSQL/SQLite style function for random ordering.
102
- * - 'RAND()': MySQL style function for random ordering.
103
- * - `sharedLockSyntax`:
104
- * - 'FOR SHARE': PostgreSQL style shared lock.
105
- * - 'LOCK IN SHARE MODE': MySQL style shared lock.
106
- * - `jsonContainsMode`:
107
- * - 'operator': Use native operators when available (e.g., Postgres `@>`).
108
- * - 'function': Use a function-based approach (e.g., `json_contains`) when operators are not available.
109
- */
110
- export declare interface SqlConfig {
39
+
40
+ export interface SqlConfig {
111
41
  randomFunction?: 'RANDOM()' | 'RAND()'
112
42
  sharedLockSyntax?: 'FOR SHARE' | 'LOCK IN SHARE MODE'
113
43
  jsonContainsMode?: 'operator' | 'function'
114
44
  }
115
- /**
116
- * # `QueryHooks`
117
- *
118
- * Optional lifecycle hooks around query execution. These are invoked for any
119
- * statement executed through the builder (select/insert/update/delete/raw).
120
- */
121
- export declare interface QueryHooks {
45
+
46
+ export interface QueryHooks {
122
47
  onQueryStart?: (event: { sql: string, params?: any[], kind?: 'select' | 'insert' | 'update' | 'delete' | 'raw' }) => void
123
48
  onQueryEnd?: (event: { sql: string, params?: any[], durationMs: number, rowCount?: number, kind?: 'select' | 'insert' | 'update' | 'delete' | 'raw' }) => void
124
49
  onQueryError?: (event: { sql: string, params?: any[], error: any, durationMs: number, kind?: 'select' | 'insert' | 'update' | 'delete' | 'raw' }) => void
125
50
  startSpan?: (event: { sql: string, params?: any[], kind?: 'select' | 'insert' | 'update' | 'delete' | 'raw' }) => { end: (error?: any) => void }
126
- }
127
- /**
128
- * # `FeatureToggles`
129
- *
130
- * Optional features that may be enabled per instance.
131
- *
132
- * - `distinctOn`: Enables PostgreSQL-like `DISTINCT ON (...)` behavior in builders.
133
- */
134
- export declare interface FeatureToggles {
51
+ beforeCreate?: (event: { table: string, data: any }) => void | Promise<void>
52
+ afterCreate?: (event: { table: string, data: any, result: any }) => void | Promise<void>
53
+ beforeUpdate?: (event: { table: string, data: any, where?: any }) => void | Promise<void>
54
+ afterUpdate?: (event: { table: string, data: any, where?: any, result: any }) => void | Promise<void>
55
+ beforeDelete?: (event: { table: string, where?: any }) => void | Promise<void>
56
+ afterDelete?: (event: { table: string, where?: any, result: any }) => void | Promise<void>
57
+ }
58
+
59
+ export interface FeatureToggles {
135
60
  distinctOn: boolean
136
61
  }
137
- /**
138
- * # `QueryBuilderConfig`
139
- *
140
- * Global configuration for the query builder.
141
- *
142
- * - `verbose`: Enables extra logging/diagnostics from the builder.
143
- * - `dialect`: Target SQL dialect. See `SupportedDialect` for details.
144
- * - `timestamps`: Timestamp column naming conventions.
145
- * - `pagination`: Defaults for pagination helpers.
146
- * - `aliasing`: How relation columns are aliased in SELECT lists.
147
- * - `relations`: Foreign key naming and singularization conventions.
148
- * - `transactionDefaults`: Default retry/backoff/isolation behavior for transactions.
149
- * - `sql`: Dialect-specific SQL toggles.
150
- * - `features`: Optional feature flags.
151
- * - `debug.captureText`: When true, the builder exposes a `toText()` method to capture SQL text in memory for debugging.
152
- */
153
- export declare interface QueryBuilderConfig {
62
+
63
+ export interface DatabaseConfig {
64
+ database: string
65
+ username: string
66
+ password: string
67
+ host: string
68
+ url?: string
69
+ port: number
70
+ }
71
+
72
+ export interface QueryBuilderConfig {
154
73
  verbose: boolean
155
74
  dialect: SupportedDialect
75
+
76
+ database: DatabaseConfig
77
+
156
78
  timestamps: TimestampConfig
157
79
  pagination: PaginationConfig
158
80
  aliasing: AliasingConfig
@@ -161,56 +83,51 @@ export declare interface QueryBuilderConfig {
161
83
  sql: SqlConfig
162
84
  features: FeatureToggles
163
85
  debug?: {
164
- /** When true, capture query text for debugging via `toText()`. */
165
86
  captureText: boolean
166
87
  }
167
88
  hooks?: QueryHooks
168
89
  softDeletes?: {
169
- /** When true, apply a default `WHERE deleted_at IS NULL` filter. */
170
90
  enabled: boolean
171
- /** Column name used for soft delete flag/timestamp. */
172
91
  column: string
173
- /** When true, default filter is applied unless `.withTrashed()` is called. */
174
92
  defaultFilter: boolean
175
93
  }
176
94
  }
177
- export declare interface CliOption {
95
+
96
+ export interface CliOption {
178
97
  verbose: boolean
179
98
  }
180
- export declare interface SqlOptions {
99
+
100
+ export interface SqlOptions {
181
101
  limit?: number
182
102
  }
183
- export declare interface WaitReadyOptions {
103
+
104
+ export interface WaitReadyOptions {
184
105
  attempts?: number
185
106
  delay?: number
186
107
  }
187
- export declare interface FileOptions {
108
+
109
+ export interface FileOptions {
188
110
  params?: string
189
111
  }
190
- export declare interface IntrospectOptions {
112
+
113
+ export interface IntrospectOptions {
191
114
  verbose?: boolean
192
115
  }
193
- export declare interface MigrateOptions {
116
+
117
+ export interface MigrateOptions {
194
118
  dialect?: SupportedDialect
195
119
  state?: string
196
120
  apply?: boolean
197
121
  full?: boolean
198
122
  }
199
- export declare interface GenerateMigrationResult {
123
+
124
+ export interface GenerateMigrationResult {
200
125
  sql: string
201
126
  sqlStatements: string[]
202
127
  hasChanges: boolean
203
128
  plan: any
204
129
  }
205
- export declare interface UnsafeOptions {
130
+
131
+ export interface UnsafeOptions {
206
132
  params?: string
207
- }
208
- /**
209
- * # `SupportedDialect`
210
- *
211
- * The SQL dialect used to tailor generated SQL and certain features.
212
- * - 'postgres': Uses `RANDOM()`, supports JSON operators (e.g. `@>`), `FOR SHARE`, `FOR UPDATE`, CTEs
213
- * - 'mysql': Uses `RAND()`, shared locks via `LOCK IN SHARE MODE`
214
- * - 'sqlite': Lightweight engine; some features are limited or emulated
215
- */
216
- export type SupportedDialect = 'postgres' | 'mysql' | 'sqlite'
133
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bun-query-builder",
3
3
  "type": "module",
4
- "version": "0.1.2",
4
+ "version": "0.1.6",
5
5
  "description": "A simple yet performant query builder for TypeScript. Built with Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -41,20 +41,20 @@
41
41
  ],
42
42
  "scripts": {
43
43
  "build": "bun --bun build.ts && bun run compile",
44
- "compile": "bun build ./bin/cli.ts --compile --minify --outfile bin/query-builder",
44
+ "compile": "bun build ./bin/cli.ts --compile --minify --outfile bin/qbx",
45
45
  "compile:all": "bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64",
46
- "compile:linux-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/query-builder-linux-x64",
47
- "compile:linux-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/query-builder-linux-arm64",
48
- "compile:windows-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/query-builder-windows-x64.exe",
49
- "compile:darwin-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/query-builder-darwin-x64",
50
- "compile:darwin-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/query-builder-darwin-arm64",
46
+ "compile:linux-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/qbx-linux-x64",
47
+ "compile:linux-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/qbx-linux-arm64",
48
+ "compile:windows-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/qbx-windows-x64.exe",
49
+ "compile:darwin-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/qbx-darwin-x64",
50
+ "compile:darwin-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/qbx-darwin-arm64",
51
51
  "zip": "bun run zip:all",
52
52
  "zip:all": "bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64",
53
- "zip:linux-x64": "zip -j bin/query-builder-linux-x64.zip bin/query-builder-linux-x64",
54
- "zip:linux-arm64": "zip -j bin/query-builder-linux-arm64.zip bin/query-builder-linux-arm64",
55
- "zip:windows-x64": "zip -j bin/query-builder-windows-x64.zip bin/query-builder-windows-x64.exe",
56
- "zip:darwin-x64": "zip -j bin/query-builder-darwin-x64.zip bin/query-builder-darwin-x64",
57
- "zip:darwin-arm64": "zip -j bin/query-builder-darwin-arm64.zip bin/query-builder-darwin-arm64",
53
+ "zip:linux-x64": "zip -j bin/qbx-linux-x64.zip bin/qbx-linux-x64",
54
+ "zip:linux-arm64": "zip -j bin/qbx-linux-arm64.zip bin/qbx-linux-arm64",
55
+ "zip:windows-x64": "zip -j bin/qbx-windows-x64.zip bin/qbx-windows-x64.exe",
56
+ "zip:darwin-x64": "zip -j bin/qbx-darwin-x64.zip bin/qbx-darwin-x64",
57
+ "zip:darwin-arm64": "zip -j bin/qbx-darwin-arm64.zip bin/qbx-darwin-arm64",
58
58
  "fresh": "bunx rimraf node_modules/ bun.lock && bun i",
59
59
  "prepublishOnly": "bun --bun run build && bun run compile:all && bun run zip",
60
60
  "test": "bun test",
@@ -62,28 +62,19 @@
62
62
  "lint:fix": "bunx --bun eslint . --fix",
63
63
  "changelog": "bunx logsmith --verbose",
64
64
  "changelog:generate": "bunx logsmith --output CHANGELOG.md",
65
- "release": "bun run changelog:generate && bunx bumpx prompt --recursive",
66
- "postinstall": "bunx git-hooks",
65
+ "release": "bun --bun run changelog:generate && bunx --bun bumpx prompt --recursive",
67
66
  "dev:docs": "bun --bun vitepress dev docs",
68
67
  "build:docs": "bun --bun vitepress build docs",
69
68
  "preview:docs": "bun --bun vitepress preview docs",
70
- "typecheck": "bun --bun tsc --noEmit"
69
+ "typecheck": "bun --bun tsc"
71
70
  },
72
71
  "dependencies": {
73
- "@stacksjs/launchpad": "^0.6.4"
72
+ "@stacksjs/clapp": "^0.2.0",
73
+ "@stacksjs/ts-validation": "^0.4.7",
74
+ "ts-mocker": "^0.1.5"
74
75
  },
75
76
  "devDependencies": {
76
- "@stacksjs/bumpx": "^0.1.61",
77
- "@stacksjs/docs": "^0.70.23",
78
- "@stacksjs/eslint-config": "^4.14.0-beta.3",
79
- "@stacksjs/gitlint": "^0.1.5",
80
- "@stacksjs/logsmith": "^0.1.15",
81
- "@types/bun": "^1.2.21",
82
- "buddy-bot": "^0.8.10",
83
- "bun-git-hooks": "^0.2.19",
84
- "bun-plugin-dtsx": "0.9.5",
85
- "bunfig": "^0.15.0",
86
- "typescript": "^5.9.2"
77
+ "bunfig": "^0.15.0"
87
78
  },
88
79
  "overrides": {
89
80
  "unconfig": "0.3.10"
package/LICENSE.md DELETED
@@ -1,21 +0,0 @@
1
- # MIT License
2
-
3
- Copyright (c) 2024 Open Web Foundation
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,150 +0,0 @@
1
- <p align="center"><img src=".github/art/cover.jpg" alt="Social Card of this repo"></p>
2
-
3
- [![npm version][npm-version-src]][npm-version-href]
4
- [![GitHub Actions][github-actions-src]][github-actions-href]
5
- [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
6
- <!-- [![npm downloads][npm-downloads-src]][npm-downloads-href] -->
7
- <!-- [![Codecov][codecov-src]][codecov-href] -->
8
-
9
- # bun-query-builder
10
-
11
- Fully-typed, model-driven Query Builder for Bun’s native `sql`.
12
-
13
- Define your data model once and get a type-safe query experience _(a la Kysely/Laravel)_, powered by Bun’s tagged templates for safety and performance.
14
-
15
- ## Features
16
-
17
- - **Typed from Models**: Infer tables/columns/PKs from your model files; `selectFrom('users')` and `where({ active: true })` are typed.
18
- - **Fluent Builder**: `select/insert/update/delete`, `where/andWhere/orWhere`, `join/leftJoin/rightJoin/crossJoin`, `groupBy/having`, `union/unionAll`.
19
- - **Relations**: `with(...)`, `withCount(...)`, `whereHas(...)`, `selectAllRelations()` with configurable aliasing.
20
- - **Utilities**: `distinct/distinctOn`, `orderByDesc/latest/oldest/inRandomOrder`, `whereColumn/whereRaw/groupByRaw/havingRaw`, JSON/date helpers.
21
- - **Pagination**: `paginate`, `simplePaginate`, `cursorPaginate`, plus `chunk/chunkById/eachById`.
22
- - **Transactions**: `transaction` with retries/backoff/isolation/onRetry/afterCommit; `savepoint`; distributed tx helpers.
23
- - **Configurable**: Dialect hints, timestamps, alias strategies, relation FK formats, JSON mode, random function, shared lock syntax.
24
- - **Bun API passthroughs**: `unsafe`, `file`, `simple`, pool `reserve/release`, `close`, `ping/waitForReady`.
25
- - **CLI**: Introspection, query printing, connectivity checks, file/unsafe execution, explain.
26
-
27
- > Note: LISTEN/NOTIFY and COPY helpers are scaffolded and will be wired as Bun exposes native APIs.
28
-
29
- ## Get Started
30
-
31
- ### Installation
32
-
33
- ```bash
34
- bun add bun-query-builder
35
- ```
36
-
37
- ### Usage
38
-
39
- ```ts
40
- import { buildDatabaseSchema, buildSchemaMeta, createQueryBuilder } from 'bun-query-builder'
41
-
42
- // Load or define your model files (see docs for model shape)
43
- const models = {
44
- User: { name: 'User', table: 'users', primaryKey: 'id', attributes: { id: { validation: { rule: {} } }, name: { validation: { rule: {} } }, active: { validation: { rule: {} } } } },
45
- } as const
46
-
47
- const schema = buildDatabaseSchema(models as any)
48
- const meta = buildSchemaMeta(models as any)
49
- const db = createQueryBuilder<typeof schema>({ schema, meta })
50
-
51
- // Fully-typed query
52
- const q = db
53
- .selectFrom('users')
54
- .where({ active: true })
55
- .orderBy('created_at', 'desc')
56
- .limit(10)
57
-
58
- const rows = await q.execute()
59
- ```
60
-
61
- ## Migrations
62
-
63
- Generate and execute migrations from your models:
64
-
65
- ```ts
66
- import { generateMigration, executeMigration } from 'bun-query-builder'
67
-
68
- // Generate migration from models directory
69
- const migration = await generateMigration('./models', {
70
- dialect: 'postgres',
71
- apply: true,
72
- full: true
73
- })
74
-
75
- // Execute the migration
76
- await executeMigration(migration)
77
- ```
78
-
79
- ### CLI
80
-
81
- ```bash
82
- # Print inferred schema from model dir
83
- query-builder introspect ./app/Models --verbose
84
-
85
- # Print a sample SQL (text) for a table
86
- query-builder sql ./app/Models users --limit 5
87
-
88
- # Connectivity:
89
- query-builder ping
90
- query-builder wait-ready --attempts 30 --delay 250
91
-
92
- # Execute a file or unsafe string (be careful!)
93
- query-builder file ./migrations/seed.sql
94
- query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"
95
-
96
- # Explain a query
97
- query-builder explain "SELECT * FROM users WHERE active = true"
98
- ```
99
-
100
- ## Testing
101
-
102
- ```bash
103
- bun test
104
- ```
105
-
106
- ## Changelog
107
-
108
- Please see our [releases](https://github.com/stackjs/bun-query-builder/releases) page for more information on what has changed recently.
109
-
110
- ## Contributing
111
-
112
- Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.
113
-
114
- ## Community
115
-
116
- For help, discussion about best practices, or any other conversation that would benefit from being searchable:
117
-
118
- [Discussions on GitHub](https://github.com/stacksjs/ts-starter/discussions)
119
-
120
- For casual chit-chat with others using this package:
121
-
122
- [Join the Stacks Discord Server](https://discord.gg/stacksjs)
123
-
124
- ## Postcardware
125
-
126
- “Software that is free, but hopes for a postcard.” We love receiving postcards from around the world showing where Stacks is being used! We showcase them on our website too.
127
-
128
- Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States 🌎
129
-
130
- ## Sponsors
131
-
132
- We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.
133
-
134
- - [JetBrains](https://www.jetbrains.com/)
135
- - [The Solana Foundation](https://solana.com/)
136
-
137
- ## License
138
-
139
- The MIT License (MIT). Please see [LICENSE](LICENSE.md) for more information.
140
-
141
- Made with 💙
142
-
143
- <!-- Badges -->
144
- [npm-version-src]: https://img.shields.io/npm/v/bun-query-builder?style=flat-square
145
- [npm-version-href]: https://npmjs.com/package/bun-query-builder
146
- [github-actions-src]: https://img.shields.io/github/actions/workflow/status/stacksjs/ts-starter/ci.yml?style=flat-square&branch=main
147
- [github-actions-href]: https://github.com/stacksjs/ts-starter/actions?query=workflow%3Aci
148
-
149
- <!-- [codecov-src]: https://img.shields.io/codecov/c/gh/stacksjs/ts-starter/main?style=flat-square
150
- [codecov-href]: https://codecov.io/gh/stacksjs/ts-starter -->