Skip to content

chore: drizzle-engineering skill source + pre-hook - #51

Merged
Bonobo791 merged 4 commits into
mainfrom
chore-drizzle-skill
Aug 3, 2026
Merged

chore: drizzle-engineering skill source + pre-hook#51
Bonobo791 merged 4 commits into
mainfrom
chore-drizzle-skill

Conversation

@Bonobo791

@Bonobo791 Bonobo791 commented Aug 3, 2026

Copy link
Copy Markdown
Owner

User description

Adds the drizzle-engineering skill source under .agents/skills-src/drizzle-engineering/ (flattened to match the sqlite-engineering layout) plus a UserPromptSubmit pre-hook at assets/hooks/skill_prehook.py, adapted from the sqlite pre-hook with Drizzle/Turso/ORM triggers.

The installed copy lives at ~/.agents/skills/drizzle-engineering/ and the hook is wired in ~/.kimi-code/config.toml alongside the sqlite hook (both user-scope, not in this repo).

Verified: hook compiles, injects the skill on a drizzle-flavored prompt, no-ops silently on an unrelated prompt, and config.toml parses with both hook entries.


CodeAnt-AI Description

Add Drizzle ORM guidance and automatic skill loading for database work

What Changed

  • Adds a Drizzle engineering skill covering schema design, type-safe queries, validation, transactions, performance, and migration safety across supported database drivers
  • Automatically provides the skill when prompts contain Drizzle-specific terms, while avoiding unrelated database prompts
  • Falls back to a clear instruction to read the skill when the skill file cannot be loaded, and reports hook failures without interrupting prompt processing
  • Documents safe migration workflows, atomic multi-row writes, protection against unsafe SQL, N+1 queries, timestamp mismatches, and destructive schema changes

Impact

✅ Consistent Drizzle guidance for ORM tasks
✅ Fewer unsafe production migrations
✅ Fewer accidental SQL injection and partial-write risks

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

@cla-bot cla-bot Bot added the cla-signed label Aug 3, 2026
@codeant-ai

codeant-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Incremental review completed 926697e Aug 03, 2026 · 12:31 12:33
✅ Reviewed your PR adc7a21 Aug 03, 2026 · 12:01 12:03

@netlify

netlify Bot commented Aug 3, 2026

Copy link
Copy Markdown

Deploy Preview for moderaty ready!

Name Link
🔨 Latest commit fa7fcf8
🔍 Latest deploy log https://app.netlify.com/projects/moderaty/deploys/6a708bb3271a940008fdaf14
😎 Deploy Preview https://deploy-preview-51--moderaty.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 92
Accessibility: 97
Best Practices: 100
SEO: 100
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Bonobo791, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 21 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 8f0a801a-6db4-4437-9577-f706a6c1078b

📥 Commits

Reviewing files that changed from the base of the PR and between 926697e and fa7fcf8.

📒 Files selected for processing (2)
  • .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py
  • .agents/skills-src/sqlite-engineering/assets/hooks/skill_prehook.py
📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added automatic detection of Drizzle-related prompts to provide relevant engineering guidance during development.
  • Documentation
    • Added a Drizzle engineering skill covering schema design, migrations, queries, transactions, validation, and database drivers.
    • Added references for migration workflows, query performance, schema declarations, transactions, driver behavior, and validation practices.
    • Documented safety checks, rollback procedures, security considerations, and post-migration verification.

Walkthrough

Adds a Drizzle ORM engineering skill with schema, query, validation, migration, transaction, driver, and troubleshooting guidance. Adds a prompt hook that detects Drizzle-related requests and injects the full skill or a directive.

Changes

Drizzle engineering guidance

Layer / File(s) Summary
Core Drizzle guidance
.agents/skills-src/drizzle-engineering/SKILL.md, .agents/skills-src/drizzle-engineering/references/schema-declaration.md, .agents/skills-src/drizzle-engineering/references/queries-performance.md, .agents/skills-src/drizzle-engineering/references/validation-zod.md
Defines Drizzle scope, schema practices, query-performance rules, validation patterns, migration verification, and common failure corrections.
Migration workflow
.agents/skills-src/drizzle-engineering/references/migrations-workflow.md
Documents migration generation, SQL review, custom DDL and DML, expand-and-contract changes, application methods, drift recovery, rollback, and verification.
Transactions and drivers
.agents/skills-src/drizzle-engineering/references/transactions-drivers.md
Documents transaction behavior, savepoints, SQLite modes, driver limitations, isolation, locking, retries, and transaction discipline.
Prompt skill injection
.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py
Adds prompt parsing, Drizzle keyword matching, configurable skill loading, directive fallback, and unconditional successful hook termination.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PromptHarness
  participant skill_prehook.py
  participant SKILL.md
  PromptHarness->>skill_prehook.py: Submit JSON or raw prompt
  skill_prehook.py->>skill_prehook.py: Parse prompt and match Drizzle keywords
  skill_prehook.py->>SKILL.md: Load full skill when enabled
  SKILL.md-->>skill_prehook.py: Return skill content
  skill_prehook.py-->>PromptHarness: Emit skill content or directive
Loading

Possibly related PRs

  • Bonobo791/Moderaty#2: Adds related Drizzle schema, configuration, client, and migration workflow changes.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main changes: the Drizzle engineering skill source and its pre-hook.
Description check ✅ Passed The description directly explains the added Drizzle skill, automatic loading hook, verification, and intended impact.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore-drizzle-skill

Comment @coderabbitai help to get the list of available commands.

@codeant-ai codeant-ai Bot added the size:XL This PR changes 500-999 lines, ignoring generated files label Aug 3, 2026
@codeant-ai

codeant-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Sequence Diagram

This PR adds a prompt prehook that detects Drizzle-related work, loads the engineering skill, and injects its guidance into the agent context before processing continues.

sequenceDiagram
    participant UserPrompt
    participant Prehook
    participant SkillFile
    participant AgentHarness

    UserPrompt->>Prehook: Submit prompt
    Prehook->>Prehook: Detect Drizzle keywords
    Prehook->>SkillFile: Read engineering skill
    SkillFile-->>Prehook: Return skill guidance
    Prehook-->>AgentHarness: Inject guidance into context
Loading

Generated by CodeAnt AI

@codeant-ai

codeant-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown

🏁 CodeAnt Quality Gate Results

Commit: fa7fcf8f
Scan Time: 2026-08-03 13:13:02 UTC

✅ Overall Status: PASSED

Quality Gate Details

Quality Gate Status Details
Secrets ✅ PASSED 0 secrets found
Duplicate Code ✅ PASSED 4.1% duplicated
SAST ✅ PASSED No security issues
Bugs ✅ PASSED Rating S: No bugs
IAC ✅ PASSED No IAC issues

View Full Results

@amazon-q-developer amazon-q-developer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review complete. The code changes add comprehensive Drizzle ORM engineering documentation and tooling that are well-structured with no blocking defects identified. All Python code includes proper error handling, and documentation examples are syntactically correct.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

@Bonobo791 Bonobo791 changed the title Phase D: team management UI + invites chore: drizzle-engineering skill source + pre-hook Aug 3, 2026
@codacy-production

codacy-production Bot commented Aug 3, 2026

Copy link
Copy Markdown

Not up to standards ⛔

🟢 Issues 1 minor

Results:
1 new issue

Category Results
Documentation 1 minor

View in Codacy

🔴 Metrics 12 complexity · 4 duplication

Metric Results
Complexity 12 (≤ 100 complexity)
Duplication ⚠️ 4 (≤ 1 duplication)

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add drizzle-engineering agent skill docs and Drizzle keyword prehook

📝 Documentation ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Add a Drizzle ORM engineering skill with non-negotiable safety and workflow rules.
• Document Drizzle schema, migrations, performance, transactions, and drizzle-zod validation
 guidance.
• Add a prompt prehook that auto-injects the skill when Drizzle-related keywords appear.
Diagram

graph TD
  P(["User prompt"]) --> R["Hook runner (harness)"] --> H["skill_prehook.py"] --> D{"Drizzle keywords?"}
  D -->|"no"| N["No-op"]
  D -->|"yes"| S[["SKILL.md"]] --> C["Injected agent context"]
  S --> M[["references/*.md"]]

  subgraph Legend
    direction LR
    _proc["Process"] ~~~ _dec{"Decision"} ~~~ _file[["File"]]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Derive hook triggers from SKILL.md front matter
  • ➕ Single source of truth for trigger keywords (no duplicated lists).
  • ➕ Easier to add/remove triggers without touching code.
  • ➖ Requires parsing YAML front matter in the hook (slightly more complexity).
  • ➖ More failure modes if the markdown format changes.
2. Generic reusable skill-injection hook framework
  • ➕ Scales to many skills with the same JSON-in/emit-text-out protocol.
  • ➕ Centralizes error handling, env var conventions, and logging.
  • ➖ Overhead if this repo will only ever have one or two skills.
  • ➖ Adds indirection that can make hook behavior harder to debug.

Recommendation: The PR’s approach (a simple, fail-safe keyword prehook plus comprehensive docs) is appropriate for low-friction adoption. If more skills are expected, consider consolidating keyword definitions by reading triggers from the skill’s front matter, and/or introducing a small generic hook runner to avoid per-skill bespoke scripts.

Files changed (7) +899 / -0

Documentation (6) +791 / -0
SKILL.mdAdd Drizzle engineering skill doctrine and safety defaults +98/-0

Add Drizzle engineering skill doctrine and safety defaults

• Introduces the drizzle-engineering skill with strict operational defaults for schema-as-source-of-truth, migration workflows, expand-and-contract, transaction discipline, and raw SQL safety. Includes failure-mode guidance and verification habits, plus pointers to detailed reference docs.

.agents/skills-src/drizzle-engineering/SKILL.md

migrations-workflow.mdDocument drizzle-kit migration lifecycle and drift recovery +159/-0

Document drizzle-kit migration lifecycle and drift recovery

• Provides an operational guide for drizzle-kit commands, when to generate vs push, how to review generated SQL, and how to handle custom DML migrations. Covers expand-and-contract, application methods (CLI/programmatic/D1), journal immutability, and rollback strategy.

.agents/skills-src/drizzle-engineering/references/migrations-workflow.md

queries-performance.mdDocument safe query shapes and Drizzle performance rules +189/-0

Document safe query shapes and Drizzle performance rules

• Adds guidance on choosing core vs relational query APIs, eliminating N+1 patterns, batching and upserts, prepared statements, pagination/counting, and strict raw SQL safety rules. Emphasizes explicit selects and observable SQL for performance debugging.

.agents/skills-src/drizzle-engineering/references/queries-performance.md

schema-declaration.mdDocument schema declaration patterns and drizzle-kit diff correctness +182/-0

Document schema declaration patterns and drizzle-kit diff correctness

• Defines conventions for drizzle.config.ts, column modes (notably SQLite timestamp units), defaults, primary keys, and constraints/indexes. Includes guidance for self-references, relations() as an N+1 defense, and multi-file schema organization.

.agents/skills-src/drizzle-engineering/references/schema-declaration.md

transactions-drivers.mdDocument db.transaction semantics across drivers +100/-0

Document db.transaction semantics across drivers

• Explains how Drizzle transactions behave, the importance of using tx within callbacks, nested transactions via savepoints, and SQLite BEGIN behavior selection. Summarizes driver-specific traps (Turso/libsql, D1, Neon HTTP, Postgres) and prescribes transaction discipline.

.agents/skills-src/drizzle-engineering/references/transactions-drivers.md

validation-zod.mdDocument drizzle-zod boundary validation patterns +63/-0

Document drizzle-zod boundary validation patterns

• Adds guidance on generating insert/select schemas from the Drizzle schema, refining without forking, and enforcing boundary discipline. Highlights avoiding mass-assignment vectors by omitting server-owned fields and using strict request parsing.

.agents/skills-src/drizzle-engineering/references/validation-zod.md

Other (1) +108 / -0
skill_prehook.pyAdd prompt prehook to auto-inject Drizzle skill on keyword match +108/-0

Add prompt prehook to auto-inject Drizzle skill on keyword match

• Adds a harness-compatible prehook that reads the user prompt (JSON or raw text), matches Drizzle-related trigger patterns, and emits either the full SKILL.md or a short directive depending on env configuration. Designed to be non-blocking: always exits 0 and swallows unexpected exceptions.

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py

@codacy-production codacy-production Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

The pull request is currently not up to standards according to Codacy, primarily due to issues within the pre-hook implementation and documentation accuracy. The most significant concern is the overly broad trigger list in the Python pre-hook, which will cause the Drizzle engineering skill to be injected into almost any database-related task, regardless of whether Drizzle is actually used. This will lead to context window pollution and potentially conflicting instructions.

Additionally, the documentation contains outdated information regarding drizzle-kit's ability to detect renames and recommends unsafe patterns using sql.raw. The pre-hook script itself is complex and lacks automated tests, posing a maintenance risk.

About this PR

  • Generic triggers such as 'orm' and 'migration' are highly likely to cause false positives, injecting Drizzle-specific guidelines into tasks that use other ORMs (e.g., Prisma, SQLAlchemy) or generic migration tools.
  • The pre-hook script is complex and lacks automated unit tests. Relying on manual verification for a component that modifies the agent's context is risky; consider adding unit tests to verify trigger logic and prompt parsing.

Test suggestions

  • Detection of Drizzle-specific keywords (e.g., 'drizzle-orm', 'sqliteTable')
  • Parsing of JSON input from standard agent harnesses like Claude Code
  • Switching between full skill inlining and directive mode via DRIZZLE_ENGINEERING_HOOK_FULL
  • Handling of file access errors when reading SKILL.md to ensure the hook remains silent rather than failing
  • Verification that broad keywords like 'orm' or 'migration' do not trigger excessive false positives for non-Drizzle tasks
  • Unit tests for skill_prehook.py to address high complexity and lack of coverage
Prompt proposal for missing tests
Consider implementing these tests if applicable:
1. Detection of Drizzle-specific keywords (e.g., 'drizzle-orm', 'sqliteTable')
2. Parsing of JSON input from standard agent harnesses like Claude Code
3. Switching between full skill inlining and directive mode via DRIZZLE_ENGINEERING_HOOK_FULL
4. Handling of file access errors when reading SKILL.md to ensure the hook remains silent rather than failing
5. Verification that broad keywords like 'orm' or 'migration' do not trigger excessive false positives for non-Drizzle tasks
6. Unit tests for skill_prehook.py to address high complexity and lack of coverage

TIP Improve review quality by adding custom instructions
TIP How was this review? Give us feedback

Comment on lines +28 to +41
TRIGGERS = [
r"\bdrizzle\b", r"\bdrizzle-orm\b", r"\bdrizzle-kit\b", r"\bdrizzle-zod\b",
r"\bdrizzle\.config\b",
r"\bsqliteTable\b", r"\bpgTable\b", r"\bmysqlTable\b",
r"\bonConflictDo(Update|Nothing)\b", r"\bupsert(s|ing)?\b",
r"\bdb\.transaction\b", r"\bdb\.query\b", r"\bprepared\s+statement(s)?\b",
r"\bsql\.placeholder\b", r"\bsql\.raw\b",
r"\borm\b",
r"\bselect\s+.+\s+from\b", r"\bjoin(s|ing)?\b", r"\bleftJoin\b", r"\binnerJoin\b",
r"\bn\+1\b", r"\brelations\b",
r"\bmigration(s)?\b", r"\bbackfill(s|ing)?\b",
r"\bexpand[-\s]and[-\s]contract\b", r"\bschema\s+(drift|declaration|design)\b",
r"\bcolumn\s+already\s+exists\b",
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 HIGH RISK

The trigger list includes extremely broad terms like 'orm', 'migration', 'select', 'join', and 'upsert'. These will cause the Drizzle engineering skill to be injected into the context for nearly any database-related task, polluting the context window. Narrow these to Drizzle-specific terms such as package names ('drizzle-orm'), specific table builders ('pgTable', 'sqliteTable'), or unique API methods.

if __name__ == "__main__":
try:
main()
except Exception:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Avoid silently ignoring all exceptions. Even if the hook must not block the prompt flow, logging the error to sys.stderr ensures visibility for troubleshooting when the skill fails to load. Update the exception handling in the __main__ block to log any caught Exception to sys.stderr before exiting with code 0.

Rules:

1. `sql.raw()` accepts only string literals you wrote. If any part came from a request, config, or
another system, it does not go through `sql.raw`. (Its one legitimate use: referencing the

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Using sql.raw is discouraged even for internal identifiers. Use the sql template literal with the column object instead to ensure proper escaping.

});

// referencing the proposed row (Postgres "excluded"):
set: { name: sql.raw(`excluded.${users.name.name}`) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Referencing the excluded table using sql.raw is unnecessary and bypasses safety mechanisms. Drizzle can safely interpolate column identifiers within the sql template tag (e.g., sqlexcluded.${users.name}`).

drizzle-kit diffs snapshots, not intent. Before committing, read the SQL and check:

1. **Drops** — every `DROP TABLE`/`DROP COLUMN` is a data-loss decision. Is it intended? If it
appeared because you renamed something, it's wrong: kit can't see renames.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ LOW RISK

The claim that drizzle-kit cannot see renames is outdated. The CLI provides interactive prompts to detect renames during the generate command, which results in correct rename statements in the migration file.

Comment on lines +58 to +71
def read_prompt() -> str:
raw = sys.stdin.read()
if not raw.strip():
return ""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return raw
if isinstance(data, dict):
for key in ("prompt", "user_prompt", "message", "text"):
val = data.get(key)
if isinstance(val, str) and val.strip():
return val
return ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ LOW RISK

Suggestion: This file duplicates the read_prompt logic from sqlite-engineering. Consider abstracting this into a shared utility or using a template to avoid manually syncing boilerplate across every new engineering skill.

@qodo-code-review

qodo-code-review Bot commented Aug 3, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 74 rules

Grey Divider


Remediation recommended

1. Hook failures invisible ✓ Resolved 🐞 Bug ◔ Observability
Description
The entrypoint wraps main() in a blanket except Exception: pass and always exits 0, so
unexpected runtime failures silently disable skill injection and are difficult to diagnose. This
preserves prompt flow as intended, but provides no observability to detect/debug hook breakage.
Code

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py[R104-107]

+    try:
+        main()
+    except Exception:
+        pass  # hooks must never break the prompt flow
Relevance

●● Moderate

No historical evidence: new hook file not present in repo history; no prior guidance on logging vs
silent hooks.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The script explicitly suppresses any exception thrown by main() and still exits 0, meaning
failures produce no output/status signal for the harness and are hard to debug.

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py[103-108]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The hook suppresses all unexpected exceptions at the entrypoint and always exits 0, which makes injection failures indistinguishable from a normal no-op. This complicates diagnosing why the skill is not being injected.

### Issue Context
The hook’s design goal is to never break the prompt flow; changes must preserve that behavior.

### Fix Focus Areas
- .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py[103-108]

### Implementation notes
- Keep `exit(0)` behavior.
- Add optional diagnostics gated by an env var (e.g., `DRIZZLE_ENGINEERING_HOOK_DEBUG=1`):
 - On exception, write a short error message (and optionally traceback) to `stderr`.
- Narrow the catch if desired (e.g., avoid swallowing `SystemExit`), but ensure the hook still can’t break the harness.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. SQL trigger misses newlines ⊘ Outdated 🐞 Bug ☼ Reliability
Description
The prehook trigger \bselect\s+.+\s+from\b won’t match common multiline SQL (e.g., `SELECT\n
...\nFROM ...) because .` doesn’t match newlines in Python regex by default, so some Drizzle/SQL
prompts won’t inject the skill. This reduces reliability of automatic skill loading for formatted
SQL/code-block prompts that don’t contain other Drizzle keywords.
Code

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py[36]

+    r"\bselect\s+.+\s+from\b", r"\bjoin(s|ing)?\b", r"\bleftJoin\b", r"\binnerJoin\b",
Relevance

●● Moderate

No repo history: path '.agents/skills-src/…' absent on default branch; can’t infer trigger-regex
expectations.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The trigger list includes r"\bselect\s+.+\s+from\b" and the regex is compiled without re.DOTALL,
so . cannot cross newlines and multiline SQL won’t satisfy this trigger.

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py[28-44]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The prompt trigger regex uses `\bselect\s+.+\s+from\b`, where `.` does not match newline characters in Python regex by default. This causes false negatives for multiline SQL snippets.

### Issue Context
This hook is meant to inject the drizzle-engineering skill whenever prompts touch Drizzle/SQL work, including code blocks that often format SQL across multiple lines.

### Fix Focus Areas
- .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py[28-44]

### Implementation notes
- Replace the `select ... from` trigger with a newline-tolerant, non-greedy variant, e.g.:
 - `r"\bselect\s+[\s\S]+?\s+from\b"`
- (Optional) Add a reasonable upper bound to avoid scanning extremely long prompts for this pattern (e.g., via a more constrained pattern), while keeping other triggers unchanged.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py Outdated
Comment thread .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 11

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py:
- Around line 103-108: Update the __main__ exception handling so hook failures
are no longer silently discarded: catch expected decoding and I/O failures at
their sources, and if the final catch-all remains necessary to preserve exit
code 0, write only the exception type to stderr without including prompt or
skill contents.
- Around line 2-4: Update the module docstring at the top of skill_prehook.py so
the opening line is followed by a blank line, the summary appears on the next
paragraph’s first line, and that summary ends with a period, preserving the
existing description.
- Around line 35-40: In the trigger patterns used by the prehook, narrow generic
matches such as join, relations, and migrations so unrelated prompts do not
enable full SKILL.md injection. Require a Drizzle-specific term or database
context for these generic terms, while preserving detection of valid Drizzle
prompts. Add regression coverage for unrelated prompts and valid Drizzle prompts
through the existing hook test symbols.

In @.agents/skills-src/drizzle-engineering/references/queries-performance.md:
- Around line 84-91: Update the onConflictDoUpdate example to remove the
undefined excludedName reference in set; replace it with a complete valid
SQL/value expression consistent with the insert example, or omit the example if
no valid expression is intended.
- Around line 55-60: In the N+1 query example, update the result binding in the
`posts` query from `posts` to `postRows` so it does not shadow the table
reference before initialization. Preserve the loop and author assignment logic,
updating any references to the fetched result as needed.
- Around line 96-102: Replace the blanket buildConflictUpdateColumns example
with a valid Drizzle pattern: define a local helper or explicit set map that
includes only mutable user column keys, excluding immutable/defaulted fields
such as id and createdAt, and remove the invalid buildConflictUpdateColumns
import and usage.

In @.agents/skills-src/drizzle-engineering/references/schema-declaration.md:
- Around line 24-30: Update the defineConfig example to clearly label it as
SQLite-only, or align it with the repository’s Turso setup by using dialect
'turso' and the corresponding `@libsql/client` credentials including the auth
token. Ensure the schema, output, and strict/verbose settings remain unchanged.
- Around line 124-135: Update the self-reference guidance in the schema
declaration documentation to reflect that drizzle-orm@0.45.2 supports the inline
references form when the callback explicitly returns AnySQLiteColumn. Retain or
additionally show the standalone foreignKey alternative, and ensure the example
and surrounding explanation no longer claim inline self-references are
unsupported.

In @.agents/skills-src/drizzle-engineering/SKILL.md:
- Around line 33-34: Revise the source-of-truth guidance in the TypeScript
schema section to apply only to normal schema changes, allowing manual database
reconciliation when recovering from a partial migration. Reference the
documented recovery procedure in migrations-workflow.md, while preserving the
warning against routine out-of-band edits.
- Around line 58-61: Add shell language identifiers to the command fences at
.agents/skills-src/drizzle-engineering/SKILL.md lines 58-61 and
.agents/skills-src/drizzle-engineering/references/migrations-workflow.md lines
62-64, 95-97, and 119-123; no other content changes are needed.
- Around line 46-47: Update the multi-row mutation rule in the Drizzle
engineering guidance to require db.transaction when the driver supports it,
while allowing an equivalent atomic SQL statement or driver-supported batch API
such as db.batch when transactions are unavailable. Preserve the requirement
that the entire mutation remains atomic and cannot leave a partial write.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: bfe8d7e3-1229-47ff-bb34-5ea23120fb94

📥 Commits

Reviewing files that changed from the base of the PR and between cd3283a and adc7a21.

📒 Files selected for processing (7)
  • .agents/skills-src/drizzle-engineering/SKILL.md
  • .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py
  • .agents/skills-src/drizzle-engineering/references/migrations-workflow.md
  • .agents/skills-src/drizzle-engineering/references/queries-performance.md
  • .agents/skills-src/drizzle-engineering/references/schema-declaration.md
  • .agents/skills-src/drizzle-engineering/references/transactions-drivers.md
  • .agents/skills-src/drizzle-engineering/references/validation-zod.md

Comment thread .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py Outdated
Comment thread .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py Outdated
Comment on lines +24 to +30
export default defineConfig({
dialect: 'sqlite', // 'postgresql' | 'mysql' | 'sqlite' | 'turso' | ...
schema: './src/lib/server/db/schema', // file OR folder — folder = all files merged
out: './drizzle', // migrations + snapshots + journal live here, COMMITTED
dbCredentials: { url: process.env.DATABASE_URL! },
strict: true, // interactive confirmations on ambiguous diffs
verbose: true, // print generated statements

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Align or label the database configuration example.

The repository configuration in drizzle.config.ts, Lines 31-41, uses dialect: 'turso', @libsql/client, and an auth token. This example sets dialect: 'sqlite' and provides only a URL. If contributors copy it into this repository, Drizzle Kit can use the wrong dialect and driver configuration. Mark this as a SQLite-only example or show the repository's Turso configuration.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills-src/drizzle-engineering/references/schema-declaration.md
around lines 24 - 30, Update the defineConfig example to clearly label it as
SQLite-only, or align it with the repository’s Turso setup by using dialect
'turso' and the corresponding `@libsql/client` credentials including the auth
token. Ensure the schema, output, and strict/verbose settings remain unchanged.

Comment thread .agents/skills-src/drizzle-engineering/SKILL.md Outdated
Comment thread .agents/skills-src/drizzle-engineering/SKILL.md Outdated
Comment thread .agents/skills-src/drizzle-engineering/SKILL.md Outdated
@codeant-ai codeant-ai Bot added size:XL This PR changes 500-999 lines, ignoring generated files and removed size:XL This PR changes 500-999 lines, ignoring generated files labels Aug 3, 2026
@Bonobo791

Copy link
Copy Markdown
Owner Author

Review dispositions at 926697e — all findings verified against the code first.

Fixed (valid):

  • skill_prehook.py broad triggers (Codacy HIGH, CodeRabbit Major): trigger list narrowed to Drizzle-specific terms only (drizzle*, sqliteTable/pgTable/mysqlTable, onConflictDo*, db.transaction/db.query/db.batch, sql.placeholder/sql.raw/sql.identifier, leftJoin/innerJoin, getTableColumns, buildConflictUpdateColumns). Generic database terms (orm, migration, join, upsert, select…from, n+1, relations, backfill, …) removed — the sqlite-engineering hook already covers those.
  • skill_prehook.py silent exception (Codacy/Qodo/CodeRabbit): catch-all now writes the exception type and message to stderr; still exits 0 so the prompt flow never breaks. No prompt/skill content is logged.
  • skill_prehook.py docstring D205/D213/D415 (CodeRabbit trivial): summary moved to its own line, ends with a period.
  • queries-performance.md N+1 example (CodeRabbit Minor): const posts = await db.select().from(posts) was a TDZ ReferenceError — result renamed to postRows.
  • queries-performance.md upsert example (CodeRabbit Minor + Major): undefined excludedName placeholder replaced with the complete sql.raw expression; buildConflictUpdateColumns is NOT a drizzle-orm export (verified against 0.45.2) — example now defines the helper locally per the Drizzle upsert guide and passes explicit mutable column keys (no id/createdAt).
  • schema-declaration.md self-reference section (CodeRabbit Major): prose claimed inline self-references are unsupported while the example showed the typed inline form — prose corrected: inline works with an explicit AnySQLiteColumn return type; standalone foreignKey noted as the circular-reference solution.
  • schema-declaration.md config example (CodeRabbit Major): labeled as a generic SQLite example with a pointer to this repo's dialect: 'turso' + @libsql/client setup in drizzle.config.ts.
  • SKILL.md rule 1 (CodeRabbit Major): qualified with the documented exception — manual reconciliation after a partially applied migration, per migrations-workflow.md.
  • SKILL.md rule 7 (CodeRabbit Major): now allows a single atomic statement or db.batch on drivers that reject SQL transactions (D1); atomicity requirement unchanged.
  • migrations-workflow.md rename claim (Codacy LOW): softened — with strict: true kit prompts interactively; non-interactive runs (CI, agents) still get drop+add.
  • MD040 fences (CodeRabbit trivial): text/sh identifiers added to the bare fences in SKILL.md and migrations-workflow.md.

Skipped (invalid or moot):

  • Codacy MEDIUM ×2 — sql.raw for the excluded. pseudo-table: this is the one use the doc's own rule 1 explicitly carves out as legitimate (identifiers are hardcoded from your own schema, and the quoting form excluded."col" is the documented pattern). No change.
  • Qodo — select\s+.+\s+from doesn't match newlines: moot, that trigger was removed entirely as too broad.
  • Codacy LOW — read_prompt duplication across skill hooks: the hooks are independent single-file installs wired per-skill; a shared module would couple separate install trees. Matches the sqlite-engineering precedent. No change.

Hook re-verified after changes: compiles, injects on Drizzle prompts, silent no-op (exit 0) on generic database and unrelated prompts. Installed copy at ~/.agents/skills/drizzle-engineering/ synced identical to this tree.

@codeant-ai

codeant-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to commit 926697e
CategorySuggestion                                                                                                                                    SeverityGenerated at (UTC)
Performance
Overlapping Drizzle triggers cause duplicate full skill injection when both hooks are enabled

When both the documented sqlite and Drizzle hooks are installed, this drizzle
trigger overlaps with the sqlite hook's own drizzle trigger. In the default full
mode, every Drizzle prompt causes both complete skill documents and directives to be
appended, unnecessarily consuming context and potentially crowding out the user
request. Avoid overlapping triggers or coordinate the hooks so only one full payload
is emitted.

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py [35-36]

Why it matters? 🤔
  • ⚠️ Every Drizzle prompt receives duplicate skill payloads.
  • ⚠️ Duplicate context consumes available agent context capacity.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py
**Line:** 35:36
**Comment:**
	*Performance: When both the documented sqlite and Drizzle hooks are installed, this `drizzle` trigger overlaps with the sqlite hook's own `drizzle` trigger. In the default full mode, every Drizzle prompt causes both complete skill documents and directives to be appended, unnecessarily consuming context and potentially crowding out the user request. Avoid overlapping triggers or coordinate the hooks so only one full payload is emitted.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
Major2026-08-03 12:33
Api mismatch
Unqualified transaction guidance can generate unsupported code for D1 drivers

This directive unconditionally instructs the agent to put multi-row mutations inside
db.transaction, but the loaded skill explicitly says D1 rejects SQL transactions and
requires a single atomic statement or db.batch instead. For D1/Turso work, the
injected directive can cause unsupported transaction code. Qualify this instruction
by driver.

.agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py [53-54]

Why it matters? 🤔
  • ❌ Generated D1 transaction code fails at runtime.
  • ⚠️ D1 implementations require manual correction to use db.batch.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py
**Line:** 53:54
**Comment:**
	*Api Mismatch: This directive unconditionally instructs the agent to put multi-row mutations inside `db.transaction`, but the loaded skill explicitly says D1 rejects SQL transactions and requires a single atomic statement or `db.batch` instead. For D1/Turso work, the injected directive can cause unsupported transaction code. Qualify this instruction by driver.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
Major2026-08-03 12:33

@Bonobo791

Copy link
Copy Markdown
Owner Author

Round-2 dispositions at fa7fcf8 (CodeAnt suggestions on 926697e) — both verified and fixed:

  • Trigger overlap (Major): valid. The sqlite-engineering hook had drizzle/drizzle-kit triggers predating this hook, so every Drizzle prompt injected BOTH full skills. Removed those two triggers from the sqlite hook (with a comment explaining why) — the drizzle hook now owns the ORM layer, the sqlite hook the engine layer. Verified: a drizzle-only prompt now fires only the drizzle hook; an engine-only prompt only the sqlite hook. Residual dual injection happens only when a prompt names both layers (e.g. "drizzle migration on turso"), which is the pairing both skills explicitly prescribe.
  • Unqualified db.transaction in the DIRECTIVE (Major): valid — the directive contradicted the amended SKILL.md rule 7. Directive now reads "multi-row mutations stay atomic (db.transaction where the driver supports it; on drivers that reject SQL transactions like D1, a single atomic statement or db.batch)".

Codacy's remaining "1 minor (Documentation)" is the previously-dispositioned read_prompt duplication note — no change.

Both installed hooks at ~/.agents/skills/ synced identical; both compile and smoke-tested.

@sonarqubecloud

sonarqubecloud Bot commented Aug 3, 2026

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills-src/drizzle-engineering/references/migrations-workflow.md:
- Around line 120-123: Update the migration workflow around the drizzle-kit
generate and wrangler d1 migrations apply commands so both tools use the same
migrations directory. Configure Wrangler’s migrations_dir to drizzle, configure
Drizzle to emit to Wrangler’s configured directory, or add a documented copy
step before applying migrations; ensure the documented commands operate on the
generated files.

In @.agents/skills-src/drizzle-engineering/references/queries-performance.md:
- Around line 94-113: Update the upsert example around
buildConflictUpdateColumns so the set property is passed inside an
onConflictDoUpdate({ ... }) options object, keeping the helper as the value for
the set field and removing the standalone set expression.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 2047b1ca-5cfa-472e-998c-57c56def4fc6

📥 Commits

Reviewing files that changed from the base of the PR and between adc7a21 and 926697e.

📒 Files selected for processing (5)
  • .agents/skills-src/drizzle-engineering/SKILL.md
  • .agents/skills-src/drizzle-engineering/assets/hooks/skill_prehook.py
  • .agents/skills-src/drizzle-engineering/references/migrations-workflow.md
  • .agents/skills-src/drizzle-engineering/references/queries-performance.md
  • .agents/skills-src/drizzle-engineering/references/schema-declaration.md

Comment on lines +120 to +123
```sh
npx drizzle-kit generate
npx wrangler d1 migrations apply <db-name> --local
npx wrangler d1 migrations apply <db-name> --remote

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- target file ---'
sed -n '1,180p' .agents/skills-src/drizzle-engineering/references/migrations-workflow.md

printf '%s\n' '--- Drizzle and Wrangler configuration references ---'
rg -n --hidden -S \
  'migrations_dir|migrationsDir|out:|drizzle-kit|drizzle\.config|wrangler\.toml|wrangler\.json|d1 migrations apply|drizzle' \
  . \
  -g '!node_modules' -g '!dist' -g '!build' \
  | head -300

printf '%s\n' '--- relevant tracked files ---'
git ls-files | rg '(^|/)(drizzle|wrangler|package\.json|.*migration.*|.*config.*)' | head -200

Repository: Bonobo791/Moderaty

Length of output: 41179


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- drizzle.config.ts ---'
cat -n drizzle.config.ts

printf '%s\n' '--- package.json ---'
cat -n package.json

printf '%s\n' '--- Wrangler configuration files ---'
git ls-files | rg '(^|/)(wrangler\.toml|wrangler\.json|wrangler\.jsonc)$' || true

printf '%s\n' '--- migration directories ---'
find . -maxdepth 2 -type d \( -name drizzle -o -name migrations \) -print | sort

printf '%s\n' '--- read-only path consistency check ---'
python3 - <<'PY'
from pathlib import Path
import re

drizzle = Path("drizzle.config.ts").read_text()
out = re.search(r"\bout\s*:\s*['\"]([^'\"]+)['\"]", drizzle)
print("drizzle.config.ts out:", out.group(1) if out else "<not found>")
print("Drizzle output directory exists:", Path(out.group(1)).is_dir() if out else False)
print("Default Wrangler D1 directory exists:", Path("migrations").is_dir())
print("Wrangler config tracked:", any(
    p.name in {"wrangler.toml", "wrangler.json", "wrangler.jsonc"}
    for p in map(Path, __import__("subprocess").check_output(
        ["git", "ls-files"], text=True
    ).splitlines())
))
PY

Repository: Bonobo791/Moderaty

Length of output: 3671


🌐 Web query:

Cloudflare Wrangler D1 migrations apply migrations_dir default official documentation

💡 Result:

In Cloudflare Wrangler, the default directory for D1 migrations is./migrations [1][2]. When you run wrangler d1 migrations create, Wrangler automatically creates this migrations folder in your project directory if it does not already exist [3][4]. You can customize this location in your wrangler.jsonc or wrangler.toml configuration file by specifying the migrations_dir field within your D1 database binding configuration [3][5][6]. Example configuration for a custom directory: { "d1_databases": [ { "binding": "DB", "database_name": "my-database", "database_id": "", "migrations_dir": "my-custom-migrations-folder" } ] } If you are using an ORM that requires a nested directory structure (such as Drizzle), you must set both migrations_dir and migrations_pattern to correctly locate and apply your migration files [3][5][7]. The migrations_pattern defaults to <migrations_dir>/*.sql if not otherwise specified [5][6][7].

Citations:


Configure Wrangler to read Drizzle's output directory.

drizzle-kit generate writes to ./drizzle, while Wrangler defaults to ./migrations when migrations_dir is unset. Set Wrangler's migrations_dir to drizzle, configure Drizzle to use Wrangler's directory, or document a copy step.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills-src/drizzle-engineering/references/migrations-workflow.md
around lines 120 - 123, Update the migration workflow around the drizzle-kit
generate and wrangler d1 migrations apply commands so both tools use the same
migrations directory. Configure Wrangler’s migrations_dir to drizzle, configure
Drizzle to emit to Wrangler’s configured directory, or add a documented copy
step before applying migrations; ensure the documented commands operate on the
generated files.

Comment on lines +94 to +113
// helper for "update every inserted column" — NOT a drizzle-orm export; it is
// the user-defined helper from the Drizzle upsert guide. Define it locally:
import { getTableColumns, sql, type SQL } from 'drizzle-orm';
import type { SQLiteTable } from 'drizzle-orm/sqlite-core';

const buildConflictUpdateColumns = <T extends SQLiteTable, Q extends keyof T['_']['columns']>(
table: T,
columns: Q[],
) => {
const cls = getTableColumns(table);
return columns.reduce(
(acc, column) => {
acc[column] = sql.raw(`excluded."${cls[column].name}"`);
return acc;
},
{} as Record<Q, SQL>,
);
};

set: buildConflictUpdateColumns(users, ['name', 'email']),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -e
file=".agents/skills-src/drizzle-engineering/references/queries-performance.md"
sed -n '70,125p' "$file"
printf '\n--- nearby onConflictDoUpdate occurrences ---\n'
rg -n -C 4 'onConflictDoUpdate|buildConflictUpdateColumns|^set:' "$file"
printf '\n--- repository references to the helper ---\n'
rg -n -C 3 'buildConflictUpdateColumns' .

Repository: Bonobo791/Moderaty

Length of output: 3373


Wrap the helper call in onConflictDoUpdate({ ... }). The standalone set: at Line 113 is invalid TypeScript after the preceding call closes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills-src/drizzle-engineering/references/queries-performance.md
around lines 94 - 113, Update the upsert example around
buildConflictUpdateColumns so the set property is passed inside an
onConflictDoUpdate({ ... }) options object, keeping the helper as the value for
the set field and removing the standalone set expression.

@Bonobo791
Bonobo791 merged commit e53a62a into main Aug 3, 2026
15 of 19 checks passed
@Bonobo791
Bonobo791 deleted the chore-drizzle-skill branch August 3, 2026 13:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla-signed size:XL This PR changes 500-999 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant