Skip to content

docs(d1): add rules of D1 best practices guide#31814

Draft
ivoryibu wants to merge 2 commits into
productionfrom
add-d1-complete-guide
Draft

docs(d1): add rules of D1 best practices guide#31814
ivoryibu wants to merge 2 commits into
productionfrom
add-d1-complete-guide

Conversation

@ivoryibu

Copy link
Copy Markdown
Collaborator

Summary

Adds a comprehensive best practices guide titled "Rules of D1" under the D1 best practices section. This is a revised version of the previously closed PR #31263, updated with new sections on migration tooling choices based on hands-on testing.

New in this version (compared to #31263)

The Schema and migrations section now includes:

  • "Use migrations for team and multi-environment workflows" — explains when migrations are necessary vs. when running raw SQL directly is fine, and documents the typical team workflow
  • "Choose the right migration tooling" — concrete guidance on when to use raw SQL + Wrangler vs. an ORM like Drizzle, with specific criteria:
    • Raw SQL works well for: 1-5 tables, straightforward CRUD, solo developer, comfortable with SQL
    • ORMs pay off for: 10+ tables with foreign keys, complex joins where type safety prevents bugs, multiple developers needing a single source of truth, editor autocompletion
    • Warning that ORM migration generators cannot apply to D1 directly and may generate destructive statements for unmanaged tables

All sections

Section Topic
Query performance Index every column, batch queries, use parameterized queries
Reliability Retry writes, chunk bulk mutations
Schema and migrations When to use migrations, ORM vs. raw SQL, defer foreign keys, Time Travel bookmarks
Data location Location hints, Sessions API for future replicas
Scaling Single-database limits, horizontal scale-out

Context

The ORM guidance was discovered during hands-on testing where drizzle-kit generate attempted to drop Wrangler's d1_migrations table and recreate the application table unnecessarily. This experience informed the specific recommendations about reviewing generated SQL and understanding the split workflow between Drizzle (generate) and Wrangler (apply).

Companion PRs:

@cloudflare-docs-bot

cloudflare-docs-bot Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Review

⚠️ 3 warnings, 💡 4 suggestions found in commit f5d3cc4.

Code Review

This code review is in beta and may not always be helpful — use your judgment.

No code review issues found.

Conventions

Checks PR title, description, and redirect checklist.

No convention issues found.

Style Guide Review

Warnings (3)
File Issue
d1/best-practices/rules-of-d1.mdx line 181 Do not bold program or tool names — Line bolds **Wrangler** in prose: \*\*Raw SQL with Wrangler\*\* works well when: Fix: Use monospace for the tool name: Raw SQL with \Wrangler``.
d1/best-practices/rules-of-d1.mdx line 188 Do not bold program or tool names — Line bolds **Drizzle** and **Prisma** in prose: \*\*An ORM like Drizzle or Prisma\*\* starts paying off when: Fix: Use monospace for the tool names: An ORM like \Drizzle` or `Prisma``.
d1/best-practices/rules-of-d1.mdx line 282 Tables must be introduced with a complete sentence ending in a colon — Line introduces the limits table with a fragment: The limits to design around first: Fix: Use a complete sentence, e.g. Design around these limits first:.
Suggestions (4)
File Issue
d1/best-practices/rules-of-d1.mdx line 183 Spell out single-digit numerals in body text — Line uses the numeral 1-5 in prose: - You have 1-5 tables Fix: Spell out the range: one to five tables.
d1/best-practices/rules-of-d1.mdx line 191 Spell out single-digit numerals in body text — Line uses the numeral 3+ in prose: joins across 3+ tables Fix: Spell out the count: three or more tables.
d1/best-practices/rules-of-d1.mdx line 202 Avoid semicolons joining independent clauses — Line uses a semicolon to join two clauses: \PRAGMA foreign_keys = off`; D1 ignores it.` Fix: Break into two sentences.
d1/best-practices/rules-of-d1.mdx line 247 Avoid semicolons joining independent clauses — Line uses a semicolon to join two clauses: [Sessions API](/d1/worker-api/d1-database/#withsession); otherwise every query goes to the primary. Fix: Break into two sentences or use a comma and coordinating conjunction.

Redirects

No missing redirect entries found.

Commands

Only codeowners can run commands. Post a comment with the command to trigger it.

Command Description
/review Runs a review now. Incremental if a prior review exists, full if not.
/full-review Re-reviews the entire PR diff from scratch, ignoring incremental history. Useful after a rebase, when you want a fresh review, or if the bot gets out of sync and reports issues that no longer exist.
/ignore-review-limit Permanently lifts the 2-review automatic limit for this PR. Future pushes will trigger reviews as normal.
/disable-auto-review Stops automatic reviews from triggering on future pushes to this PR. Codeowners can still run /review or /full-review manually.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request requires reviews from CODEOWNERS as it changes files that match the following patterns:

Pattern Owners
/src/content/docs/d1/ @elithrar, @rita3ko, @irvinebroque, @vy-ton, @ivoryibu, @rts-rob, @joshthoward, @lambrospetrou, @oxyjun, @cloudflare/product-owners

@ivoryibu ivoryibu marked this pull request as draft June 30, 2026 19:33
@ask-bonk

ask-bonk Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

PR Review: docs(d1): add rules of D1 best practices guide

Labels

  • Already correctly labeled product:d1 and size/m. No additional labels needed.

Summary
This PR adds a new ~330-line best-practices page (rules-of-d1.mdx) that covers query performance, reliability, schema migrations, data location / replication, and scaling. It also bumps the best-practices/index.mdx sidebar order from 3 to 4. The migration-tooling guidance (raw SQL vs. ORMs) and the warning about destructive ORM-generated statements are valuable additions. All internal links resolve correctly and astro check passes cleanly.

What looks good

  • Frontmatter is correct: pcx_content_type: concept, description within the 50–160 character range, and a valid products entry.
  • Great use of TypeScriptExample for every Workers/TS snippet.
  • Heading hierarchy follows H2 → H3 with no skipped levels.
  • Numbered lists are used appropriately for the procedural team workflow.
  • Internal links and anchor targets (#batch, #error-list, #sequential-consistency, #drizzle-orm) all verified.

Issues to address before merging

  1. Sentence case in table headers (line ~284)
    The style guide requires table column headers to be sentence case.

    - | Limit                               | Workers Paid | Workers Free |
    + | Limit                               | Workers paid | Workers free |
  2. Tool name formatting — wrangler must be monospace, not bold (lines ~165, ~181, ~196)
    The style guide explicitly states: “Do not bold program or tool names — wrangler and npm are monospace, not bold.”

    - Wrangler tracks which migrations have been applied in a `d1_migrations` table so they are never double-applied.
    + `wrangler` tracks which migrations have been applied in a `d1_migrations` table so they are never double-applied.
    - **Raw SQL with Wrangler** works well when:
    + **Raw SQL** with `wrangler` works well when:
    - You generate the SQL with your ORM, then apply it with Wrangler.
    + You generate the SQL with your ORM, then apply it with `wrangler`.
  3. Spell out acronyms on first use (lines ~179, ~183)
    The style guide requires acronyms to be spelled out on first use unless they appear in the short-list of exceptions (API, REST, URL, etc.). ORM and CRUD are not in that list.

    - You can write migration SQL by hand or use an ORM to generate it.
    + You can write migration SQL by hand or use an object-relational mapping (ORM) to generate it.
    - - Your queries are straightforward CRUD
    + - Your queries are basic create, read, update, and delete (CRUD) operations
  4. Numbers zero through nine should be written as words (lines ~183, ~191)
    The style guide says: “Spell out whole numbers zero through nine in body text. Use digits for 10 and above.”

    - - You have 1-5 tables
    + - You have one to five tables
    - - You build complex queries with joins across 3+ tables, where type safety prevents you from accidentally joining on the wrong column or misspelling a field name
    + - You build complex queries with joins across three or more tables, where type safety prevents you from accidentally joining on the wrong column or misspelling a field name
  5. Avoid LLM-filler word “straightforward” (line ~184)
    “straightforward” is listed as a filler phrase to avoid.
    (Addressed together with item 3 above by replacing “straightforward CRUD” with “basic create, read, update, and delete (CRUD) operations”.)

  6. (Optional) Clarify read-only retry rule for WITH statements (line ~91)
    A WITH clause can precede a write (WITH ... INSERT). Consider tightening the wording so readers don’t assume all WITH queries are retried.

    - Only queries containing solely `SELECT`, `EXPLAIN`, or `WITH` are retried; any query that can write is never auto-retried.
    + Only read-only queries — those containing solely `SELECT`, `EXPLAIN`, or read-only `WITH` statements — are retried; any query that can write is never auto-retried.

Bottom line
Content is solid, accurate, and well structured. Please address the style-guide items above (especially tool-name formatting, sentence-case table headers, and acronym spelling) and this will be ready to merge.

github run

…cronym spelling, number words, WITH clarification
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product:d1 D1: https://developers.cloudflare.com/d1/ size/m

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants