Skip to content

fix(db): detect Postgres dialect reliably under minification - #2138

Closed
neobones wants to merge 2 commits into
emdash-cms:mainfrom
neobones:fix/postgres-dialect-detection-minified
Closed

neobones wants to merge 2 commits into
emdash-cms:mainfrom
neobones:fix/postgres-dialect-detection-minified

Conversation

@neobones

@neobones neobones commented Jul 19, 2026 •

Copy link
Copy Markdown

What does this PR do?

Fixes Postgres dialect misdetection under minification, which makes the documented Postgres setup fail on the very first migration.

With the documented config:

import { postgres } from "emdash/db";
emdash({ database: postgres({ connectionString: process.env.DATABASE_URL }) })

an Astro SSR production build fails at startup:

Migration failed: function datetime(unknown) does not exist (migration: 001_initial)

Root cause: detectDialect (packages/core/src/database/dialect-helpers.ts) identifies the dialect solely by the adapter class name:

if (db.getExecutor().adapter.constructor.name === "PostgresAdapter") return "postgres";
return "sqlite";

When the consuming app bundles + minifies emdash, the PostgresAdapter class name is mangled, so a real Postgres connection is misdetected as SQLite and the timestamp helpers emit SQLite-only SQL (datetime('now')), which PostgreSQL rejects. (The build also surfaces the related warning Import "createCoalescingDialect" will always be undefined … emdash/dist/db/sqlite.mjs.) The helpers themselves branch correctly — only the detection is unreliable.

Fix: fall back to the adapter's supportsMultipleConnections capability — the same signal this codebase already uses to distinguish SQLite from Postgres (see emdash-runtime.ts). Confirmed against the real Kysely adapters: PostgresAdapter reports true, SqliteAdapter reports false.

Closes #

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes — see note below
  • pnpm lint passes — see note below
  • pnpm test passes — see note below
  • pnpm format has been run — see note below
  • I have added/updated tests for my changes
  • User-visible strings wrapped for translation (n/a — no admin UI strings)
  • I have added a changeset (emdash patch)
  • New features link to an approved Discussion (n/a — bug fix)

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8

Screenshots / test output

Transparency: I did not run the full monorepo suite (pnpm typecheck/lint/test/format) in my fork; the maintainer CI will. What I did verify:

  • End-to-end against a real managed PostgreSQL backend (isolated schema via search_path): with this change emdash's migrations apply cleanly and the CMS boots and serves on Postgres; without it, the same setup fails at 001_initial as shown above.

  • Adapter capability ground truth, instantiating the real Kysely dialects:

    postgres | name: PostgresAdapter | supportsMultipleConnections: true
    sqlite   | name: SqliteAdapter   | supportsMultipleConnections: false
    
  • New tests (packages/core/tests/unit/database/dialect-helpers.test.ts) instantiate the real PostgresDialect and SqliteDialect adapters (plus a minified-name stub), so the fallback is validated against actual runtime behavior rather than hand-rolled stubs.

emdash version reproduced on: 0.29.0.

@changeset-bot

changeset-bot Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 30290ad

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

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds 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-actions github-actions Bot added review/needs-review No maintainer or bot review yet area/core size/M labels Jul 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor


Thank you for your submission, we really appreciate it. Like many open-source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution. You can sign the CLA by just posting a Pull Request Comment same as the below format.


I have read the CLA Document and I hereby sign the CLA


You can retrigger this bot by commenting recheck in this Pull Request. Posted by the CLA Assistant Lite bot.

@emdashbot emdashbot 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.

This PR fixes a real failure: after minification, PostgresAdapter class names are mangled, so detectDialect falls back to SQLite SQL and the first Postgres migration fails. Adding a behavioral fallback is the right direction.

However, the chosen fallback signal — adapter.supportsTransactionalDdl === true — is only safe if Kysely's SQLite/libSQL/D1 adapters report false for that property. The repo's own emdash-runtime.ts comment (line ~1121) distinguishes SQLite from Postgres via supportsMultipleConnections, not supportsTransactionalDdl, so that assumption needs to be proven. More importantly, the new unit test uses hand-rolled fake adapters (class Ae { supportsTransactionalDdl = true }), which exercises the code's own assumption rather than the actual runtime behavior. If Kysely's real SqliteAdapter also reports supportsTransactionalDdl: true, a minified SQLite build would now be misdetected as Postgres and emit broken SQL — the inverse of the bug being fixed.

