Repository navigation
db adapter plugins - #2
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughIntroduce a plugin-based adapter resolver and types, extract and publish multiple standalone adapter packages, remove in-repo adapter factories, wire missing-plugin auto-install into the compile pipeline, change runtime/compiled detection, adjust SQLite/Docker adapters, update tests/docs, and remove pglite runtime probe from doctor output. Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as CLI/User
participant Pipeline as runCompilePipeline
participant Resolver as resolveAdapterPlugin
participant Registry as BuiltinRegistry
participant Loader as DynamicImporter
participant Installer as onMissingPlugin
participant Plugin as AdapterPlugin
participant DB as Database
CLI->>Pipeline: start compilation (devUrl, context, sqldocDir)
Pipeline->>Resolver: resolveAdapterPlugin(devUrl, context, sqldocDir, onMissingPlugin)
Resolver->>Resolver: extractScheme(devUrl)
Resolver->>Registry: check builtin plugins
alt builtin found
Registry-->>Resolver: plugin
else not builtin
Resolver->>Loader: try dynamic import (package, maybe sqldocDir)
alt import succeeds
Loader-->>Resolver: plugin module
else import fails
Resolver->>Installer: onMissingPlugin(package, version)?
alt installer installs
Installer-->>Resolver: installed
Resolver->>Loader: retry import
Loader-->>Resolver: plugin module
else installer declined
Resolver-->>Pipeline: throw error
end
end
end
Resolver->>Plugin: validate + createAdapter(devUrl, context)
Plugin->>DB: connect/initialise
DB-->>Plugin: ready
Plugin-->>Resolver: DatabaseAdapter
Resolver-->>Pipeline: DatabaseAdapter
Pipeline-->>CLI: proceed with compile using adapter
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Externalize all non-builtin database adapters into separate packages that are auto-installed on first use
302a54d to
63fe06a
Compare
Deploying sqldoc with
|
| Latest commit: |
112b761
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://6e2ba470.sqldoc.pages.dev |
| Branch Preview URL: | https://feat-db-adapter-plugins.sqldoc.pages.dev |
There was a problem hiding this comment.
Actionable comments posted: 17
🧹 Nitpick comments (11)
packages/db-neon-temporary/.gitignore (1)
1-2: Duplicate.enventry.The
.envpattern is listed twice. Remove the duplicate line.Proposed fix
.env -.env🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/.gitignore` around lines 1 - 2, The .gitignore contains a duplicated ".env" entry; edit the packages/db-neon-temporary/.gitignore to remove the redundant ".env" line so only a single ".env" entry remains, leaving all other patterns unchanged.tests/pagila/pagila.test.ts (1)
65-70: Consider extracting nested ternary to improve readability.The three-way conditional for adapter creation is flagged by SonarCloud. Whilst functional, a helper function or early-return pattern would clarify the intent.
♻️ Suggested refactor
+ async function createLiveDbAdapter(devUrl: string | undefined) { + if (devUrl === 'neon-temporary') { + return neonTemporaryPlugin.createAdapter('neon-temporary', { dialect: 'postgres', extensions: [] }) + } + if (devUrl) { + return createPostgresDockerAdapter(devUrl) + } + return pglitePlugin.createAdapter('pglite', { dialect: 'postgres', extensions: [] }) + } + it(`${testTitle}: live DB diff against original SQL produces zero changes`, async () => { - const liveDb = - devUrl === 'neon-temporary' - ? await neonTemporaryPlugin.createAdapter('neon-temporary', { dialect: 'postgres', extensions: [] }) - : devUrl - ? await createPostgresDockerAdapter(devUrl) - : await pglitePlugin.createAdapter('pglite', { dialect: 'postgres', extensions: [] }) + const liveDb = await createLiveDbAdapter(devUrl)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/pagila/pagila.test.ts` around lines 65 - 70, The nested ternary assigning liveDb is hard to read; replace it with a small helper or early-return if/else that branches on devUrl to call neonTemporaryPlugin.createAdapter('neon-temporary', ...), createPostgresDockerAdapter(devUrl), or pglitePlugin.createAdapter('pglite', ...). Locate the liveDb assignment and refactor into either a getAdapterForDevUrl(devUrl) helper or explicit if (devUrl === 'neon-temporary') / else if (devUrl) / else blocks that call neonTemporaryPlugin.createAdapter, createPostgresDockerAdapter, or pglitePlugin.createAdapter respectively to improve readability and satisfy SonarCloud.packages/db-mysql/src/index.ts (1)
20-20: Avoid passingnormalizeValuedirectly to.map().When a function is passed directly to
map(), it receives(element, index, array)as arguments. IfnormalizeValueever inspects additional parameters, this could cause unexpected behaviour.♻️ Proposed fix
- rows: (rows as unknown[][]).map((row) => (row as unknown[]).map(normalizeValue)), + rows: (rows as unknown[][]).map((row) => row.map((v) => normalizeValue(v))),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-mysql/src/index.ts` at line 20, The current rows mapping passes normalizeValue directly to .map, which can forward extra arguments; update both maps to call normalizeValue via a unary wrapper so only the element is passed — e.g., replace (rows as unknown[][]).map((row) => (row as unknown[]).map(normalizeValue)) with a nested mapping that uses (v) => normalizeValue(v) for the inner .map (and similarly wrap the outer map callback) referencing the normalizeValue function and the rows mapping expression in index.ts.packages/db-postgres/src/index.ts (1)
21-21: WrapnormalizeValueto avoid passing extra map arguments.♻️ Proposed fix
- rows: (result.rows as unknown[][]).map((row) => row.map(normalizeValue)), + rows: (result.rows as unknown[][]).map((row) => row.map((v) => normalizeValue(v))),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-postgres/src/index.ts` at line 21, The current rows mapping uses row.map(normalizeValue) which forwards extra arguments (index, array) to normalizeValue; wrap normalizeValue in a single-arg arrow to ensure only the value is passed. Replace the mapping expression on result.rows with (result.rows as unknown[][]).map(row => row.map(v => normalizeValue(v))) so normalizeValue receives only the cell value.packages/db-mysql/package.json (1)
6-14: TypeScript source as export entry point.Exporting
./src/index.tsdirectly works with Bun but may cause issues with Node.js consumers that don't have TypeScript transpilation configured. If this package is intended for broader consumption, consider adding a build step.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-mysql/package.json` around lines 6 - 14, The package.json currently points "exports", "main", and "types" at the TypeScript source ("./src/index.ts"), which will break Node consumers without TS transpilation; add a build step to emit compiled JS and type declarations (e.g., compile to dist/ and generate .d.ts), then update "main" and each export entry under "exports" to point to the compiled JS (e.g., "./dist/index.js") and update "types" to the emitted declaration file (e.g., "./dist/index.d.ts"); ensure your build script (e.g., "build": "tsc --build") is added to package.json and CI/publish runs it before publishing so consumers get JS + .d.ts rather than raw .ts.packages/db/src/db/sqlite.ts (1)
22-22: WrapnormalizeValueto avoid passing extra map arguments.Same issue as other adapters—pass explicitly to prevent potential issues if
normalizeValuesignature changes.♻️ Proposed fix
- rows: (rows as unknown[][]).map((row) => row.map(normalizeValue)), + rows: (rows as unknown[][]).map((row) => row.map((v) => normalizeValue(v))),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db/src/db/sqlite.ts` at line 22, The rows mapping passes normalizeValue directly which can forward extra arguments if its signature changes; update the inner map in the rows assignment in sqlite.ts (the expression using (rows as unknown[][]).map((row) => row.map(...))) to call normalizeValue via an explicit single-argument wrapper (e.g., row.map((val) => normalizeValue(val))) so only the cell value is passed to normalizeValue.packages/db-pglite/src/index.ts (1)
43-47: Handle empty result array inexec.If
db.exec(sql)returns an empty array (e.g., for a no-op SQL statement), accessingresult[result.length - 1]returnsundefined, and the nullish coalescing correctly handles it. However, the logic would be clearer with an explicit check.♻️ Optional clarification
async exec(sql: string): Promise<ExecResult> { const result = await db.exec(sql) - const last = result[result.length - 1] - return { rowsAffected: last?.affectedRows ?? 0 } + return { rowsAffected: result.at(-1)?.affectedRows ?? 0 } },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-pglite/src/index.ts` around lines 43 - 47, In exec, explicitly handle the case where db.exec(sql) returns an empty array instead of relying only on last?.affectedRows; after calling db.exec(sql) (the result variable), if result.length === 0 return { rowsAffected: 0 } immediately, otherwise set last = result[result.length - 1] and return { rowsAffected: last.affectedRows ?? 0 } so that the exec method and ExecResult clearly handle no-op SQL results.packages/db/src/db/plugin-resolver.ts (1)
106-170: Consider extracting validation logic to reduce cognitive complexity.SonarCloud reports cognitive complexity of 16 (limit 15). The validation section (lines 150-167) could be extracted into a separate
validatePluginfunction to improve readability and reduce complexity.♻️ Proposed refactor
function validatePlugin( plugin: DatabaseAdapterPlugin, packageName: string, scheme: string, dialect: string, ): void { if (plugin.apiVersion !== 1) { throw new Error(`${packageName} has unsupported apiVersion ${plugin.apiVersion} (expected 1).`) } if (!plugin.schemes.includes(scheme)) { throw new Error(`${packageName} does not handle scheme '${scheme}'. It handles: ${plugin.schemes.join(', ')}`) } if (!plugin.dialects.includes(dialect as any)) { throw new Error( `${packageName} does not support dialect '${dialect}'. It supports: ${plugin.dialects.join(', ')}`, ) } if (plugin.runtime !== 'any') { const currentRuntime = isBun ? 'bun' : 'node' if (plugin.runtime !== currentRuntime) { throw new Error(`${packageName} requires '${plugin.runtime}' but running on '${currentRuntime}'.`) } } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db/src/db/plugin-resolver.ts` around lines 106 - 170, Extract the validation block in resolveAdapterPlugin into a new helper function validatePlugin(plugin: DatabaseAdapterPlugin, packageName: string, scheme: string, dialect: string) that performs the apiVersion, schemes, dialects and runtime checks (including using isBun to determine currentRuntime) and throws the same errors; replace the inline validation (the if checks that reference plugin.apiVersion, plugin.schemes, plugin.dialects, plugin.runtime) with a single call validatePlugin(plugin, packageName, scheme, context.dialect) before returning plugin.createAdapter(devUrl, context).packages/db-neon-temporary/src/index.ts (2)
182-184: ValidatelockTimeoutMsis a safe integer to prevent injection.While
lockTimeoutMsis a plugin property (controlled), it's interpolated directly into SQL. For defence in depth, validate it's a reasonable positive integer.🛡️ Proposed defensive fix
log('acquiring advisory lock...') - await adapter.exec(`SET lock_timeout = '${plugin.lockTimeoutMs}ms'`) + const timeoutMs = Math.max(0, Math.floor(plugin.lockTimeoutMs)) + await adapter.exec(`SET lock_timeout = '${timeoutMs}ms'`) await adapter.exec(`SELECT pg_advisory_lock(${LOCK_KEY})`)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 182 - 184, The code interpolates plugin.lockTimeoutMs directly into SQL (in the adapter.exec calls around log('acquiring advisory lock...') and SELECT pg_advisory_lock(${LOCK_KEY})), which could allow injection if the value is not a safe integer; fix by normalizing and validating plugin.lockTimeoutMs before use: coerce to a Number (or parseInt), ensure Number.isSafeInteger(value) and value > 0 and within a reasonable max (e.g. configurable maxLockTimeoutMs), otherwise throw or fall back to a safe default, and then pass that validated numeric value into adapter.exec (or use a parameterized query API if available) instead of interpolating the raw plugin value.
45-54: Auto-create.sqldocdirectory insaveCache()to ensure caching works reliably.
getCachePath()returnsnullif no.sqldocdirectory is found, causingsaveCache()to silently skip. If a fresh project or a cloned repository hasn't runsqldoc init, the cache won't save and the Neon database will be recreated on every invocation—wasting API calls and increasing latency.Modify
saveCache()to create the.sqldocdirectory if missing before attempting to write the cache file:Suggested fix
function saveCache(data: CachedDb): void { const cachePath = getCachePath() if (!cachePath) { // Create .sqldoc in the current working directory if no parent has it const sqldocDir = path.join(process.cwd(), '.sqldoc') fs.mkdirSync(sqldocDir, { recursive: true }) const newCachePath = path.join(sqldocDir, CACHE_FILE) fs.writeFileSync(newCachePath, `${JSON.stringify(data, null, 2)}\n`) log(`cached to ${newCachePath}`) return } fs.writeFileSync(cachePath, `${JSON.stringify(data, null, 2)}\n`) log(`cached to ${cachePath}`) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 45 - 54, The saveCache() function should ensure the .sqldoc directory exists before writing the cache so caching works when getCachePath() returns null; update saveCache() to detect a null cachePath, create the .sqldoc directory (e.g. path.join(process.cwd(), '.sqldoc')) with fs.mkdirSync(..., { recursive: true }), then write the CACHE_FILE into that directory (using JSON.stringify(data, null, 2) + '\n') and log the new path; otherwise keep the existing behavior of writing to the returned cachePath and logging it.tests/postgraphile-kitchensink/kitchen-sink.test.ts (1)
27-31: Extract nested ternary for readability.The nested ternary on line 30 is flagged by SonarCloud and reduces readability. Consider extracting it into a helper function or using an if-else block.
♻️ Proposed refactor
+function getDevUrl(version: string | undefined): string | undefined { + if (version === 'neon-temporary') return 'neon-temporary' + if (version) return `docker://${version}` + return undefined +} + versions.forEach((version) => { const timeout = version === 'neon-temporary' ? 600_000 : 120_000 describe(`postgraphile kitchen-sink schema - ${version ?? 'pglite'}`, { timeout }, () => { - const devUrl = version === 'neon-temporary' ? 'neon-temporary' : version ? `docker://${version}` : undefined + const devUrl = getDevUrl(version) const testTitle = version ?? 'pglite'🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/postgraphile-kitchensink/kitchen-sink.test.ts` around lines 27 - 31, The nested ternary used to compute devUrl inside the versions.forEach block reduces readability; replace it by extracting the logic into a small helper or an explicit if/else before the describe call (e.g., implement a getDevUrl(version) function or set devUrl via if/else), and then use that helper/variable in the describe block and for testTitle if needed; update references to the devUrl variable (and testTitle if you choose to derive it similarly) so the describe call reads clearly without nested ternaries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.env:
- Around line 1-5: This file contains committed DB credentials (DATABASE_URL,
DATABASE_URL_DIRECT, PUBLIC_POSTGRES_CLAIM_URL); remove the secrets by renaming
this file to .env.example and replace the values with placeholder strings for
DATABASE_URL and DATABASE_URL_DIRECT (e.g. POSTGRES_URL_PLACEHOLDER) and a
placeholder for PUBLIC_POSTGRES_CLAIM_URL, then add a new .env to .gitignore at
repo root to prevent committing real credentials; after that, consider rotating
the exposed credentials and removing the secret from git history if needed.
In `@packages/cli/src/commands/schema.ts`:
- Around line 28-30: The new URL branch that treats plugin-backed sources
(extractScheme -> scheme !== source) bypasses the adapter auto-install wiring
used when creating runners; update schemaInspectCommand() and diffWithLiveDb()
to create runners using the same pipeline runner setup that includes sqldocDir
and onMissingPlugin (the same parameters/logic added around createRunner in
packages/cli/src/utils/pipeline.ts lines ~118-130). Locate the createRunner
calls used by schemaInspectCommand and diffWithLiveDb and thread the sqldocDir
value and the onMissingPlugin handler into those calls (mirror the wiring used
in the pipeline util) so that plugin-backed sources like neon:// will trigger
the adapter install prompt.
In `@packages/cli/src/runtime.ts`:
- Around line 14-18: The isCompiledBinary() function currently compares
COMPILED_SQLDOC to the string 'true' and will throw a ReferenceError if
COMPILED_SQLDOC is undefined; change it to first guard against an undefined
global (use typeof COMPILED_SQLDOC !== 'undefined'), then handle both boolean
and string forms (if COMPILED_SQLDOC is a boolean return it directly, otherwise
coerce/compare the string form to 'true') so isCompiledBinary() returns true
when the build injects a true boolean and also works in dev/test where the
identifier may be absent.
In `@packages/cli/src/utils/pipeline.ts`:
- Around line 118-129: The code uses findSqldocDir() without the target project
root, so sqldocDir is resolved from the caller's CWD instead of the intended
project; change the resolution used before createRunner to call findSqldocDir
with the target project root (the configRoot/third-parameter value passed into
this pipeline) so sqldocDir = findSqldocDir(configRoot) ?? undefined, ensuring
createRunner and the onMissingPlugin install flow (promptInstall /
installPackages) operate against the target project rather than the caller's
working directory.
In `@packages/db-mysql/src/index.ts`:
- Line 11: The createAdapter method in packages/db-mysql/src/index.ts does not
match the DatabaseAdapterPlugin interface: change the signature of createAdapter
to accept the second parameter (context: AdapterPluginContext) in addition to
the connection string so it conforms to createAdapter(devUrl: string, context:
AdapterPluginContext): Promise<DatabaseAdapter>; add an import for
AdapterPluginContext from the db types file if missing and, if the context is
unused, keep using it only for type compatibility (e.g., accept but not
reference it) so the implementation matches the interface contract.
In `@packages/db-neon-temporary/src/__tests__/neon-temporary.test.ts`:
- Line 18: The test file mutates the module-global singleton by setting
plugin.lockTimeoutMs = 5000 at module scope; capture the original value before
altering and restore it after the test(s) to avoid leaking state. Modify the
file to move the assignment into a lifecycle hook: in a before (or beforeEach)
hook save const originalLockTimeout = plugin.lockTimeoutMs and then set
plugin.lockTimeoutMs = 5000, and in an after (or afterEach) hook restore
plugin.lockTimeoutMs = originalLockTimeout so other tests using the same plugin
are not affected.
In `@packages/db-neon-temporary/src/index.ts`:
- Line 163: The inner .map is passing (value, index, array) to normalizeValue
which can receive unexpected extra args; change the rows mapping to wrap
normalizeValue with a unary function so only the value is forwarded — e.g., in
the rows: (result.rows as unknown[][]).map((row) => row.map((v) =>
normalizeValue(v))) — locate the mapping that uses normalizeValue and replace
direct reference with an explicit single-argument wrapper to avoid extra
arguments being passed.
- Around line 106-114: The second fetch that reads the Neon DB info (using
NEON_API/${dbId} and variable dataRes) lacks error handling and can yield an
undefined connection_string used by toDirect/toPooler; update the fetch handling
in the same block to check dataRes.ok and throw a descriptive Error including
dataRes.status and dataRes.statusText when false, then parse the JSON and
validate that the parsed connection_string exists (throwing if missing) before
returning/using it so downstream calls to toDirect/toPooler never receive
undefined.
In `@packages/db-pglite/src/index.ts`:
- Line 40: The map callback is passing extra args to normalizeValue because
Array.map supplies (value, index, array); wrap normalizeValue in a unary wrapper
so it only receives the value. Update the rows mapping that uses (result.rows as
unknown[][]).map((row) => row.map(normalizeValue)) to use an explicit single-arg
arrow function (e.g., row.map(v => normalizeValue(v))) so normalizeValue is
invoked with only the cell value; do the same for any other uses of
normalizeValue in the file.
In `@packages/db-postgres/src/index.ts`:
- Line 11: The createAdapter method in this package currently has the wrong
signature; update the async createAdapter(connectionString: string):
Promise<DatabaseAdapter> to match the DatabaseAdapterPlugin interface by
changing its parameters to (devUrl: string, context: AdapterPluginContext) and
adjust the implementation to use devUrl instead of connectionString and to
consume the context as needed; also add the missing import for
AdapterPluginContext at the top of the file so the type resolves.
In `@packages/db/src/db/plugin-resolver.ts`:
- Around line 30-40: The built-in SQLite plugin's createAdapter currently has a
single parameter but must match the DatabaseAdapterPlugin signature
createAdapter(devUrl: string, context: AdapterPluginContext); update the
anonymous createAdapter function registered via registerBuiltin to accept both
(devUrl, context) and either pass context through to createSqliteAdapter if it
supports it or explicitly ignore/annotate it to satisfy TypeScript (keeping the
existing devUrl handling). Reference: registerBuiltin, createAdapter,
createSqliteAdapter, DatabaseAdapterPlugin, AdapterPluginContext.
- Around line 44-64: The two built-in registrations for 'bun-postgres' and
'bun-mysql' have createAdapter functions that are missing the required second
parameter (context) for interface conformance; update both async createAdapter
signatures in the registerBuiltin calls to accept (connectionString: string,
context) and pass the context through to createBunSqlAdapter so the call becomes
createBunSqlAdapter(connectionString, context), keeping the function names
registerBuiltin and createBunSqlAdapter unchanged.
In `@packages/db/src/db/postgres-docker.ts`:
- Around line 37-40: The call to resolveAdapterPlugin(...) in the
postgres-docker flow can throw if the `@sqldoc/db-postgres` adapter is not
preinstalled; update the postgres-docker path so resolveAdapterPlugin is invoked
with the onMissingPlugin mechanism from sqldocDir (or otherwise use the same
installer hook) so missing adapters are auto-installed instead of crashing.
Specifically, modify the code around pgAdapter = await resolveAdapterPlugin({
devUrl: connectionUri, ... }) to pass the onMissingPlugin handler (thread
through the sqldocDir/onMissingPlugin reference) or alternatively add
`@sqldoc/db-postgres` as a runtime dependency for this Docker flow so
resolveAdapterPlugin always finds the plugin.
In `@packages/db/src/db/sqlite.ts`:
- Around line 48-51: The empty-result branch currently returns columns: [] when
rows.length === 0, causing divergence from the Bun adapter which uses
stmt.columnNames; update the conditional so that when rows is empty you still
populate columns from stmt.columnNames (or a fallback derived from the prepared
statement) instead of returning an empty array, i.e., replace the columns = []
path with columns = stmt.columnNames ?? [] and keep rows as [] to align
behavior; adjust any surrounding logic in the function that reads rows/columns
(the block referencing rows, columns and stmt.columnNames) so both Node and Bun
adapters return the same column metadata on zero-row results.
In `@packages/sqldoc/src/commands/add.ts`:
- Line 6: The function isCompiledBinary in runtime.ts currently reads the bare
COMPILED_SQLDOC constant which causes a ReferenceError in uncompiled/dev mode;
update isCompiledBinary to guard access by checking typeof COMPILED_SQLDOC !==
'undefined' (or using globalThis['COMPILED_SQLDOC']) before reading/using it,
and then compare its value to the expected string to return the boolean. Ensure
all callers (e.g., imports in add.ts, init, upgrade) continue to call
isCompiledBinary() and do not reference COMPILED_SQLDOC directly.
In `@packages/sqldoc/src/runtime.ts`:
- Around line 8-12: The ReferenceError occurs because COMPILED_SQLDOC is only
declared for TS and not defined at runtime; update the declaration to allow
undefined (declare const COMPILED_SQLDOC: string | undefined) and modify
isCompiledBinary() to guard access using typeof (e.g., return typeof
COMPILED_SQLDOC === 'string' && COMPILED_SQLDOC === 'true') so the function
safely works in dev mode when the constant is not defined.
In `@site/guide/connection-urls.md`:
- Line 44: The docs claim the temporary Neon DB is reused for "24 hours" but the
implementation constant MAX_AGE_MS in the db-neon-temporary package is set to 72
hours; update the documentation in connection-urls.md to state "72 hours"
(replace the three occurrences mentioning 24 hours) so it matches the
implementation, or alternatively change MAX_AGE_MS in
packages/db-neon-temporary/src/index.ts to 24 * 60 * 60 * 1000 if you prefer the
docs to be authoritative—ensure whichever side you change (the doc text or the
MAX_AGE_MS value) is consistent across all mentions.
---
Nitpick comments:
In `@packages/db-mysql/package.json`:
- Around line 6-14: The package.json currently points "exports", "main", and
"types" at the TypeScript source ("./src/index.ts"), which will break Node
consumers without TS transpilation; add a build step to emit compiled JS and
type declarations (e.g., compile to dist/ and generate .d.ts), then update
"main" and each export entry under "exports" to point to the compiled JS (e.g.,
"./dist/index.js") and update "types" to the emitted declaration file (e.g.,
"./dist/index.d.ts"); ensure your build script (e.g., "build": "tsc --build") is
added to package.json and CI/publish runs it before publishing so consumers get
JS + .d.ts rather than raw .ts.
In `@packages/db-mysql/src/index.ts`:
- Line 20: The current rows mapping passes normalizeValue directly to .map,
which can forward extra arguments; update both maps to call normalizeValue via a
unary wrapper so only the element is passed — e.g., replace (rows as
unknown[][]).map((row) => (row as unknown[]).map(normalizeValue)) with a nested
mapping that uses (v) => normalizeValue(v) for the inner .map (and similarly
wrap the outer map callback) referencing the normalizeValue function and the
rows mapping expression in index.ts.
In `@packages/db-neon-temporary/.gitignore`:
- Around line 1-2: The .gitignore contains a duplicated ".env" entry; edit the
packages/db-neon-temporary/.gitignore to remove the redundant ".env" line so
only a single ".env" entry remains, leaving all other patterns unchanged.
In `@packages/db-neon-temporary/src/index.ts`:
- Around line 182-184: The code interpolates plugin.lockTimeoutMs directly into
SQL (in the adapter.exec calls around log('acquiring advisory lock...') and
SELECT pg_advisory_lock(${LOCK_KEY})), which could allow injection if the value
is not a safe integer; fix by normalizing and validating plugin.lockTimeoutMs
before use: coerce to a Number (or parseInt), ensure Number.isSafeInteger(value)
and value > 0 and within a reasonable max (e.g. configurable maxLockTimeoutMs),
otherwise throw or fall back to a safe default, and then pass that validated
numeric value into adapter.exec (or use a parameterized query API if available)
instead of interpolating the raw plugin value.
- Around line 45-54: The saveCache() function should ensure the .sqldoc
directory exists before writing the cache so caching works when getCachePath()
returns null; update saveCache() to detect a null cachePath, create the .sqldoc
directory (e.g. path.join(process.cwd(), '.sqldoc')) with fs.mkdirSync(..., {
recursive: true }), then write the CACHE_FILE into that directory (using
JSON.stringify(data, null, 2) + '\n') and log the new path; otherwise keep the
existing behavior of writing to the returned cachePath and logging it.
In `@packages/db-pglite/src/index.ts`:
- Around line 43-47: In exec, explicitly handle the case where db.exec(sql)
returns an empty array instead of relying only on last?.affectedRows; after
calling db.exec(sql) (the result variable), if result.length === 0 return {
rowsAffected: 0 } immediately, otherwise set last = result[result.length - 1]
and return { rowsAffected: last.affectedRows ?? 0 } so that the exec method and
ExecResult clearly handle no-op SQL results.
In `@packages/db-postgres/src/index.ts`:
- Line 21: The current rows mapping uses row.map(normalizeValue) which forwards
extra arguments (index, array) to normalizeValue; wrap normalizeValue in a
single-arg arrow to ensure only the value is passed. Replace the mapping
expression on result.rows with (result.rows as unknown[][]).map(row => row.map(v
=> normalizeValue(v))) so normalizeValue receives only the cell value.
In `@packages/db/src/db/plugin-resolver.ts`:
- Around line 106-170: Extract the validation block in resolveAdapterPlugin into
a new helper function validatePlugin(plugin: DatabaseAdapterPlugin, packageName:
string, scheme: string, dialect: string) that performs the apiVersion, schemes,
dialects and runtime checks (including using isBun to determine currentRuntime)
and throws the same errors; replace the inline validation (the if checks that
reference plugin.apiVersion, plugin.schemes, plugin.dialects, plugin.runtime)
with a single call validatePlugin(plugin, packageName, scheme, context.dialect)
before returning plugin.createAdapter(devUrl, context).
In `@packages/db/src/db/sqlite.ts`:
- Line 22: The rows mapping passes normalizeValue directly which can forward
extra arguments if its signature changes; update the inner map in the rows
assignment in sqlite.ts (the expression using (rows as unknown[][]).map((row) =>
row.map(...))) to call normalizeValue via an explicit single-argument wrapper
(e.g., row.map((val) => normalizeValue(val))) so only the cell value is passed
to normalizeValue.
In `@tests/pagila/pagila.test.ts`:
- Around line 65-70: The nested ternary assigning liveDb is hard to read;
replace it with a small helper or early-return if/else that branches on devUrl
to call neonTemporaryPlugin.createAdapter('neon-temporary', ...),
createPostgresDockerAdapter(devUrl), or pglitePlugin.createAdapter('pglite',
...). Locate the liveDb assignment and refactor into either a
getAdapterForDevUrl(devUrl) helper or explicit if (devUrl === 'neon-temporary')
/ else if (devUrl) / else blocks that call neonTemporaryPlugin.createAdapter,
createPostgresDockerAdapter, or pglitePlugin.createAdapter respectively to
improve readability and satisfy SonarCloud.
In `@tests/postgraphile-kitchensink/kitchen-sink.test.ts`:
- Around line 27-31: The nested ternary used to compute devUrl inside the
versions.forEach block reduces readability; replace it by extracting the logic
into a small helper or an explicit if/else before the describe call (e.g.,
implement a getDevUrl(version) function or set devUrl via if/else), and then use
that helper/variable in the describe block and for testTitle if needed; update
references to the devUrl variable (and testTitle if you choose to derive it
similarly) so the describe call reads clearly without nested ternaries.
🪄 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: CHILL
Plan: Pro
Run ID: 9211e5d3-c27c-495a-8ede-517321eb057b
📥 Commits
Reviewing files that changed from the base of the PR and between 1dc7a32 and 302a54d4a29726021461a30be49f586dc7d3ce45.
⛔ Files ignored due to path filters (2)
bun.lockis excluded by!**/*.lockpackages/db/wasm/atlas.wasmis excluded by!**/*.wasm
📒 Files selected for processing (41)
.envpackages/cli/src/commands/doctor.tspackages/cli/src/commands/schema.tspackages/cli/src/runtime.tspackages/cli/src/utils/pipeline.tspackages/db-mysql/package.jsonpackages/db-mysql/src/index.tspackages/db-neon-temporary/.gitignorepackages/db-neon-temporary/package.jsonpackages/db-neon-temporary/src/__tests__/neon-temporary.test.tspackages/db-neon-temporary/src/index.tspackages/db-neon/package.jsonpackages/db-neon/src/index.tspackages/db-pglite/package.jsonpackages/db-pglite/src/index.tspackages/db-postgres/package.jsonpackages/db-postgres/src/index.tspackages/db/package.jsonpackages/db/src/__tests__/extensions.test.tspackages/db/src/__tests__/pglite.test.tspackages/db/src/__tests__/runner.test.tspackages/db/src/db/mysql-docker.tspackages/db/src/db/mysql.tspackages/db/src/db/pglite.tspackages/db/src/db/plugin-resolver.tspackages/db/src/db/postgres-docker.tspackages/db/src/db/postgres.tspackages/db/src/db/sqlite.tspackages/db/src/db/types.tspackages/db/src/extensions.tspackages/db/src/index.tspackages/db/src/runner.tspackages/sqldoc/src/commands/add.tspackages/sqldoc/src/commands/init.tspackages/sqldoc/src/commands/upgrade.tspackages/sqldoc/src/runtime.tsscripts/build-binary.shsite/guide/connection-urls.mdtests/package.jsontests/pagila/pagila.test.tstests/postgraphile-kitchensink/kitchen-sink.test.ts
💤 Files with no reviewable changes (3)
- packages/db/src/db/pglite.ts
- packages/db/src/db/postgres.ts
- packages/db/src/db/mysql.ts
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/db/src/extensions.ts (1)
53-56:⚠️ Potential issue | 🟠 MajorEscape extension names before interpolating them into the validation query.
requestedis concatenated straight into a SQL ARRAY literal. A quoted extension name containing'will break the query, and a crafted name can splice extra SQL into the validation step. Please parameterise this query if you can, or at least escape embedded quotes before building the literal.🔧 Minimal fix
const result = await queryFn( 'SELECT name FROM pg_available_extensions WHERE name = ANY(ARRAY[' + - requested.map((e) => `'${e}'`).join(',') + + requested.map((e) => `'${e.replace(/'/g, "''")}'`).join(',') + '])', )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db/src/extensions.ts` around lines 53 - 56, The validation query builds a SQL ARRAY literal by interpolating requested directly (see the queryFn call using requested.map), which is vulnerable to SQL injection and breaks on embedded quotes; update the code to parameterize the query or at minimum escape single quotes in each extension name before joining (e.g., replace ' with ''), or better yet pass requested as a parameterized array to queryFn so the SELECT uses WHERE name = ANY($1::text[]) or equivalent; ensure you modify the code paths that compute the SQL string and the call to queryFn so the final query uses parameters (or safely-escaped names) and retains the same returned variable/result handling.
♻️ Duplicate comments (4)
packages/db-neon-temporary/src/index.ts (1)
110-115:⚠️ Potential issue | 🟠 MajorCheck the Neon details fetch before reading
connection_string.If this GET fails, the code falls through with
undefinedand the later URL helpers throw a much less useful error. GuarddataRes.okand validate that the field exists first.🔧 Minimal fix
log(`GET ${NEON_API}/${dbId}`) const dataRes = await fetch(`${NEON_API}/${dbId}`, { headers: { 'Content-Type': 'application/json' }, }) - const { connection_string } = (await dataRes.json()) as { connection_string: string } + if (!dataRes.ok) { + throw new Error(`Failed to fetch Neon database details: ${dataRes.status} ${dataRes.statusText}`) + } + const { connection_string } = (await dataRes.json()) as { connection_string?: string } + if (!connection_string) { + throw new Error('Neon API did not return a connection string') + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 110 - 115, Check the response from fetch(`${NEON_API}/${dbId}`) before reading connection_string: verify dataRes.ok and that the parsed JSON contains a non-empty connection_string; if the GET failed or the field is missing, log a clear error (including status and body) and throw an explicit error so callers don't receive undefined. Update the code around NEON_API/dbId where dataRes and connection_string are used (the fetch call and the destructuring) to perform these checks and fail fast with a helpful message.packages/cli/src/utils/pipeline.ts (1)
53-54:⚠️ Potential issue | 🟠 MajorResolve
.sqldocfromconfigRoot, not the caller’s CWD.
runCompilePipeline()already receives the target project root, but Line 118 ignores it. When the CLI is run from outside the project, the missing-plugin flow installs into the wrong.sqldocdirectory or never installs at all.🔧 Minimal fix
export async function runCompilePipeline( inputPath: string, config: ResolvedConfig, - _configRoot: string, + configRoot: string, ): Promise<PipelineResult> { @@ - const sqldocDir = findSqldocDir() ?? undefined + const sqldocDir = findSqldocDir(configRoot) ?? undefinedAlso applies to: 118-126
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/utils/pipeline.ts` around lines 53 - 54, runCompilePipeline currently ignores the passed-in project root (_configRoot) and resolves the .sqldoc path from the caller's CWD, causing missing-plugin installs to target the wrong directory; update the code in runCompilePipeline to derive the .sqldoc directory from _configRoot (e.g., use path.join(_configRoot, '.sqldoc') or path.resolve(_configRoot, '.sqldoc')) instead of process.cwd() or path.resolve('.') and apply the same change to the missing-plugin installation flow where the .sqldoc path is computed so all references use _configRoot as the base.packages/db/src/db/sqlite.ts (1)
45-50:⚠️ Potential issue | 🟡 MinorKeep empty-result column metadata consistent across runtimes.
The Node path returns
columns: []on zero rows, while the Bun path still reports the selected columns. That makesQueryResultbehaviour depend on runtime for the same query.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db/src/db/sqlite.ts` around lines 45 - 50, The query method in packages/db/src/db/sqlite.ts returns columns: [] when rows.length === 0, causing runtime-dependent QueryResult; instead, retrieve column metadata from the prepared statement before returning empty rows. Modify query (the async query(sql: string, args?: SQLInputValue[])) to call the prepared statement's column/columns metadata API (e.g., stmt.columns() or equivalent on stmt) to build the columns array and return { columns: <those columns>, rows: [] } when no rows are returned so QueryResult consistently includes selected column info across runtimes.site/guide/connection-urls.md (1)
44-44:⚠️ Potential issue | 🟡 MinorThe
neon-temporarycache duration is out of sync with the implementation.These three mentions still say 24 hours, but the adapter itself documents 72 hours and sets
MAX_AGE_MS = 72 * 60 * 60 * 1000. Please make the guide and implementation agree. (raw.githubusercontent.com)📝 Proposed doc update
-| `neon-temporary` | `@sqldoc/db-neon-temporary` | postgres | Creates a temporary Neon database automatically. No URL or API key needed. Reuses the same database for 24 hours. Safe for parallel development (advisory lock). | +| `neon-temporary` | `@sqldoc/db-neon-temporary` | postgres | Creates a temporary Neon database automatically. No URL or API key needed. Reuses the same database for 72 hours. Safe for parallel development (advisory lock). | @@ -Creates a temporary Neon PostgreSQL database automatically -- no URL, API key, or account needed. The database is created via [neon-new](https://github.com/neondatabase/neon-pkgs/tree/main/packages/neon-new) on first use and reused for 24 hours (cached in `.sqldoc/neon-temporary.json`). +Creates a temporary Neon PostgreSQL database automatically -- no URL, API key, or account needed. The database is created via [neon-new](https://github.com/neondatabase/neon-pkgs/tree/main/packages/neon-new) on first use and reused for 72 hours (cached in `.sqldoc/neon-temporary.json`). @@ -1. Loads or creates the database (cached for 24h) +1. Loads or creates the database (cached for 72h)Also applies to: 99-99, 109-109
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@site/guide/connection-urls.md` at line 44, Update the documentation references for the neon-temporary cache duration to match the adapter implementation: replace any mention of "24 hours" with "72 hours" (or "MAX_AGE_MS = 72 * 60 * 60 * 1000") so the guide text describing `neon-temporary` aligns with the adapter's `MAX_AGE_MS` constant and its behaviour; ensure all occurrences (including the three mentions flagged) are updated to 72 hours.
🧹 Nitpick comments (1)
packages/cli/src/commands/doctor.ts (1)
114-130: Remove the commented-out pglite check.This is dead code now. Either bring it back behind a real flag or delete it so
doctorstays readable.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/doctor.ts` around lines 114 - 130, Remove the dead commented-out pglite check block: delete the commented code that declares pgliteOk and pgliteDetail, the try/catch that imports '@sqldoc/db-pglite' and calls createAdapter/query/close, and the results.push that references the pglite check so doctor.ts no longer contains this unused commented section; if you intend to reintroduce it later, reimplement it behind a real feature flag or config check rather than leaving it commented.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/db-neon-temporary/src/index.ts`:
- Around line 154-198: The adapter initialization leaks the Neon session if an
exception occurs after await client.connect() (before returning adapter); wrap
the lock/wipe sequence (the SET lock_timeout, SELECT pg_advisory_lock, schema
DROP/CREATE steps) in a try/finally (or try/catch then rethrow) so that on any
failure you call the same cleanup used in adapter.close(): execute SELECT
pg_advisory_unlock(LOCK_KEY) (catching errors) and await client.end() to ensure
the session and advisory lock are released, then rethrow the original error;
reference the Client instance (client), the adapter.close() cleanup behavior
(SELECT pg_advisory_unlock and client.end), and the LOCK_KEY and adapter.exec
calls to locate where to add the try/finally.
- Around line 191-193: The DROP SCHEMA statement interpolates raw schema names
from schemas.rows into adapter.exec (loop over schemas.rows using the variable
name), which allows a schema containing quotes or SQL to break or inject code;
fix by escaping/quoting the identifier before executing: sanitize name by
doubling any internal double quotes (replace " with "") and wrap the result in
double quotes (or use the adapter's identifier-quoting helper if available) so
the adapter.exec call executes DROP SCHEMA "safe_name" CASCADE with a properly
escaped identifier.
- Around line 82-92: The current toPooler and toDirect split the entire
connection string on '.' which corrupts URLs containing dots in
username/password/query; instead parse the connection string as a URL (use the
URL constructor) in both toPooler and toDirect, modify only url.hostname by
appending or removing the '-pooler' suffix, and then return url.toString() (or
url.href) so userinfo, path, query and port are preserved; ensure you keep the
existing early-return checks (connString.includes('pooler') / !includes) but
replace them with hostname checks via the parsed URL's hostname to avoid false
positives in credentials or query strings.
In `@packages/db-pglite/src/index.ts`:
- Around line 5-14: The loadExtension function and wherever extensions are
stored should normalize hyphenated SQL names to PGlite module identifiers by
replacing '-' with '_' before doing dynamic imports and object key
lookups/stores; in particular, inside loadExtension(name: string) create a
normalizedName = name.replace(/-/g, '_') and use that for the import paths
(e.g., `@electric-sql/pglite/contrib/${normalizedName}` and
`@electric-sql/pglite/${normalizedName}`) and when accessing mod.default or
mod[normalizedName], and ensure any extModules map is keyed by the
normalizedName so supported extensions like uuid-ossp resolve to uuid_ossp.
In `@packages/db/src/db/plugin-resolver.ts`:
- Around line 110-115: The current early return from builtinPlugins.get(scheme)
bypasses the standard validation (apiVersion, schemes, dialects, runtime) and
can produce wrong adapters; instead, after retrieving builtin via
builtinPlugins.get(scheme) do not return immediately—run it through the same
validation path used for external plugins (the
apiVersion/schemes/dialects/runtime checks) and only call
builtin.createAdapter(devUrl, context) after those checks pass; update
plugin-resolver.ts to apply the same validation logic to the builtin entry so it
fails fast and consistently with external plugins.
- Around line 174-190: tryImportPlugin currently swallows all errors in the
createRequire/req.resolve and dynamic import blocks, causing real
module-evaluation errors to be treated as "missing"; change each empty catch to
inspect the caught error (from req.resolve and from import(resolved)) and only
swallow/continue when the error indicates the module cannot be found (e.g.
err.code === 'MODULE_NOT_FOUND' || err.code === 'ERR_MODULE_NOT_FOUND' or
message includes "Cannot find module"); for any other errors (module
evaluation/runtime errors) rethrow the error so callers see the real failure;
update both try/catch sites that use createRequire, req.resolve and
import(resolved) (and keep behavior for the import.meta.url and process.cwd()
bases) so non-missing errors are propagated.
- Around line 11-12: The fallback package lookup uses new
URL(import.meta.url).pathname which is not cross-platform; import fileURLToPath
from 'node:url' and replace usages of new URL(import.meta.url).pathname with
fileURLToPath(import.meta.url) so Windows drive letters and percent-encoded
characters are handled correctly; update the import list and change the path
calculation used by the fallback lookup (the code that uses createRequire and
path to resolve the package and ultimately affects getOwnVersion()) to use
fileURLToPath(import.meta.url) instead.
In `@packages/db/src/index.ts`:
- Around line 119-126: The extension validation can throw before ownership of
the DB adapter is transferred to createAtlasRunner(), so wrap the
validatePostgresExtensions(...) call in a try/catch, and on any catch call
db.close() (or db.close?.() if optional) to ensure open connections are closed,
then rethrow the error; keep the existing flow so createAtlasRunner({ wasmPath,
db, dialect }) is only called on success. Reference validatePostgresExtensions,
db, and createAtlasRunner when making this change.
- Around line 98-116: The Docker adapter paths don't forward plugin options so
createMysqlDockerAdapter and createPostgresDockerAdapter must accept the same
plugin options and pass them into resolveAdapterPlugin; update their signatures
to createMysqlDockerAdapter(devUrl: string, pluginOpts) and
createPostgresDockerAdapter(devUrl: string, pluginOpts) and ensure the call to
resolveAdapterPlugin inside each function includes {...pluginOpts, devUrl} (so
sqldocDir and onMissingPlugin are forwarded), and update any call sites in this
file where those functions are invoked to pass pluginOpts.
---
Outside diff comments:
In `@packages/db/src/extensions.ts`:
- Around line 53-56: The validation query builds a SQL ARRAY literal by
interpolating requested directly (see the queryFn call using requested.map),
which is vulnerable to SQL injection and breaks on embedded quotes; update the
code to parameterize the query or at minimum escape single quotes in each
extension name before joining (e.g., replace ' with ''), or better yet pass
requested as a parameterized array to queryFn so the SELECT uses WHERE name =
ANY($1::text[]) or equivalent; ensure you modify the code paths that compute the
SQL string and the call to queryFn so the final query uses parameters (or
safely-escaped names) and retains the same returned variable/result handling.
---
Duplicate comments:
In `@packages/cli/src/utils/pipeline.ts`:
- Around line 53-54: runCompilePipeline currently ignores the passed-in project
root (_configRoot) and resolves the .sqldoc path from the caller's CWD, causing
missing-plugin installs to target the wrong directory; update the code in
runCompilePipeline to derive the .sqldoc directory from _configRoot (e.g., use
path.join(_configRoot, '.sqldoc') or path.resolve(_configRoot, '.sqldoc'))
instead of process.cwd() or path.resolve('.') and apply the same change to the
missing-plugin installation flow where the .sqldoc path is computed so all
references use _configRoot as the base.
In `@packages/db-neon-temporary/src/index.ts`:
- Around line 110-115: Check the response from fetch(`${NEON_API}/${dbId}`)
before reading connection_string: verify dataRes.ok and that the parsed JSON
contains a non-empty connection_string; if the GET failed or the field is
missing, log a clear error (including status and body) and throw an explicit
error so callers don't receive undefined. Update the code around NEON_API/dbId
where dataRes and connection_string are used (the fetch call and the
destructuring) to perform these checks and fail fast with a helpful message.
In `@packages/db/src/db/sqlite.ts`:
- Around line 45-50: The query method in packages/db/src/db/sqlite.ts returns
columns: [] when rows.length === 0, causing runtime-dependent QueryResult;
instead, retrieve column metadata from the prepared statement before returning
empty rows. Modify query (the async query(sql: string, args?: SQLInputValue[]))
to call the prepared statement's column/columns metadata API (e.g.,
stmt.columns() or equivalent on stmt) to build the columns array and return {
columns: <those columns>, rows: [] } when no rows are returned so QueryResult
consistently includes selected column info across runtimes.
In `@site/guide/connection-urls.md`:
- Line 44: Update the documentation references for the neon-temporary cache
duration to match the adapter implementation: replace any mention of "24 hours"
with "72 hours" (or "MAX_AGE_MS = 72 * 60 * 60 * 1000") so the guide text
describing `neon-temporary` aligns with the adapter's `MAX_AGE_MS` constant and
its behaviour; ensure all occurrences (including the three mentions flagged) are
updated to 72 hours.
---
Nitpick comments:
In `@packages/cli/src/commands/doctor.ts`:
- Around line 114-130: Remove the dead commented-out pglite check block: delete
the commented code that declares pgliteOk and pgliteDetail, the try/catch that
imports '@sqldoc/db-pglite' and calls createAdapter/query/close, and the
results.push that references the pglite check so doctor.ts no longer contains
this unused commented section; if you intend to reintroduce it later,
reimplement it behind a real feature flag or config check rather than leaving it
commented.
🪄 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: CHILL
Plan: Pro
Run ID: af06e5e1-0eab-414e-a817-6f021a887c6c
📥 Commits
Reviewing files that changed from the base of the PR and between 302a54d4a29726021461a30be49f586dc7d3ce45 and 63fe06a5dcb440e8db1b7efd8160324978d3e419.
⛔ Files ignored due to path filters (2)
bun.lockis excluded by!**/*.lockpackages/db/wasm/atlas.wasmis excluded by!**/*.wasm
📒 Files selected for processing (41)
packages/cli/src/commands/doctor.tspackages/cli/src/commands/schema.tspackages/cli/src/runtime.tspackages/cli/src/utils/pipeline.tspackages/db-mysql/package.jsonpackages/db-mysql/src/index.tspackages/db-neon-temporary/.gitignorepackages/db-neon-temporary/package.jsonpackages/db-neon-temporary/src/__tests__/neon-temporary.test.tspackages/db-neon-temporary/src/index.tspackages/db-neon/package.jsonpackages/db-neon/src/index.tspackages/db-pglite/package.jsonpackages/db-pglite/src/index.tspackages/db-postgres/package.jsonpackages/db-postgres/src/index.tspackages/db/package.jsonpackages/db/src/__tests__/extensions.test.tspackages/db/src/__tests__/pglite.test.tspackages/db/src/__tests__/runner.test.tspackages/db/src/db/mysql-docker.tspackages/db/src/db/mysql.tspackages/db/src/db/pglite.tspackages/db/src/db/plugin-resolver.tspackages/db/src/db/postgres-docker.tspackages/db/src/db/postgres.tspackages/db/src/db/sqlite.tspackages/db/src/db/types.tspackages/db/src/extensions.tspackages/db/src/index.tspackages/db/src/runner.tspackages/ns-validate/src/index.tspackages/sqldoc/src/commands/add.tspackages/sqldoc/src/commands/init.tspackages/sqldoc/src/commands/upgrade.tspackages/sqldoc/src/runtime.tsscripts/build-binary.shsite/guide/connection-urls.mdtests/package.jsontests/pagila/pagila.test.tstests/postgraphile-kitchensink/kitchen-sink.test.ts
💤 Files with no reviewable changes (3)
- packages/db/src/db/mysql.ts
- packages/db/src/db/postgres.ts
- packages/db/src/db/pglite.ts
✅ Files skipped from review due to trivial changes (12)
- packages/db-neon-temporary/.gitignore
- tests/package.json
- scripts/build-binary.sh
- packages/db/src/tests/runner.test.ts
- packages/sqldoc/src/commands/add.ts
- packages/db/src/tests/pglite.test.ts
- packages/db-pglite/package.json
- packages/db-neon/package.json
- packages/db-postgres/package.json
- packages/db-mysql/package.json
- packages/db-neon-temporary/package.json
- packages/db-neon/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (12)
- packages/cli/src/commands/schema.ts
- packages/sqldoc/src/commands/upgrade.ts
- packages/db/src/runner.ts
- packages/db/src/db/postgres-docker.ts
- packages/db/package.json
- packages/cli/src/runtime.ts
- packages/sqldoc/src/runtime.ts
- packages/db/src/db/mysql-docker.ts
- packages/db-neon-temporary/src/tests/neon-temporary.test.ts
- packages/db/src/db/types.ts
- packages/db-postgres/src/index.ts
- packages/sqldoc/src/commands/init.ts
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (4)
packages/db-neon-temporary/src/index.ts (4)
82-92:⚠️ Potential issue | 🟠 MajorRewrite the hostname, not the whole connection string.
Splitting the full URL on
.corrupts valid URLs when the username, password, or query string contains dots. This can produce broken direct/pooler URLs from Neon'sconnection_string.🔧 Safer host rewrite using URL parsing
function toPooler(connString: string): string { - if (connString.includes('pooler')) return connString - const [start, ...end] = connString.split('.') - return `${start}-pooler.${end.join('.')}` + const url = new URL(connString) + if (url.hostname.includes('-pooler.')) return connString + url.hostname = url.hostname.replace(/^([^.]+)/, '$1-pooler') + return url.toString() } function toDirect(connString: string): string { - if (!connString.includes('pooler')) return connString - const [first, ...rest] = connString.split('.') - return [first.replace('-pooler', ''), ...rest].join('.') + const url = new URL(connString) + if (!url.hostname.includes('-pooler.')) return connString + url.hostname = url.hostname.replace('-pooler', '') + return url.toString() }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 82 - 92, The current toPooler and toDirect functions split the entire connection string on dots and corrupt parts that contain dots; instead parse the connection string with the URL API (new URL(connString)), update only the hostname (URL.hostname) to add or remove the "-pooler" suffix, and return url.toString() so username, password, port, path, and query remain intact; update functions to handle thrown URL parsing errors by falling back to the original connString or rethrow as appropriate and reference the toPooler and toDirect functions when making the change.
110-114:⚠️ Potential issue | 🟡 MinorAdd error handling for the database status fetch.
The second fetch to retrieve the connection string (line 111) doesn't check for failure. If this request fails,
connection_stringcould be undefined, leading to errors intoDirect/toPooler.🛡️ Proposed fix
log(`GET ${NEON_API}/${dbId}`) const dataRes = await fetch(`${NEON_API}/${dbId}`, { headers: { 'Content-Type': 'application/json' }, }) + if (!dataRes.ok) { + throw new Error(`Failed to fetch Neon database details: ${dataRes.status} ${dataRes.statusText}`) + } const { connection_string } = (await dataRes.json()) as { connection_string: string } + if (!connection_string) { + throw new Error('Neon API did not return a connection string') + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 110 - 114, The fetch that retrieves the connection string using the variable dataRes needs proper error handling: after awaiting fetch(`${NEON_API}/${dbId}`) check dataRes.ok (or the status) and handle non-2xx responses by logging or throwing a clear error before attempting to read json(); ensure the parsed payload contains a defined connection_string and throw/log a descriptive error if it's missing so callers like toDirect/toPooler don't receive undefined. Update the code around the dataRes fetch and the extraction of connection_string to validate response.ok and the presence of connection_string, then fail fast with context if invalid.
193-196:⚠️ Potential issue | 🟠 MajorEscape schema names before interpolating them into
DROP SCHEMA.
schema_namecomes from the database. A valid schema containing"will break this statement, and a crafted name can inject extra SQL into the wipe step. Quote the identifier properly before executing.🔧 Minimal fix
for (const row of schemas.rows) { const name = row[0] as string - await adapter.exec(`DROP SCHEMA "${name}" CASCADE`) + const escapedName = name.replace(/"/g, '""') + await adapter.exec(`DROP SCHEMA "${escapedName}" CASCADE`) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 193 - 196, The loop over schemas.rows builds a DROP SCHEMA SQL string with the raw name variable and risks SQL injection when a schema contains quotes; update the code that iterates rows (the for (const row of schemas.rows) { const name = row[0] as string ... await adapter.exec(`DROP SCHEMA "${name}" CASCADE`) }) to properly escape the identifier before interpolation—either call an existing identifier-escaping helper on name (e.g., escapeIdentifier(name)) or replace any double-quote characters by doubling them per SQL rules and then interpolate the escaped value into adapter.exec so DROP SCHEMA is executed with a safely quoted identifier.
151-201:⚠️ Potential issue | 🔴 CriticalClose the Neon session when adapter initialisation fails.
Any exception thrown after
await client.connect()(line 158) but beforereturn adapter(line 200) leaks the session. If it happens after line 186, the advisory lock stays held until process exit. Wrap the lock/wipe phase intry/catchand always unlock/end on failure.🛡️ Proposed fix with try/finally
const client = new Client(directUrl) await client.connect() + let lockAcquired = false + try { const adapter: DatabaseAdapter = { // ... adapter methods unchanged ... } log('acquiring advisory lock...') await adapter.exec(`SET lock_timeout = '${plugin.lockTimeoutMs}ms'`) await adapter.exec(`SELECT pg_advisory_lock(${LOCK_KEY})`) + lockAcquired = true log('lock acquired, wiping schemas...') // ... schema wipe logic ... return adapter + } catch (err) { + if (lockAcquired) { + try { + await client.query(`SELECT pg_advisory_unlock(${LOCK_KEY})`) + } catch { /* ignore */ } + } + await client.end() + throw err + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 151 - 201, createAdapter currently connects the Client but if any error occurs between await client.connect() and return adapter the Neon session (and advisory lock if taken) can leak; fix by wrapping the lock/wipe phase in a try/finally (or try/catch then rethrow) that ensures any acquired advisory lock is released and client.end() is called on failure. Specifically, in createAdapter after client.connect() introduce a boolean like lockAcquired = false; set it true after the SELECT pg_advisory_lock(...) succeeds (or after adapter.exec that acquires the lock), and in the finally block call adapter.exec(`SELECT pg_advisory_unlock(${LOCK_KEY})`) only if lockAcquired, then await client.end(); rethrow the original error so callers still see the failure. Ensure any early returns are avoided so the cleanup always runs before throwing.
🧹 Nitpick comments (2)
packages/cli/src/commands/doctor.ts (2)
70-76: Same nested ternary pattern as above.This mirrors the previous block. If you refactor one, consider refactoring both for consistency.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/doctor.ts` around lines 70 - 76, The nested ternary used to compute the detail value (referencing sqldocDir, hasNodeModules, hasCliInstalled) should be refactored to match the earlier refactor: replace the nested ternary with a small helper or explicit if/else that returns the same three possible strings ('No .sqldoc/ directory', 'node_modules/ missing. Run install in .sqldoc/', or '@sqldoc/cli not found in node_modules/') or undefined when all checks pass; update the code that sets detail to call that helper (or use the if/else) so this block mirrors the earlier clearer implementation and improves readability and maintainability.
48-54: Consider extracting nested ternary for readability.The triple-nested ternary is functional but reduces readability. SonarCloud flags this pattern. A helper function or early-return logic would be clearer, though this is a minor stylistic concern in a diagnostic command.
♻️ Optional refactor using a helper function
+function getCliDepDetail(sqldocDir: string | null, hasPkgJson: boolean, hasCliDep: boolean): string | undefined { + if (!sqldocDir) return 'No .sqldoc/ directory' + if (!hasPkgJson) return 'No package.json in .sqldoc/' + if (!hasCliDep) return '@sqldoc/cli not listed in dependencies' + return undefined +} + results.push({ label: 'package.json has `@sqldoc/cli` dependency', ok: hasCliDep, - detail: sqldocDir - ? hasPkgJson - ? hasCliDep - ? undefined - : '@sqldoc/cli not listed in dependencies' - : 'No package.json in .sqldoc/' - : 'No .sqldoc/ directory', + detail: getCliDepDetail(sqldocDir, hasPkgJson, hasCliDep), })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/doctor.ts` around lines 48 - 54, Extract the nested ternary into a small helper (e.g., formatSqldocDetail or getSqldocDetail) that accepts the three booleans/values (sqldocDir, hasPkgJson, hasCliDep) and returns the string detail; replace the inline triple-nested ternary used to set detail with a call to that helper, implementing clear early-return or if/else branches inside the helper for readability and to satisfy SonarCloud.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/db-neon-temporary/src/index.ts`:
- Around line 36-41: The CachedDb shape and loadCache need defensive validation:
in loadCache (and any code that reads the cache), wrap JSON.parse in try/catch,
verify required fields (directUrl, poolerUrl, claimUrl, createdAt) are present
and of correct types, and validate createdAt by using Date.parse or new
Date(...).getTime() and explicitly checking for NaN; if any check fails return
null (or discard the cache) instead of trusting the data. Update the code
referencing the CachedDb interface to treat parsed data as unknown before
asserting its type and ensure age calculation uses a validated numeric timestamp
so NaN cannot bypass expiry logic.
---
Duplicate comments:
In `@packages/db-neon-temporary/src/index.ts`:
- Around line 82-92: The current toPooler and toDirect functions split the
entire connection string on dots and corrupt parts that contain dots; instead
parse the connection string with the URL API (new URL(connString)), update only
the hostname (URL.hostname) to add or remove the "-pooler" suffix, and return
url.toString() so username, password, port, path, and query remain intact;
update functions to handle thrown URL parsing errors by falling back to the
original connString or rethrow as appropriate and reference the toPooler and
toDirect functions when making the change.
- Around line 110-114: The fetch that retrieves the connection string using the
variable dataRes needs proper error handling: after awaiting
fetch(`${NEON_API}/${dbId}`) check dataRes.ok (or the status) and handle non-2xx
responses by logging or throwing a clear error before attempting to read json();
ensure the parsed payload contains a defined connection_string and throw/log a
descriptive error if it's missing so callers like toDirect/toPooler don't
receive undefined. Update the code around the dataRes fetch and the extraction
of connection_string to validate response.ok and the presence of
connection_string, then fail fast with context if invalid.
- Around line 193-196: The loop over schemas.rows builds a DROP SCHEMA SQL
string with the raw name variable and risks SQL injection when a schema contains
quotes; update the code that iterates rows (the for (const row of schemas.rows)
{ const name = row[0] as string ... await adapter.exec(`DROP SCHEMA "${name}"
CASCADE`) }) to properly escape the identifier before interpolation—either call
an existing identifier-escaping helper on name (e.g., escapeIdentifier(name)) or
replace any double-quote characters by doubling them per SQL rules and then
interpolate the escaped value into adapter.exec so DROP SCHEMA is executed with
a safely quoted identifier.
- Around line 151-201: createAdapter currently connects the Client but if any
error occurs between await client.connect() and return adapter the Neon session
(and advisory lock if taken) can leak; fix by wrapping the lock/wipe phase in a
try/finally (or try/catch then rethrow) that ensures any acquired advisory lock
is released and client.end() is called on failure. Specifically, in
createAdapter after client.connect() introduce a boolean like lockAcquired =
false; set it true after the SELECT pg_advisory_lock(...) succeeds (or after
adapter.exec that acquires the lock), and in the finally block call
adapter.exec(`SELECT pg_advisory_unlock(${LOCK_KEY})`) only if lockAcquired,
then await client.end(); rethrow the original error so callers still see the
failure. Ensure any early returns are avoided so the cleanup always runs before
throwing.
---
Nitpick comments:
In `@packages/cli/src/commands/doctor.ts`:
- Around line 70-76: The nested ternary used to compute the detail value
(referencing sqldocDir, hasNodeModules, hasCliInstalled) should be refactored to
match the earlier refactor: replace the nested ternary with a small helper or
explicit if/else that returns the same three possible strings ('No .sqldoc/
directory', 'node_modules/ missing. Run install in .sqldoc/', or '@sqldoc/cli
not found in node_modules/') or undefined when all checks pass; update the code
that sets detail to call that helper (or use the if/else) so this block mirrors
the earlier clearer implementation and improves readability and maintainability.
- Around line 48-54: Extract the nested ternary into a small helper (e.g.,
formatSqldocDetail or getSqldocDetail) that accepts the three booleans/values
(sqldocDir, hasPkgJson, hasCliDep) and returns the string detail; replace the
inline triple-nested ternary used to set detail with a call to that helper,
implementing clear early-return or if/else branches inside the helper for
readability and to satisfy SonarCloud.
🪄 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: CHILL
Plan: Pro
Run ID: 32de650c-3d19-475b-aee9-365e246cdfdb
📥 Commits
Reviewing files that changed from the base of the PR and between 63fe06a5dcb440e8db1b7efd8160324978d3e419 and f1af1c40f3bbdb5e78e3aef6f15095cb11cdb134.
📒 Files selected for processing (3)
.vscode/settings.jsonpackages/cli/src/commands/doctor.tspackages/db-neon-temporary/src/index.ts
✅ Files skipped from review due to trivial changes (1)
- .vscode/settings.json
pass opts through docker adapter so the driver install can happen if not there
f1af1c4 to
cd8b59f
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
♻️ Duplicate comments (3)
site/guide/connection-urls.md (1)
108-110:⚠️ Potential issue | 🟡 MinorKeep the
neon-temporarycache TTL consistent on this page.Lines 44 and 99 say 72 hours, but Line 109 still says 24h. That leaves readers with two different lifecycle guarantees for the same adapter.
📝 Suggested fix
-1. Loads or creates the database (cached for 24h) +1. Loads or creates the database (cached for 72h)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@site/guide/connection-urls.md` around lines 108 - 110, The page mentions the neon-temporary cache TTL inconsistently (some places say "72 hours" while the "On each run, sqldoc:" list uses "24h"); update the string for the neon-temporary cache TTL so all occurrences use the same wording and value (e.g., replace "24h" with "72 hours" or vice versa) and normalize formatting (use either "72 hours" or "72h") so every reference to neon-temporary TTL, including the list under "On each run, sqldoc:", is identical.packages/db-neon-temporary/src/index.ts (2)
129-133:⚠️ Potential issue | 🟡 MinorAdd error handling for the database status fetch.
The fetch response at line 130 isn't checked for success before parsing. If this request fails,
connection_stringcould be undefined, causing errors intoDirect/toPooler.🛡️ Proposed fix
log(`GET ${NEON_API}/${dbId}`) const dataRes = await fetch(`${NEON_API}/${dbId}`, { headers: { 'Content-Type': 'application/json' }, }) + if (!dataRes.ok) { + throw new Error(`Failed to fetch Neon database details: ${dataRes.status} ${dataRes.statusText}`) + } const { connection_string } = (await dataRes.json()) as { connection_string: string } + if (!connection_string) { + throw new Error('Neon API did not return a connection string') + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 129 - 133, The fetch to NEON_API for dbId does not check response status before parsing; update the code around the fetch (the call that assigns dataRes and extracts connection_string) to verify dataRes.ok (and handle non-2xx by throwing or logging the status/text), then validate that the parsed payload contains a non-empty connection_string before calling toDirect/toPooler; reference NEON_API, dbId, dataRes, connection_string, and the downstream toDirect/toPooler so you ensure you fail fast with a clear error or fallback when the fetch or payload is invalid.
210-217:⚠️ Potential issue | 🟡 MinorEscape schema names before interpolating into SQL.
Schema names from
information_schema.schemataare interpolated directly into theDROP SCHEMAstatement. While unlikely in practice, a schema name containing"would break the query. This was flagged in a previous review but the escaping wasn't applied.🛡️ Proposed fix
for (const row of schemas.rows) { const name = row[0] as string - await adapter.exec(`DROP SCHEMA "${name}" CASCADE`) + const escapedName = name.replace(/"/g, '""') + await adapter.exec(`DROP SCHEMA "${escapedName}" CASCADE`) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db-neon-temporary/src/index.ts` around lines 210 - 217, The DROP SCHEMA interpolation can break if a schema name contains a double-quote; in the loop that uses adapter.query and adapter.exec (the variables schemas and name), escape identifier quotes before injecting into the SQL by replacing any " characters with "" (SQL identifier escaping) or otherwise constructing a safely quoted identifier, then use that escaped identifier in the adapter.exec(`DROP SCHEMA "${escapedName}" CASCADE`) call; keep the rest of the logic (querying information_schema.schemata and recreating public) unchanged.
🧹 Nitpick comments (5)
packages/cli/src/commands/doctor.ts (1)
48-54: Refactor nested ternaries into explicit branches.These two
detailexpressions are correct but difficult to read/maintain and are likely to keep tripping static analysis.♻️ Suggested refactor
+ let cliDepDetail: string | undefined + if (!sqldocDir) { + cliDepDetail = 'No .sqldoc/ directory' + } else if (!hasPkgJson) { + cliDepDetail = 'No package.json in .sqldoc/' + } else if (!hasCliDep) { + cliDepDetail = '@sqldoc/cli not listed in dependencies' + } results.push({ label: 'package.json has `@sqldoc/cli` dependency', ok: hasCliDep, - detail: sqldocDir - ? hasPkgJson - ? hasCliDep - ? undefined - : '@sqldoc/cli not listed in dependencies' - : 'No package.json in .sqldoc/' - : 'No .sqldoc/ directory', + detail: cliDepDetail, }) @@ + let cliInstallDetail: string | undefined + if (!sqldocDir) { + cliInstallDetail = 'No .sqldoc/ directory' + } else if (!hasNodeModules) { + cliInstallDetail = 'node_modules/ missing. Run install in .sqldoc/' + } else if (!hasCliInstalled) { + cliInstallDetail = '@sqldoc/cli not found in node_modules/' + } results.push({ label: 'node_modules/ has `@sqldoc/cli` installed', ok: hasCliInstalled, - detail: sqldocDir - ? hasNodeModules - ? hasCliInstalled - ? undefined - : '@sqldoc/cli not found in node_modules/' - : 'node_modules/ missing. Run install in .sqldoc/' - : 'No .sqldoc/ directory', + detail: cliInstallDetail, })Also applies to: 70-76
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/doctor.ts` around lines 48 - 54, The nested ternary used to compute the detail value (using sqldocDir, hasPkgJson, hasCliDep) is hard to read; replace it with an explicit branch or helper function (e.g., a getDetailMessage or computeDetail) that returns the three possible strings ('No .sqldoc/ directory', 'No package.json in .sqldoc/', '@sqldoc/cli not listed in dependencies' or undefined) based on the same boolean inputs; do the same replacement for the other occurrence that uses the same three boolean variables so both places call the shared helper or use clear if/else logic for maintainability and to satisfy static analysis.packages/db/src/db/plugin-resolver.ts (1)
75-79: Consider usingRegExp.exec()for slight performance improvement.SonarCloud suggests using
RegExp.exec()instead ofString.match()when you only need the first match.♻️ Optional refactor
export function extractScheme(devUrl: string): string { - const match = devUrl.match(/^([a-z][a-z0-9_-]*):\/\//) + const match = /^([a-z][a-z0-9_-]*):\/\//.exec(devUrl) return match ? match[1] : devUrl }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/db/src/db/plugin-resolver.ts` around lines 75 - 79, The extractScheme function uses String.match to capture the first regex group; replace that with a precompiled RegExp and call its exec method to get the first capture for a small performance improvement — i.e., in extractScheme(devUrl: string) create a const re = /^([a-z][a-z0-9_-]*):\/\// and use re.exec(devUrl) to read the scheme from the returned array (or fall back to devUrl) instead of devUrl.match(...).tests/pagila/pagila.test.ts (2)
66-71: Consider extracting adapter creation logic.This three-way dispatch nested ternary is harder to follow. A helper function would clarify the intent:
♻️ Optional refactor
+async function createLiveAdapter(devUrl: string | undefined) { + if (devUrl === 'neon-temporary') { + return neonTemporaryPlugin.createAdapter('neon-temporary', { dialect: 'postgres', extensions: [] }) + } + if (devUrl) { + return createPostgresDockerAdapter(devUrl) + } + return pglitePlugin.createAdapter('pglite', { dialect: 'postgres', extensions: [] }) +} + it(`${testTitle}: live DB diff against original SQL produces zero changes`, async () => { - const liveDb = - devUrl === 'neon-temporary' - ? await neonTemporaryPlugin.createAdapter('neon-temporary', { dialect: 'postgres', extensions: [] }) - : devUrl - ? await createPostgresDockerAdapter(devUrl) - : await pglitePlugin.createAdapter('pglite', { dialect: 'postgres', extensions: [] }) + const liveDb = await createLiveAdapter(devUrl)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/pagila/pagila.test.ts` around lines 66 - 71, Extract the three-way adapter selection into a small helper function (e.g., getTestDbAdapter or resolveAdapter) to replace the nested ternary used to set liveDb; move the logic that checks devUrl === 'neon-temporary', calls neonTemporaryPlugin.createAdapter('neon-temporary', ...), calls createPostgresDockerAdapter(devUrl), or calls pglitePlugin.createAdapter('pglite', ...) into that function, return the adapter, and then call it from the test to assign liveDb, which will make the intent clearer and simplify the test setup.
27-27: Consider extracting nested ternary for clarity.SonarCloud flagged this nested ternary. While functional, extracting to a helper would improve readability:
♻️ Optional refactor
+function getDevUrl(version: string | undefined): string | undefined { + if (version === 'neon-temporary') return 'neon-temporary' + if (version) return `docker://${version}` + return undefined +} + versions.forEach((version) => { describe(`pagila schema - ${version ?? 'pglite'}`, { timeout: 120_000 }, () => { - const devUrl = version === 'neon-temporary' ? 'neon-temporary' : version ? `docker://${version}` : undefined + const devUrl = getDevUrl(version)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/pagila/pagila.test.ts` at line 27, The nested ternary used to compute devUrl in tests/pagila/pagila.test.ts is hard to read; extract it into a small helper (e.g., getDevUrl(version) or buildDevUrl) that returns 'neon-temporary' when version === 'neon-temporary', returns `docker://${version}` when version is truthy, and returns undefined otherwise, then replace the inline expression assigning devUrl with a call to that helper to improve readability and satisfy the SonarCloud suggestion.tests/postgraphile-kitchensink/kitchen-sink.test.ts (1)
28-30: Consider extracting nested ternary for consistency.Same suggestion as in
pagila.test.ts- a helper function would improve readability.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/postgraphile-kitchensink/kitchen-sink.test.ts` around lines 28 - 30, The nested ternary used to compute timeout and devUrl reduces readability; extract the logic into a small helper (e.g., getDevUrl/versionToDevUrl or computeTimeoutAndDevUrl) and call it from the test setup so that the const timeout and const devUrl assignments are a single clear call; update references to version, timeout, and devUrl in the describe block to use the helper's returned values to mirror the refactor done in pagila.test.ts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/compiler/compile.ts`:
- Around line 166-182: The missing-namespace detection used in the block loop
(using missingNamespaces, plugins, errors and checking tag.namespace) is only in
compileTier1; replicate the same logic into the Atlas-tier code path so
unimported namespaces produce the same compiler error when atlasRealm is
present. Locate the Atlas/realm branch or function that processes blocks for the
Atlas tier (e.g., the compileTier2 or atlas-related block-processing function)
and add the same for-loop logic that looks up plugins.get(tag.namespace), tracks
missingNamespaces to avoid duplicates, and pushes an error object with namespace
and message when a plugin is absent, then continue; ensure you use the same
symbols (missingNamespaces, plugins, errors, tag.namespace) so behavior matches
compileTier1 exactly.
In `@packages/core/src/loader.ts`:
- Around line 67-70: The resolver currently forces workspace resolution when
SQLDOC_RESOLVE_FROM_LOCAL_PACKAGE==='true' even if a .sqldoc/node_modules copy
exists, causing precedence mismatch with packages/ns-codegen/src/index.ts;
update the branch around resolved/importPath/resolveDir so it first checks for
and prefers the .sqldoc/node_modules package (if present) and only falls back to
using the sql file's directory (sqlDir) when .sqldoc/node_modules is absent or
unavailable, preserving the same precedence logic as the codegen resolver while
still honoring the SQLDOC_RESOLVE_FROM_LOCAL_PACKAGE flag for the final
fallback.
In `@packages/db-neon/src/index.ts`:
- Around line 38-40: The exec implementation drops bound parameters: update the
async exec(queryText: string) in this module to accept and forward the bindings
(e.g., args or params) to the underlying sql call so adapter.exec(req.sql,
req.args) works; specifically modify the exec signature to include the second
parameter (the bound args) and pass them into sql(...) when calling it (preserve
return shape { rowsAffected: ... } as before).
In `@packages/db-pglite/src/index.ts`:
- Around line 45-48: The exec(sql: string) implementation drops bound parameters
(args) so parameterized statements never get bindings; update the exec function
(exec) to accept the args/bindings parameter from callers and forward them to
db.exec (or if you prefer fail-fast, detect a non-empty args array and throw a
clear error), ensuring you reference the underlying db.exec call and return the
same ExecResult shape ({ rowsAffected: last?.affectedRows ?? 0 }) after
forwarding bindings.
- Around line 5-16: In loadExtension, do not swallow import failures: capture
the thrown errors from each dynamic import attempt (the first
import(`@electric-sql/pglite/contrib/${moduleName}`) and the second
import(`@electric-sql/pglite/${moduleName}`)), and if both attempts fail throw
(or return a rejected Promise with) a new Error that includes moduleName and the
original error messages/stack traces so the caller sees why the extension failed
to load instead of silently returning null; update loadExtension to aggregate or
chain the caught errors and include them in the thrown error message.
In `@packages/db/src/db/sqlite.ts`:
- Around line 45-58: The Node SQLite adapter narrows method parameter types to
SQLInputValue[] which conflicts with the DatabaseAdapter interface; update the
signatures of query and exec in the createNodeSqliteAdapter implementation to
use args?: unknown[] (instead of args?: SQLInputValue[]) and adjust any internal
uses (e.g., the calls to stmt.all(...args) and db.prepare(sql).run(...args)) to
accept unknown[] (cast only where the sqlite driver requires) so the adapter
matches DatabaseAdapter and avoids LSP/type-safety violations; reference the
async query and async exec methods and createNodeSqliteAdapter in your changes.
---
Duplicate comments:
In `@packages/db-neon-temporary/src/index.ts`:
- Around line 129-133: The fetch to NEON_API for dbId does not check response
status before parsing; update the code around the fetch (the call that assigns
dataRes and extracts connection_string) to verify dataRes.ok (and handle non-2xx
by throwing or logging the status/text), then validate that the parsed payload
contains a non-empty connection_string before calling toDirect/toPooler;
reference NEON_API, dbId, dataRes, connection_string, and the downstream
toDirect/toPooler so you ensure you fail fast with a clear error or fallback
when the fetch or payload is invalid.
- Around line 210-217: The DROP SCHEMA interpolation can break if a schema name
contains a double-quote; in the loop that uses adapter.query and adapter.exec
(the variables schemas and name), escape identifier quotes before injecting into
the SQL by replacing any " characters with "" (SQL identifier escaping) or
otherwise constructing a safely quoted identifier, then use that escaped
identifier in the adapter.exec(`DROP SCHEMA "${escapedName}" CASCADE`) call;
keep the rest of the logic (querying information_schema.schemata and recreating
public) unchanged.
In `@site/guide/connection-urls.md`:
- Around line 108-110: The page mentions the neon-temporary cache TTL
inconsistently (some places say "72 hours" while the "On each run, sqldoc:" list
uses "24h"); update the string for the neon-temporary cache TTL so all
occurrences use the same wording and value (e.g., replace "24h" with "72 hours"
or vice versa) and normalize formatting (use either "72 hours" or "72h") so
every reference to neon-temporary TTL, including the list under "On each run,
sqldoc:", is identical.
---
Nitpick comments:
In `@packages/cli/src/commands/doctor.ts`:
- Around line 48-54: The nested ternary used to compute the detail value (using
sqldocDir, hasPkgJson, hasCliDep) is hard to read; replace it with an explicit
branch or helper function (e.g., a getDetailMessage or computeDetail) that
returns the three possible strings ('No .sqldoc/ directory', 'No package.json in
.sqldoc/', '@sqldoc/cli not listed in dependencies' or undefined) based on the
same boolean inputs; do the same replacement for the other occurrence that uses
the same three boolean variables so both places call the shared helper or use
clear if/else logic for maintainability and to satisfy static analysis.
In `@packages/db/src/db/plugin-resolver.ts`:
- Around line 75-79: The extractScheme function uses String.match to capture the
first regex group; replace that with a precompiled RegExp and call its exec
method to get the first capture for a small performance improvement — i.e., in
extractScheme(devUrl: string) create a const re = /^([a-z][a-z0-9_-]*):\/\// and
use re.exec(devUrl) to read the scheme from the returned array (or fall back to
devUrl) instead of devUrl.match(...).
In `@tests/pagila/pagila.test.ts`:
- Around line 66-71: Extract the three-way adapter selection into a small helper
function (e.g., getTestDbAdapter or resolveAdapter) to replace the nested
ternary used to set liveDb; move the logic that checks devUrl ===
'neon-temporary', calls neonTemporaryPlugin.createAdapter('neon-temporary',
...), calls createPostgresDockerAdapter(devUrl), or calls
pglitePlugin.createAdapter('pglite', ...) into that function, return the
adapter, and then call it from the test to assign liveDb, which will make the
intent clearer and simplify the test setup.
- Line 27: The nested ternary used to compute devUrl in
tests/pagila/pagila.test.ts is hard to read; extract it into a small helper
(e.g., getDevUrl(version) or buildDevUrl) that returns 'neon-temporary' when
version === 'neon-temporary', returns `docker://${version}` when version is
truthy, and returns undefined otherwise, then replace the inline expression
assigning devUrl with a call to that helper to improve readability and satisfy
the SonarCloud suggestion.
In `@tests/postgraphile-kitchensink/kitchen-sink.test.ts`:
- Around line 28-30: The nested ternary used to compute timeout and devUrl
reduces readability; extract the logic into a small helper (e.g.,
getDevUrl/versionToDevUrl or computeTimeoutAndDevUrl) and call it from the test
setup so that the const timeout and const devUrl assignments are a single clear
call; update references to version, timeout, and devUrl in the describe block to
use the helper's returned values to mirror the refactor done in pagila.test.ts.
🪄 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: CHILL
Plan: Pro
Run ID: 4275fa5c-36de-4a4c-83d6-a6e828604bef
📥 Commits
Reviewing files that changed from the base of the PR and between f1af1c40f3bbdb5e78e3aef6f15095cb11cdb134 and 771d2f0.
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (31)
.vscode/settings.jsonpackage.jsonpackages/cli/src/commands/doctor.tspackages/cli/src/commands/schema.tspackages/cli/src/runtime.tspackages/cli/src/utils/pipeline.tspackages/core/src/compiler/compile.tspackages/core/src/loader.tspackages/db-mysql/src/index.tspackages/db-neon-temporary/src/index.tspackages/db-neon/src/index.tspackages/db-pglite/src/index.tspackages/db-postgres/src/index.tspackages/db/src/__tests__/extensions.test.tspackages/db/src/__tests__/pglite.test.tspackages/db/src/__tests__/plugin-resolver.test.tspackages/db/src/db/mysql-docker.tspackages/db/src/db/plugin-resolver.tspackages/db/src/db/postgres-docker.tspackages/db/src/db/sqlite.tspackages/db/src/db/types.tspackages/db/src/index.tspackages/ns-validate/src/index.tspackages/sqldoc/src/commands/add.tspackages/sqldoc/src/commands/init.tspackages/sqldoc/src/commands/upgrade.tspackages/sqldoc/src/runtime.tsscripts/build-binary.shsite/guide/connection-urls.mdtests/pagila/pagila.test.tstests/postgraphile-kitchensink/kitchen-sink.test.ts
✅ Files skipped from review due to trivial changes (3)
- .vscode/settings.json
- packages/ns-validate/src/index.ts
- scripts/build-binary.sh
🚧 Files skipped from review as they are similar to previous changes (10)
- packages/db/src/tests/pglite.test.ts
- packages/cli/src/commands/schema.ts
- packages/db/src/db/postgres-docker.ts
- packages/db/src/db/types.ts
- packages/db-postgres/src/index.ts
- packages/sqldoc/src/commands/upgrade.ts
- packages/cli/src/utils/pipeline.ts
- packages/sqldoc/src/commands/init.ts
- packages/db/src/index.ts
- packages/db/src/db/mysql-docker.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/ns-codegen/src/index.ts`:
- Around line 61-66: The findSqldocDir() call should be seeded with the project
root to avoid searching from process.cwd(); update the branch that sets
resolveDir so that it calls findSqldocDir(ctx.projectRoot) and assigns
resolveDir accordingly (still using path.join(sqldocDir, 'node_modules') when
found); reference findSqldocDir, ctx.projectRoot, resolveDir and the
SQLDOC_RESOLVE_FROM_LOCAL_PACKAGE check to locate the change, and also
verify/confirm the differing behavior vs loader.ts (which uses sqlDir) is
intentional.
🪄 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: CHILL
Plan: Pro
Run ID: cb1ee994-001b-41c4-83d2-0d9fa64b6e0f
📒 Files selected for processing (1)
packages/ns-codegen/src/index.ts
|



including neon and neon-temporary (no login required) dbs
Summary by CodeRabbit
New Features
New Features
Documentation
Tests
Bug Fixes