Skip to content

CFSQL-1294 be more faithful to sqlite's algorithm for printing newlines in export - #15334

Open
alsuren wants to merge 2 commits into
mainfrom
dlaban/CFSQL-1294-dump-newlines
Open

alsuren wants to merge 2 commits into
mainfrom
dlaban/CFSQL-1294-dump-newlines

Conversation

@alsuren

@alsuren alsuren commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

If newline and backslash n are both taken, it picks a new string to use

Fixes #9042

Describe your change...

Ports the sqlite3 .dump algorithm a bit more faithfully, by checking for collisions in proposed escape sequences and then generating new escape sequences until it finds one that doesn't collide.

Extended tests pass in internal d1-worker copy of this change.


  • Tests
    • Tests included/updated
    • Automated tests not possible - manual testing has been completed as follows:
    • Additional testing not necessary because: tests for this file live in the internal d1-worker repo
  • Public documentation
    • Cloudflare docs PR(s):
    • Documentation not necessary because: bugfix of edge case in the export flow.

A picture of a cute animal (not mandatory, but encouraged)

Screenshot 2026-08-24 at 13 53 42

https://freesvg.org/rabbit-line-art (I hope you like what I did there :D)


Devin Review

@changeset-bot

changeset-bot Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: a2a85c4

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 10 packages
Name Type
miniflare Patch
@cloudflare/deploy-helpers Patch
@cloudflare/dev-helpers Patch
@cloudflare/pages-shared Patch
@cloudflare/remote-bindings Patch
@cloudflare/runtime-types Patch
@cloudflare/test-server Patch
@cloudflare/vite-plugin Patch
@cloudflare/vitest-plugin Patch
wrangler Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-project-automation github-project-automation Bot moved this to Untriaged in workers-sdk Aug 24, 2026
@workers-devprod
workers-devprod requested review from a team and emily-shen and removed request for a team August 24, 2026 12:59
@workers-devprod

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • @cloudflare/wrangler
Show detailed file reviewers
  • .changeset/two-lamps-leave.md: [@cloudflare/wrangler]
  • packages/miniflare/src/workers/d1/dumpSql.ts: [@cloudflare/wrangler]

@ask-bonk

ask-bonk Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

github run

@ask-bonk

ask-bonk Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

@alsuren Bonk workflow failed. Check the logs for details.

View workflow run · To retry, trigger Bonk again.

@ask-bonk

ask-bonk Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

github run

@pkg-pr-new

pkg-pr-new Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
@cloudflare/autoconfig

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/autoconfig@15334

@cloudflare/build-output-utils

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/build-output-utils@15334

@cloudflare/codemods

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/codemods@15334

@cloudflare/config

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/config@15334

@cloudflare/containers-shared

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/containers-shared@15334

create-cloudflare

npm i https://pkg.pr.new/cloudflare/workers-sdk/create-cloudflare@15334

@cloudflare/deploy-helpers

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/deploy-helpers@15334

@cloudflare/kv-asset-handler

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/kv-asset-handler@15334

miniflare

npm i https://pkg.pr.new/cloudflare/workers-sdk/miniflare@15334

@cloudflare/pages-functions

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/pages-functions@15334

@cloudflare/pages-shared

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/pages-shared@15334

@cloudflare/runtime-types

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/runtime-types@15334

@cloudflare/test-server

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/test-server@15334

@cloudflare/unenv-preset

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/unenv-preset@15334

@cloudflare/vite-plugin

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/vite-plugin@15334

@cloudflare/vitest-plugin

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/vitest-plugin@15334

@cloudflare/workers-auth

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/workers-auth@15334

@cloudflare/workers-editor-shared

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/workers-editor-shared@15334

@cloudflare/workers-utils

npm i https://pkg.pr.new/cloudflare/workers-sdk/@cloudflare/workers-utils@15334

wrangler

npm i https://pkg.pr.new/cloudflare/workers-sdk/wrangler@15334

commit: a2a85c4

@dario-piotrowicz
dario-piotrowicz requested review from dario-piotrowicz and removed request for emily-shen September 10, 2026 10:59
@workers-devprod

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • @cloudflare/wrangler
Show detailed file reviewers
  • .changeset/two-lamps-leave.md: [@cloudflare/wrangler]
  • packages/miniflare/src/workers/d1/dumpSql.ts: [@cloudflare/wrangler]

@devin-ai-integration devin-ai-integration 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.

Note

This report is out of date. Scroll down for Devin Review's latest report on this PR.

🔍 Devin Review: 1 flag

Not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

@dario-piotrowicz dario-piotrowicz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Generally looks ok to me, besides the one small thing I commented on

Also the CI seems quite red and there's a merge conflict 🥲


// Taken from SQLite shell.c.in https://github.com/sqlite/sqlite/blob/105c20648e1b05839fd0638686b95f2e3998abcb/src/shell.c.in#L8463-L8469
// @ts-expect-error -- SqlStorageStatement needs to be callable
// @ts-ignore (SqlStorageStatement needs to be callable)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why this change? generally @ts-expect-error is preferred

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh I see what might happened. This file is vendored into the d1 codebase, and I fixed it there first. I then just copied the file over here and reverted all of the changes that were made by others.

It seems like there are other changes, so I will need to copy them back over at some point.

At the time this file was written, there wasn't a good package to put a file that could be imported into the d1-worker durable object code, so the file was vendored in both places and kept in sync by hand (or not, as I found out when I joined and changes had been made in both places).

I feel like things might have changed since then. Is there somewhere that we could move this file so that we can import it from our DO code and also import it from miniflare, to avoid this?

@alsuren
alsuren force-pushed the dlaban/CFSQL-1294-dump-newlines branch from 33217f3 to 0fdb6e7 Compare September 21, 2026 14:51
@workers-devprod

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • @cloudflare/wrangler
Show detailed file reviewers
  • .changeset/two-lamps-leave.md: [@cloudflare/wrangler]
  • packages/miniflare/src/workers/d1/dumpSql.ts: [@cloudflare/wrangler]

devin-ai-integration[bot]

This comment was marked as resolved.

…es in export

If newline and backslash n are both taken, it picks a new string to use
@alsuren
alsuren force-pushed the dlaban/CFSQL-1294-dump-newlines branch from 0fdb6e7 to e8825e6 Compare September 21, 2026 15:43
@workers-devprod

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • ✅ @cloudflare/wrangler
Show detailed file reviewers

@workers-devprod workers-devprod 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.

Codeowners reviews satisfied

@clanky-the-clanker clanky-the-clanker 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.

💬 Approved with comments — The ported escaping logic is correct. There are two non-blocking notes: no regression test in this repository, and a small wording tweak in the changeset.

Findings: 2 info (2 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

Logic matches SQLite's algorithm; no regression test in this repository.

Recommendation: 💬 Optional Nits

  • [INFO] No regression test in this repository for the newline/backslash-n collision fix; the existing miniflare D1 dumpSql suite could cover it. (packages/miniflare/src/workers/d1/dumpSql.ts:206)
View full review

The new unusedString and outputQuotedEscapedString logic matches SQLite's algorithm:

  • The collision check runs on the original value.
  • The fallback format (\n0) is the same as SQLite's.
  • Quote doubling does not interfere with the placeholders.
  • The replace() nesting order is the same.

The only note is that this repository has no test for the fix. packages/miniflare/test/plugins/d1/suite.ts already has dumpSql round-trip tests, and a case for this would fit there.


📝 Documentation: 💬 1 info

Minor wording clarification in the changeset.

Recommendation: 💬 Optional Nits

  • [INFO] Clarify that \n in the changeset means the literal two-character sequence. (.changeset/two-lamps-leave.md:7)
View full review

The changeset is accurate. Saying "literal \n" would make it clearer which input was affected.


✅ All other checks passed

🔒 Security: ✅ LGTM

No security concerns. The placeholders contain no single quotes, so the generated SQL literals stay properly quoted.


Reviewed commit: a2a85c4d

// Ported `output_quoted_escaped_string` from https://github.com/sqlite/sqlite/blob/master/src/shell.c.in#L1799-L1862
// Ported from SQLite's pre-unistr() `output_quoted_escaped_string` in shell.c.in.
// https://github.com/sqlite/sqlite/blob/dd2deecbbd03ec1478701b2029479c4983d8fae7/src/shell.c.in#L1959-L2015
function outputQuotedEscapedString(cell: unknown) {

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.

ℹ️ INFO · Code Quality

No regression test in this repository for the newline/backslash-n collision fix; the existing miniflare D1 dumpSql suite could cover it.

This changes the SQL emitted for any text cell that contains \n or \r, but none of the tests in this repository cover it. Tests elsewhere don't run in this repository's CI, so a future change to this copy could break it without anyone noticing. Consider adding a round-trip case to the dumpSql tests in packages/miniflare/test/plugins/d1/suite.ts: a real newline together with a literal \n, a value that also contains \012 (to hit the (\n0) fallback), and the same cases for \r.


Fix newline escaping edge-case for `wrangler d1 export --local`.

Previously, if you had a text field with both a real newline and a '\n' escaped newline, it would output both as real newlines.

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.

ℹ️ INFO · Documentation

Clarify that \n in the changeset means the literal two-character sequence.

"a '\n' escaped newline" could be read as a second real newline rather than the literal backslash-n characters that collide with the placeholder. Wording it as "a literal \n character sequence" would make the fixed edge case clearer to readers of the changelog.

@devin-ai-integration devin-ai-integration 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.

Devin Review found 1 new potential issue.

Devin Review

Comment on lines +214 to +224
const newlinePlaceholder = hasNewline
? unusedString(value, "\\n", "\\012")
: "";
const carriageReturnPlaceholder = hasCarriageReturn
? unusedString(value, "\\r", "\\015")
: "";

// Function to replace ' with '', while also tracking whether the string contains any \r or \n chars
const escapeQuotesDetectingNewlines = (_: string, lf: string, cr: string) => {
if (lf) {
lfs = true;
return `\\n`;
}
if (cr) {
crs = true;
return `\\r`;
}
return `''`;
};
const escaped = value
.replaceAll("'", "''")
.replaceAll("\n", newlinePlaceholder)
.replaceAll("\r", carriageReturnPlaceholder);

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.

🔴 Unrestorable exports for multiline text

For a large multiline value containing literal \n, outputQuotedEscapedString can push the INSERT over workerd’s 100,000-byte limit. Export succeeds, but local restore rejects the file.

Learn more

Local export writes the generated INSERT statements without checking whether they fit the pinned workerd runtime’s 100,000-byte SQL statement limit. A bound value can fit in the database even when writing it out as a SQL literal exceeds that limit. The new fallback uses four or more bytes per newline rather than two. Local restore splits the file into statements and submits each INSERT whole, so the added bytes can make SQLite reject it.

Example: Bind and insert a text value containing 3,700 lines of warning: retrying job 047 followed by format: \n with a literal backslash. The value occupies 96,210 bytes. The old export emitted a 99,972-byte INSERT that ran but changed the literal \n. The new export emits a 107,374-byte INSERT that SQLite rejects with the workerd limit. An unused one-byte marker preserves the same input in a 96,271-byte INSERT.

Recommended fix: Check the full INSERT’s UTF-8 byte length when a collision expands it. If it crosses the statement limit, try a more compact, collision-free representation, such as an unused single-byte printable marker. Verify that the resulting SQL fits and round-trips the exact value through local export and execution.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Untriaged

Development

Successfully merging this pull request may close these issues.

D1 export by Wrangler did not escape the literal \n properly

5 participants