I also don't see a changeset for the published emdash package, which AGENTS/CONTRIBUTING requires for user-facing package changes.

I'd ask the author to add tests that instantiate the real Kysely PostgresDialect and SqliteDialect adapters, and to add the missing changeset. If the real-adapter tests reveal that supportsTransactionalDdl is not a unique Postgres signal, switch to a Postgres-only capability (e.g. supportsMultipleConnections, or a combined check) instead.

`detectDialect` relied solely on `db.getExecutor().adapter.constructor.name ===
"PostgresAdapter"`. When the consuming app bundles and minifies emdash (e.g. an
Astro SSR production build), the adapter class name is mangled, so the check
fails and a real Postgres connection is misdetected as SQLite. The dialect
helpers then emit SQLite-only SQL such as `datetime('now')`, and the very first
migration fails on Postgres with:

    function datetime(unknown) does not exist (migration: 001_initial)

Fix: fall back to the adapter's `supportsMultipleConnections` capability — the
same signal this codebase already uses to tell SQLite from Postgres (see
emdash-runtime.ts). Verified against the real Kysely adapters: PostgresAdapter
reports `true`, SqliteAdapter reports `false`.

Tests instantiate the real Kysely `PostgresDialect` and `SqliteDialect` adapters
(plus a minified-name stub) so the fallback is validated against actual runtime
behavior, not hand-rolled stubs. Adds a changeset (`emdash` patch).

Also verified end-to-end against a real managed PostgreSQL backend: emdash
migrations apply cleanly and the CMS boots and serves on Postgres.
@neobones
neobones force-pushed the fix/postgres-dialect-detection-minified branch from 918ce06 to db25777 Compare July 19, 2026 19:05
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/needs-review No maintainer or bot review yet labels Jul 19, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/admin@2138

@emdash-cms/auth

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/auth@2138

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/auth-atproto@2138

@emdash-cms/blocks

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/blocks@2138

@emdash-cms/cloudflare

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/cloudflare@2138

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/contentful-to-portable-text@2138

emdash

npm i https://pkg.pr.new/emdash-cms/emdash@2138

create-emdash

npm i https://pkg.pr.new/emdash-cms/emdash/create-emdash@2138

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/gutenberg-to-portable-text@2138

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-cli@2138

@emdash-cms/plugin-types

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-types@2138

@emdash-cms/registry-client

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-client@2138

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-lexicons@2138

@emdash-cms/registry-verification

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-verification@2138

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/sandbox-workerd@2138

@emdash-cms/x402

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/x402@2138

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-ai-moderation@2138

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-atproto@2138

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-audit-log@2138

@emdash-cms/plugin-color

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-color@2138

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-embeds@2138

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-field-kit@2138

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-forms@2138

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-webhook-notifier@2138

commit: db25777

@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026

@emdashbot emdashbot 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.

This is a re-review. The author addressed the prior feedback: the fallback signal switched from supportsTransactionalDdl to supportsMultipleConnections, the new unit tests instantiate the real Kysely PostgresDialect/SqliteDialect adapters, the manual stub is more realistic, and a changeset was added. Those are all improvements.

However, the chosen fallback is still not a unique Postgres signal, and this PR would introduce the inverse bug on Cloudflare D1/DO SQL with coalescing enabled. EmDash's own CoalescingD1Adapter (in packages/cloudflare/src/db/coalescing-d1.ts) and CoalescingDOSqlAdapter (in packages/cloudflare/src/db/coalescing-do-sql.ts) extend SqliteAdapter but override supportsMultipleConnections to true so Kysely will let same-turn SELECTs reach the coalescing buffer. With the new detectDialect logic, those request-scoped Kysely instances will be classified as "postgres", and every dialect helper (currentTimestamp, buildStatusCondition, tableExists, indexExists, columnExists, listTablesLike, binaryType, jsonExtractExpr) will emit Postgres-only SQL (CURRENT_TIMESTAMP, ::timestamptz, information_schema, pg_indexes, bytea, ->>) against a SQLite/D1/DO database. That breaks the runtime on a supported backend.

The safer fix is to rule out SQLite-family adapters before applying the capability fallback. instanceof SqliteAdapter is minification-proof (the class identity survives bundling even when the name is mangled), and it catches stock SqliteAdapter, D1, DO SQL, libSQL, and the coalescing subclasses. After that, the PostgresAdapter name check plus the supportsMultipleConnections fallback can still catch minified Postgres.

I also added a test request for the coalescing case, because the current tests don't exercise the exact EmDash adapters that make supportsMultipleConnections a non-unique signal.

Everything else looks fine: the changeset is present and written for users, tests were added, no admin UI strings are involved, and no SQL injection or authorization issues were introduced.

Comment on lines +40 to +42
adapter.constructor.name === "PostgresAdapter" ||
adapter.supportsMultipleConnections === true
) {

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.

[needs fixing] The fallback treats adapter.supportsMultipleConnections === true as a Postgres-only signal, but EmDash's own coalescing SQLite adapters (CoalescingD1Adapter in packages/cloudflare/src/db/coalescing-d1.ts and CoalescingDOSqlAdapter in packages/cloudflare/src/db/coalescing-do-sql.ts) extend SqliteAdapter and deliberately override this getter to true. On Cloudflare D1/DO SQL with coalescing enabled, the request-scoped Kysely uses one of those adapters, so detectDialect will return "postgres" and every dialect helper will emit Postgres-only SQL against SQLite — the inverse of the original bug on another supported runtime.

Rule out SQLite-family adapters first with instanceof SqliteAdapter; class identity survives minification, so this catches stock SQLite, D1, DO SQL, libSQL, and the coalescing subclasses. The name/capability fallback can then safely identify Postgres.

Suggested change
adapter.constructor.name === "PostgresAdapter" ||
adapter.supportsMultipleConnections === true
) {
import type { ColumnDataType, Kysely, RawBuilder } from "kysely";
import { sql, SqliteAdapter } from "kysely";
Suggested change
adapter.constructor.name === "PostgresAdapter" ||
adapter.supportsMultipleConnections === true
) {
export function detectDialect(db: Kysely<any>): DatabaseDialectType {
const adapter = db.getExecutor().adapter;
// Class identity survives minification and catches SQLite, D1, DO SQL,
// libSQL, and EmDash's coalescing SQLite adapters that report
// supportsMultipleConnections=true to lift Kysely's connection mutex.
if (adapter instanceof SqliteAdapter) {
return "sqlite";
}
if (
adapter.constructor.name === "PostgresAdapter" ||
adapter.supportsMultipleConnections === true
) {
return "postgres";
}
return "sqlite";
}

getExecutor: () => ({ adapter }),
} as unknown as Kysely<Record<string, never>>;
expect(detectDialect(db)).toBe("postgres");
});

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.

[needs fixing] The minified-name stub only exercises an anonymous object with supportsMultipleConnections: true. It doesn't cover the EmDash adapters that make the fallback unsafe: CoalescingD1Adapter and CoalescingDOSqlAdapter extend SqliteAdapter but override supportsMultipleConnections to true. Add a regression test that such a subclass is still detected as "sqlite" so the D1/DO coalescing path can't regress.

Suggested change
});
it("still detects SQLite when a SqliteAdapter subclass reports supportsMultipleConnections", () => {
// EmDash's coalescing D1/DO adapters extend SqliteAdapter but override
// supportsMultipleConnections to true to lift Kysely's per-connection
// mutex for query batching. They must not be mis-detected as Postgres.
class CoalescingSqliteAdapter extends SqliteAdapter {
override get supportsMultipleConnections(): boolean {
return true;
}
}
const adapter = new CoalescingSqliteAdapter();
const db = {
getExecutor: () => ({ adapter }),
} as unknown as Kysely<Record<string, never>>;
expect(detectDialect(db)).toBe("sqlite");
});

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-rereview New commits since the last review labels Jul 20, 2026
@ascorbic

Copy link
Copy Markdown
Member

Thanks for the contribution. We needed to get this fix in, so have superseded it with #2193

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

Labels

area/core cla: needed review/awaiting-author Reviewed; waiting on the author to respond size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants