@gallopsystems/agent-skills 1.14.0 → 1.15.0

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.
@@ -0,0 +1,374 @@
1
+ ## JSON, JSONB, and Array Handling
2
+
3
+ ### JSONB Columns
4
+
5
+ **NO `JSON.stringify` or `JSON.parse` needed!** The `pg` driver handles JSONB automatically:
6
+
7
+ ```typescript
8
+ // INSERT - pass objects directly
9
+ await db
10
+ .insertInto("user")
11
+ .values({
12
+ email: "test@example.com",
13
+ metadata: { preferences: { theme: "dark" }, count: 42 },
14
+ })
15
+ .execute();
16
+
17
+ // UPDATE - pass objects directly
18
+ await db
19
+ .updateTable("user")
20
+ .set({
21
+ metadata: { preferences: { theme: "light" } },
22
+ })
23
+ .where("id", "=", userId)
24
+ .execute();
25
+
26
+ // READ - returns parsed object, not string
27
+ const user = await db
28
+ .selectFrom("user")
29
+ .select(["id", "metadata"])
30
+ .executeTakeFirst();
31
+ console.log(user.metadata.preferences.theme); // "dark" - already an object!
32
+ ```
33
+
34
+ ### Array Columns (text[], int[], etc.)
35
+
36
+ **NO `JSON.stringify` needed for array columns!** The `pg` driver handles arrays natively:
37
+
38
+ ```typescript
39
+ // INSERT with array - pass array directly
40
+ await db
41
+ .insertInto("product")
42
+ .values({
43
+ name: "Product",
44
+ tags: ["phone", "electronics", "premium"], // Direct array!
45
+ })
46
+ .execute();
47
+
48
+ // READ - returns as native JavaScript array
49
+ const product = await db
50
+ .selectFrom("product")
51
+ .select(["name", "tags"])
52
+ .executeTakeFirst();
53
+ console.log(product.tags); // ["phone", "electronics", "premium"]
54
+
55
+ // UPDATE array
56
+ await db
57
+ .updateTable("product")
58
+ .set({ tags: ["updated", "tags"] })
59
+ .where("id", "=", productId)
60
+ .execute();
61
+ ```
62
+
63
+ ### Querying Arrays
64
+
65
+ ```typescript
66
+ // Array contains all values (@>) - operator works natively!
67
+ .where("tags", "@>", sql`ARRAY['phone', 'premium']::text[]`)
68
+
69
+ // Arrays overlap (&&) - operator works natively!
70
+ .where("tags", "&&", sql`ARRAY['premium', 'basic']::text[]`)
71
+
72
+ // Array contains value (ANY) - type-safe with eb.fn
73
+ .where((eb) => eb(sql`${searchTerm}`, "=", eb.fn("any", [eb.ref("tags")])))
74
+ // eb.ref("tags") validates column exists - eb.ref("invalid") would be a TS error
75
+ ```
76
+
77
+ ### Querying JSONB
78
+
79
+ ```typescript
80
+ // Key exists (?) - operator works natively!
81
+ .where("metadata", "?", "theme")
82
+
83
+ // Any key exists (?|) - operator works natively!
84
+ .where("metadata", "?|", sql`array['theme', 'language']`)
85
+
86
+ // All keys exist (?&) - operator works natively!
87
+ .where("metadata", "?&", sql`array['theme', 'notifications']`)
88
+
89
+ // JSONB contains (@>) - operator works natively!
90
+ .where("metadata", "@>", sql`'{"notifications": true}'::jsonb`)
91
+
92
+ // Extract field as text (->> as operator) - type-safe!
93
+ .where((eb) => eb(eb("metadata", "->>", "theme"), "=", "dark"))
94
+ // eb("metadata", ...) validates column - eb("invalid", ...) would be TS error
95
+
96
+ // Extract nested path (#>> still needs sql``)
97
+ .where(sql`metadata#>>'{preferences,theme}'`, "=", "dark")
98
+
99
+ // In SELECT - type-safe with eb()
100
+ .select((eb) => [
101
+ eb("metadata", "->", "preferences").as("prefs"), // Returns JSONB
102
+ eb("metadata", "->>", "theme").as("theme"), // Returns text
103
+ ])
104
+ // Nested paths still need sql``
105
+ .select(sql`metadata#>'{preferences,theme}'`.as("t")) // Nested as JSONB
106
+ .select(sql<string>`metadata#>>'{a,b}'`.as("t")) // Nested as text
107
+ ```
108
+
109
+ ### JSONPath (PostgreSQL 12+)
110
+
111
+ ```typescript
112
+ // JSONPath match (@@) - works as native operator!
113
+ .where("metadata", "@@", sql`'$.preferences.theme == "dark"'`)
114
+
115
+ // JSONPath exists (@?) - NOT in Kysely's allowlist, use function instead
116
+ // Use jsonb_path_exists() for type-safe column validation
117
+ .where((eb) =>
118
+ eb.fn("jsonb_path_exists", [eb.ref("metadata"), sql`'$.preferences.theme'`])
119
+ )
120
+ // eb.ref("metadata") validates column - eb.ref("invalid") would be TS error
121
+
122
+ // Extract with JSONPath - type-safe with eb.fn
123
+ .select((eb) => [
124
+ "id",
125
+ eb.fn("jsonb_path_query_first", [eb.ref("metadata"), sql`'$.preferences.theme'`]).as("theme"),
126
+ ])
127
+
128
+ // JSONPath with variables
129
+ const searchValue = "dark";
130
+ .where((eb) =>
131
+ eb.fn("jsonb_path_exists", [
132
+ eb.ref("metadata"),
133
+ sql`'$.preferences.theme ? (@ == $val)'`,
134
+ sql`jsonb_build_object('val', ${searchValue}::text)`,
135
+ ])
136
+ )
137
+ ```
138
+
139
+ ### Conditional Queries ($if)
140
+
141
+ Use `$if()` for runtime-conditional query modifications:
142
+
143
+ ```typescript
144
+ const result = await db
145
+ .selectFrom("user")
146
+ .selectAll()
147
+ .$if(!includeInactive, (qb) => qb.where("is_active", "=", true))
148
+ .$if(includeMetadata, (qb) => qb.select("metadata"))
149
+ .$if(!!searchTerm, (qb) => qb.where("name", "like", `%${searchTerm}%`))
150
+ .$if(!!roleFilter, (qb) => qb.where("role", "in", roleFilter!))
151
+ .execute();
152
+ ```
153
+
154
+ **Type behavior**: Columns added via `$if` become optional in the result type since inclusion isn't guaranteed at compile time.
155
+
156
+ ### Relations (jsonArrayFrom / jsonObjectFrom)
157
+
158
+ Kysely is NOT an ORM - it uses PostgreSQL's JSON functions for nested data:
159
+
160
+ ```typescript
161
+ import { jsonArrayFrom, jsonObjectFrom } from "kysely/helpers/postgres";
162
+
163
+ // One-to-many: User with their orders
164
+ const users = await db
165
+ .selectFrom("user")
166
+ .select((eb) => [
167
+ "user.id",
168
+ "user.email",
169
+ jsonArrayFrom(
170
+ eb
171
+ .selectFrom("order")
172
+ .select(["order.id", "order.status", "order.total_amount"])
173
+ .whereRef("order.user_id", "=", "user.id")
174
+ .orderBy("order.created_at", "desc")
175
+ ).as("orders"),
176
+ ])
177
+ .execute();
178
+
179
+ // Many-to-one: Product with its category
180
+ const products = await db
181
+ .selectFrom("product")
182
+ .select((eb) => [
183
+ "product.id",
184
+ "product.name",
185
+ jsonObjectFrom(
186
+ eb
187
+ .selectFrom("category")
188
+ .select(["category.id", "category.name"])
189
+ .whereRef("category.id", "=", "product.category_id")
190
+ ).as("category"),
191
+ ])
192
+ .execute();
193
+ ```
194
+
195
+ **Critical: Use explicit `.select()` instead of `.selectAll()` with nested json helpers**
196
+
197
+ When using `jsonObjectFrom` containing a nested `jsonArrayFrom` (or vice versa), using `selectAll("table")` breaks TypeScript's type inference. The result type becomes `unknown` or loses the nested structure, requiring `$castTo` to fix.
198
+
199
+ ```typescript
200
+ // WRONG - selectAll() breaks type inference for nested json helpers
201
+ const invoice = await db
202
+ .selectFrom("invoices")
203
+ .selectAll("invoices")
204
+ .select((eb) => [
205
+ jsonObjectFrom(
206
+ eb
207
+ .selectFrom("payment_plans")
208
+ .selectAll() // ❌ This breaks type inference!
209
+ .select((eb2) => [
210
+ jsonArrayFrom(
211
+ eb2.selectFrom("installments").selectAll()
212
+ .whereRef("installments.plan_id", "=", "payment_plans.id")
213
+ ).as("installments"),
214
+ ])
215
+ .whereRef("payment_plans.invoice_id", "=", "invoices.id")
216
+ ).as("payment_plan"), // Type is unknown or broken
217
+ ])
218
+ .executeTakeFirst();
219
+
220
+ // RIGHT - explicit select() preserves type inference
221
+ const invoice = await db
222
+ .selectFrom("invoices")
223
+ .selectAll("invoices")
224
+ .select((eb) => [
225
+ jsonObjectFrom(
226
+ eb
227
+ .selectFrom("payment_plans")
228
+ .select([ // ✅ Explicit columns!
229
+ "payment_plans.id",
230
+ "payment_plans.invoice_id",
231
+ "payment_plans.notes",
232
+ "payment_plans.created_at",
233
+ ])
234
+ .select((eb2) => [
235
+ jsonArrayFrom(
236
+ eb2.selectFrom("installments").selectAll()
237
+ .whereRef("installments.plan_id", "=", "payment_plans.id")
238
+ ).as("installments"),
239
+ ])
240
+ .whereRef("payment_plans.invoice_id", "=", "invoices.id")
241
+ ).as("payment_plan"), // Type is properly inferred!
242
+ ])
243
+ .executeTakeFirst();
244
+ ```
245
+
246
+ **Why this happens**: Kysely's type inference for nested json helpers relies on tracking the selected columns through the query chain. `selectAll()` returns all columns dynamically, which confuses TypeScript when combined with additional `.select()` calls that add nested json helpers. Using explicit column names gives TypeScript the static information it needs.
247
+
248
+ **Rule of thumb**: When combining `jsonObjectFrom`/`jsonArrayFrom` with nested json helpers, always use explicit `.select([...columns])` instead of `.selectAll()` on the subquery containing the nested helper.
249
+
250
+ ### Reusable Helpers
251
+
252
+ Create composable, type-safe helper functions using `Expression<T>`:
253
+
254
+ ```typescript
255
+ import { Expression, sql } from "kysely";
256
+
257
+ // Helper that takes and returns Expression<string>
258
+ function lower(expr: Expression<string>) {
259
+ return sql<string>`lower(${expr})`;
260
+ }
261
+
262
+ // Use in queries
263
+ .where(({ eb, ref }) => eb(lower(ref("email")), "=", email.toLowerCase()))
264
+ ```
265
+
266
+ ### Splitting Query Building and Execution
267
+
268
+ Build queries without executing, useful for dynamic query construction:
269
+
270
+ ```typescript
271
+ // Build query (doesn't execute)
272
+ let query = db
273
+ .selectFrom("user")
274
+ .select(["id", "email"]);
275
+
276
+ // Add conditions dynamically
277
+ if (role) {
278
+ query = query.where("role", "=", role);
279
+ }
280
+ if (isActive !== undefined) {
281
+ query = query.where("is_active", "=", isActive);
282
+ }
283
+
284
+ // Execute when ready
285
+ const results = await query.execute();
286
+
287
+ // Or compile to SQL without executing
288
+ const compiled = query.compile();
289
+ console.log(compiled.sql); // The SQL string
290
+ console.log(compiled.parameters); // Bound parameters
291
+ ```
292
+
293
+ ### Subqueries
294
+
295
+ ```typescript
296
+ // Subquery in WHERE
297
+ .where("id", "in",
298
+ db.selectFrom("order").select("user_id").where("status", "=", "completed")
299
+ )
300
+
301
+ // EXISTS subquery
302
+ .where((eb) =>
303
+ eb.exists(
304
+ db.selectFrom("review")
305
+ .select(sql`1`.as("one"))
306
+ .whereRef("review.product_id", "=", eb.ref("product.id"))
307
+ )
308
+ )
309
+ ```
310
+
311
+ ### INSERT Operations
312
+
313
+ ```typescript
314
+ // Single insert with returning
315
+ const user = await db
316
+ .insertInto("user")
317
+ .values({ email: "test@example.com", first_name: "Test", last_name: "User" })
318
+ .returning(["id", "email"])
319
+ .executeTakeFirst();
320
+
321
+ // Multiple rows
322
+ await db
323
+ .insertInto("user")
324
+ .values([
325
+ { email: "a@example.com", first_name: "A", last_name: "User" },
326
+ { email: "b@example.com", first_name: "B", last_name: "User" },
327
+ ])
328
+ .execute();
329
+
330
+ // Upsert (ON CONFLICT) - type-safe with expression builder
331
+ await db
332
+ .insertInto("product")
333
+ .values({ sku: "ABC123", name: "Product", stock_quantity: 10 })
334
+ .onConflict((oc) =>
335
+ oc.column("sku").doUpdateSet((eb) => ({
336
+ stock_quantity: eb("product.stock_quantity", "+", eb.ref("excluded.stock_quantity")),
337
+ }))
338
+ )
339
+ .execute();
340
+ // eb("product.invalid_column", ...) would be a TypeScript error!
341
+
342
+ // Insert from SELECT
343
+ await db
344
+ .insertInto("archive")
345
+ .columns(["user_id", "data", "archived_at"])
346
+ .expression(
347
+ db.selectFrom("user")
348
+ .select(["id", "metadata", sql`now()`.as("archived_at")])
349
+ .where("is_active", "=", false)
350
+ )
351
+ .execute();
352
+ ```
353
+
354
+ ### UPDATE Operations
355
+
356
+ ```typescript
357
+ // Simple update
358
+ await db
359
+ .updateTable("user")
360
+ .set({ is_active: false })
361
+ .where("id", "=", userId)
362
+ .execute();
363
+
364
+ // Update with expression
365
+ await db
366
+ .updateTable("product")
367
+ .set((eb) => ({
368
+ stock_quantity: eb("stock_quantity", "+", 10),
369
+ }))
370
+ .where("sku", "=", "ABC123")
371
+ .returning(["id", "stock_quantity"])
372
+ .executeTakeFirst();
373
+ ```
374
+
@@ -0,0 +1,162 @@
1
+ ## Migrations
2
+
3
+ ### Configuration (kysely.config.ts)
4
+
5
+ ```typescript
6
+ import { PostgresDialect } from "kysely";
7
+ import { defineConfig } from "kysely-ctl";
8
+ import pg from "pg";
9
+
10
+ export default defineConfig({
11
+ dialect: new PostgresDialect({
12
+ pool: new pg.Pool({
13
+ connectionString: process.env.DATABASE_URL,
14
+ }),
15
+ }),
16
+ migrations: {
17
+ migrationFolder: "src/db/migrations",
18
+ },
19
+ seeds: {
20
+ seedFolder: "src/db/seeds",
21
+ },
22
+ });
23
+ ```
24
+
25
+ ### Migration Commands
26
+
27
+ ```bash
28
+ npx kysely migrate:make migration-name # Create migration
29
+ npx kysely migrate:latest # Run all pending migrations
30
+ npx kysely migrate:down # Rollback last migration
31
+ npx kysely seed make seed-name # Create seed
32
+ npx kysely seed run # Run all seeds
33
+ ```
34
+
35
+ Seeds that feed a preview/dev box have their own conventions (idempotency,
36
+ order-independence, factories shared with tests, a validity harness) — see
37
+ [seeding-pattern.md](references/seeding-pattern.md).
38
+
39
+ ### Migration File Structure
40
+
41
+ ```typescript
42
+ import type { Kysely } from "kysely";
43
+ import { sql } from "kysely";
44
+
45
+ // Always use Kysely<any> - migrations should be frozen in time
46
+ export async function up(db: Kysely<any>): Promise<void> {
47
+ await db.schema
48
+ .createTable("user")
49
+ .addColumn("id", "bigint", (col) => col.primaryKey().generatedAlwaysAsIdentity())
50
+ .addColumn("email", "text", (col) => col.notNull().unique())
51
+ .addColumn("created_at", "timestamptz", (col) => col.notNull().defaultTo(sql`now()`))
52
+ .execute();
53
+
54
+ // IMPORTANT: Always index foreign key columns!
55
+ await db.schema.createIndex("idx_order_user_id").on("order").column("user_id").execute();
56
+ }
57
+
58
+ export async function down(db: Kysely<any>): Promise<void> {
59
+ await db.schema.dropTable("user").execute();
60
+ }
61
+ ```
62
+
63
+ ### Recommended Column Types
64
+
65
+ ```typescript
66
+ // Primary keys: Use identity columns (SQL standard, prevents accidental ID conflicts)
67
+ .addColumn("id", "bigint", (col) => col.primaryKey().generatedAlwaysAsIdentity())
68
+ // NOT serial/bigserial - those allow manual ID inserts that can cause conflicts
69
+
70
+ // Timestamps: Always use timestamptz (stores UTC, converts to client timezone)
71
+ .addColumn("created_at", "timestamptz", (col) => col.notNull().defaultTo(sql`now()`))
72
+ // NOT timestamp - loses timezone information
73
+
74
+ // Money: Use numeric with precision (exact decimal, no floating point errors)
75
+ .addColumn("price", "numeric(10, 2)", (col) => col.notNull())
76
+ // NOT float/real/double precision - those have rounding errors
77
+
78
+ // Strings: Use text (no length limit, same performance as varchar)
79
+ .addColumn("name", "text", (col) => col.notNull())
80
+ // varchar(n) only if you need a hard length constraint
81
+
82
+ // JSON: Use jsonb (binary, indexable, faster queries)
83
+ .addColumn("metadata", "jsonb")
84
+ // NOT json - stored as text, no indexing, slower
85
+
86
+ // Foreign keys: Create indexes manually (PostgreSQL doesn't auto-index FKs)
87
+ await db.schema.createIndex("idx_order_user_id").on("order").column("user_id").execute();
88
+ ```
89
+
90
+ ### Data Type Gotchas
91
+
92
+ ```typescript
93
+ // CORRECT - Space after comma in numeric types
94
+ .addColumn("price", "numeric(10, 2)")
95
+
96
+ // WRONG - Will fail with "invalid column data type"
97
+ .addColumn("price", "numeric(10,2)")
98
+
99
+ // For complex types, use sql template
100
+ .addColumn("price", sql`numeric(10, 2)`)
101
+ ```
102
+
103
+ ### Migration Ordering Is Append-Only — Out-of-Order Timestamps Break Prod Deploys
104
+
105
+ Kysely's migrator enforces a **strict append-only ledger**: it refuses to run any
106
+ unexecuted migration whose timestamp sorts *before* the last-executed one
107
+ (throwing `Corrupted migrations: previously executed migration ... is missing`).
108
+ This bites when two branches each add a migration, and the one that merges *second*
109
+ carries the *earlier* timestamp:
110
+
111
+ ```
112
+ branch A merges first → 1700000200000_drop_thing (runs in prod)
113
+ branch B merges second → 1700000100000_add_table (timestamp is EARLIER)
114
+ → 1700000100001_add_column
115
+ ```
116
+
117
+ Prod has already recorded `...200000_drop_thing` as executed. On the next deploy
118
+ the `migrate` job sees two pending migrations that sort *before* it, throws
119
+ "Corrupted migrations", and **exits non-zero**. If migrations run as a pre-deploy
120
+ job (common on PaaS like DigitalOcean App Platform), the failed job fails the whole
121
+ deploy and the platform **auto-rolls-back to the previous image** — so prod silently
122
+ stays on stale code and every subsequent deploy fails the same way. A self-reinforcing
123
+ loop that looks like a deploy/token problem but is really a migration-ledger problem.
124
+
125
+ **Prevent it:** before merging a long-lived branch, check whether `main` has merged
126
+ any migration with a *later* timestamp than yours. If so, regenerate your migration's
127
+ timestamp so it sorts last (`migrate:make` again, or rename the file) **before it
128
+ merges** — only safe while the migration has not yet run in any shared DB. Never
129
+ re-stamp a migration that prod has already executed; that forces it to re-run.
130
+
131
+ **Fix it once prod is wedged:** reconcile the ledger so the executed set is a clean
132
+ *prefix* again, then let the normal strict migrate job run. Do **not** reach for
133
+ `allowUnorderedMigrations: true` — it works (kysely-ctl spreads the `migrations`
134
+ config into the `Migrator`), but it permanently weakens the ordering guard to paper
135
+ over one bad state. Instead, surgically remove the prematurely-recorded row from the
136
+ migration ledger table (default `kysely_migration`):
137
+
138
+ ```sql
139
+ -- prod ledger has the later-timestamp migration recorded, blocking the two earlier ones
140
+ DELETE FROM kysely_migration WHERE name = '1700000200000_drop_thing';
141
+ ```
142
+
143
+ Now `add_table → add_column → drop_thing` are all pending in true timestamp order, and
144
+ the next deploy's strict migrate job applies them cleanly. This only works when the
145
+ removed migration is **idempotent to re-run** (e.g. a `dropTable`/`dropColumn` written
146
+ with `ifExists`, so re-applying it after the others is a safe no-op). Verify the
147
+ ledger is a contiguous prefix after the DELETE, and prefer letting the deploy's own
148
+ migrate job re-apply rather than running migrations from a laptop against prod.
149
+
150
+ ## Type Generation
151
+
152
+ Use `kysely-codegen` to generate types from your database:
153
+
154
+ ```bash
155
+ npx kysely-codegen --url "postgresql://..." --out-file src/db/db.d.ts
156
+ ```
157
+
158
+ Generated types use:
159
+ - `Generated<T>` for auto-increment columns (optional on insert)
160
+ - `ColumnType<Select, Insert, Update>` for different operation types
161
+ - `Timestamp` for timestamptz columns
162
+