@carllee1983/dbcli 1.39.2 → 1.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -105,6 +105,7 @@ dbcli schema --use prod # Scan prod DB; saves to .dbcli/schemas/prod
105
105
 
106
106
  **Schema storage (v1.4+):** Schema is persisted as layered files under `.dbcli/schemas/`. With v2 multi-connection config each connection gets its own subdirectory (`.dbcli/schemas/<connection>/`). Run `dbcli schema --use <connection>` once per connection before querying it — otherwise `schema <table>` may return data from the wrong connection's cache.
107
107
 
108
+ > **PostgreSQL:** Introspection uses the exact `public` catalog identity throughout. Full catalog/schema/table joins prevent a reused constraint name from contaminating another table; enum lookup includes its namespace; composite primary-key order comes from the exact table OID and index ordinality; and row estimates are scoped to the exact `public` relation. Row-count SQL qualifies and quotes both `"public"` and the exact table identifier, escaping embedded quotes so mixed-case or punctuation-bearing names remain distinct and safe.
108
109
  > **Redis:** `schema <key>` is required (no full scan). The output exposes `type`, `ttl`, `size`, and a small `sample` (e.g. first 5 hash keys). `--reset` / `--refresh` are rejected — Redis caches no schema.
109
110
  > **Elasticsearch:** `schema [index]` flattens the `_mapping` properties (nested `a.b.c`) and emits each `.fields` multi-field as a separate column (e.g. `text` + `text.keyword`). Full scan iterates all non-system indices and stores per-connection caches alongside SQL engines.
110
111
  > **MongoDB:** schema is sampled via `$sample` (default 100, max 1000). `--sample-method natural` switches to `find().limit()`; `random` (default) falls back to natural order on driver error. Output columns surface nested dot-paths with `presence` (0..1) and `redacted: true` flags for blacklist-matched paths. The persisted cache records `sampleMethod` and `sampleSize`; `dbcli doctor` reports them via a `sampled: method=…, size=…` line.
@@ -192,9 +193,134 @@ dbcli explain --bulk @analytics/* # glob over saved queries
192
193
  | `nested-loop-large` | yellow | PG `Nested Loop` with planner rows > 10,000 |
193
194
 
194
195
  > Notes:
195
- > - `--analyze` executes the statement do not use against destructive SQL.
196
+ > - `--analyze` executes the statement, so dbcli accepts it only for SQL that is
197
+ > structurally proven to be a read-only, function-free `SELECT` (including
198
+ > SELECT-only CTEs). Explicit function and table-function calls are unproven
199
+ > because user-defined and built-in functions may have side effects. DML, DDL,
200
+ > data-modifying CTEs, session assignments, function-bearing SQL, and
201
+ > unrecognized SQL are rejected before the adapter is invoked; use plain
202
+ > `dbcli explain` for those statements.
196
203
  > - Auto-`LIMIT` is **not** applied to EXPLAIN statements (since v1.23 P1).
197
204
 
205
+ ### lint
206
+
207
+ Static, report-only SQL anti-pattern analysis for PostgreSQL, MySQL, and
208
+ MariaDB. `lint` never opens a database connection, never runs the SQL, and
209
+ never applies a rewrite. Schema-aware findings use only the layered schema
210
+ cache under `.dbcli/schemas/`.
211
+
212
+ ```text
213
+ dbcli lint [queries...]
214
+ dbcli lint --bulk <input>
215
+ dbcli --use <conn> lint [queries...]
216
+ ```
217
+
218
+ An input may be inline SQL, a saved query such as `@analytics/live-summary`, a
219
+ SQL file such as `@queries.sql`, or a saved-query/filesystem glob such as
220
+ `@analytics/*` or `@queries/**/*.sql`. `--bulk` accepts a comma-separated mix
221
+ of those `@file`, `@glob`, and `@saved-query` inputs; quote a filesystem glob
222
+ in a shell so the `@` reference reaches dbcli unchanged.
223
+
224
+ ```bash
225
+ dbcli lint "SELECT * FROM users WHERE email LIKE '%@example.com'" --format json
226
+ dbcli lint --bulk '@queries/**/*.sql' --format markdown
227
+ dbcli --use staging lint @analytics/live-summary --min-severity warn
228
+ ```
229
+
230
+ | Option | Default | Meaning |
231
+ |---|---|---|
232
+ | `--format <text\|json\|markdown>` | `text` | Render one report per resolved input. |
233
+ | `--min-severity <info\|warn\|error>` | `info` | Omit findings below the selected severity. |
234
+ | `--no-schema` | off | Skip schema-only checks without reading schema-cache paths; static `NOT IN` NULL checks still run. |
235
+ | `--bulk <input>` | none | Resolve a comma-separated list of `@file`, `@glob`, or `@saved-query` inputs. |
236
+ | `--recovery` | off | On command failure, emit and save a linked `RecoveryEnvelope`. |
237
+ | global `--use <conn>` | configured default | Select a v2 named connection and its isolated cache; place it before `lint`: `dbcli --use <conn> lint …`. |
238
+
239
+ **Rules:**
240
+
241
+ | Rule | Severity | What it reports |
242
+ |---|---|---|
243
+ | `select-star` | warn | A top-level `SELECT *`; when one table and its cached columns are unambiguous, the finding may include a column-list rewrite draft. |
244
+ | `unanchored-like` | warn | A `LIKE` / `ILIKE` pattern beginning with `%`, which a conventional B-tree index cannot anchor. |
245
+ | `missing-limit-offset` | info | Deep pagination with `OFFSET >= 1000`; prefer keyset pagination. |
246
+ | `non-sargable-where` | warn | A function or arithmetic expression applied to the column side of a predicate. |
247
+ | `or-to-union` | info | A top-level `OR` across different columns that can complicate index selection; any UNION alternative must preserve identity and multiplicity. |
248
+ | `subquery-to-join` | info | `IN (SELECT …)` where an equivalent `EXISTS`, or a JOIN with proven uniqueness/deduplication, may plan better. |
249
+ | `distinct-groupby-abuse` | warn | Redundant `DISTINCT` when simple projected columns exactly cover the `GROUP BY` columns. |
250
+ | `implicit-cast` | warn | A schema-verified column/literal type mismatch that can disable index use; safe, unambiguous numeric drafts may be included. |
251
+ | `not-in-nullable` | warn | A right-hand `NOT IN` value that can be NULL: explicit `NULL`, outer-join null extension, a nullable subquery projection, or a known nullable CASE/cast/aggregate expression. A nullable left-hand column is not this rule. |
252
+
253
+ `implicit-cast` and the schema-enriched portion of `not-in-nullable` read the
254
+ selected cache through the schema loader abstraction. Static `not-in-nullable`
255
+ checks still run without it. All schema caches live beneath `.dbcli/schemas/`. A v2
256
+ configuration always uses `.dbcli/schemas/<resolved-connection>/`, including
257
+ the configured default. The root `.dbcli/schemas/` directory is only the
258
+ v1/legacy unnamed cache. Global `dbcli --use <conn> lint …` selects another
259
+ named v2 slot. The command never refreshes the cache and never falls back to
260
+ schema embedded in config.
261
+
262
+ Skipped rules are returned with machine-readable `blocked:` reasons:
263
+
264
+ - Invalid SQL blocks all nine rules with `blocked: parse failed` and includes
265
+ `parseError`.
266
+ - `--no-schema` blocks `implicit-cast` and the schema-dependent portion of
267
+ `not-in-nullable` with `blocked: --no-schema`; static RHS hazards still run.
268
+ - A missing layered cache records
269
+ `blocked: schema cache unavailable (run dbcli schema)` for those unavailable
270
+ schema checks while retaining static RHS findings.
271
+
272
+ Every finding includes its rule, severity, source span, message, and
273
+ `schemaVerified` state. Some findings also carry a confidence-labelled rewrite
274
+ draft and a shell-safe verification command. It uses
275
+ `dbcli explain --analyze` only when the statement is structurally proven read-only;
276
+ function-bearing and session-assignment statements are unproven, so lint
277
+ falls back to plain `dbcli explain`. These are suggestions only: `lint` neither
278
+ executes the verification command nor changes the query.
279
+
280
+ When schema identifiers collide after case folding, schema-aware findings and
281
+ rewrites are withheld. The SQL parser does not preserve reliable quote
282
+ provenance, so an exact-looking mixed-case AST identifier cannot disambiguate
283
+ that collision. CTE, derived, schema-qualified, and database-qualified
284
+ relations also never borrow facts from the unqualified cache.
285
+
286
+ For `not-in-nullable`, remove or filter right-hand NULL values. In a subquery,
287
+ filter the projected value with `IS NOT NULL`; `NOT EXISTS` may be a better
288
+ semantic form when appropriate. dbcli does not automatically rewrite this case
289
+ unless correlation, type classification, qualified-column resolution, and the
290
+ rewrite target are all unambiguous. A direct or `AND`-conjoined `IS NOT NULL`
291
+ filter on the exact projected expression suppresses the finding; aggregates
292
+ apply the same proof in `HAVING`. Filters under `OR` or ambiguous expression
293
+ matches do not. The rule recursively checks projection, JOIN `ON`, `WHERE`, and
294
+ `HAVING` expressions, using each nested SELECT/CTE/derived statement's own
295
+ scope. Qualified outer-join null extension remains detectable without a cache,
296
+ but a join's synthetic NULL row is not applied inside that join's own `ON`;
297
+ declared nullability and completed earlier joins still apply there.
298
+
299
+ Trimmed JSON example:
300
+
301
+ ```json
302
+ [
303
+ {
304
+ "sql": "SELECT * FROM users",
305
+ "dialect": "postgresql",
306
+ "findings": [
307
+ {
308
+ "rule": "select-star",
309
+ "severity": "warn",
310
+ "message": "SELECT * fetches every column; list the columns you need.",
311
+ "span": { "start": 0, "end": 8 },
312
+ "schemaVerified": false
313
+ }
314
+ ],
315
+ "skippedRules": [],
316
+ "relatedCommands": [
317
+ "dbcli guide missing-index-for \"SELECT * FROM users\"",
318
+ "dbcli explain --analyze \"SELECT * FROM users\""
319
+ ]
320
+ }
321
+ ]
322
+ ```
323
+
198
324
  ### plan
199
325
 
200
326
  Static SQL risk analyzer. Classifies a statement into the same permission tiers
@@ -583,6 +709,147 @@ dbcli diff --against before.json --format json
583
709
  **Options:** `--snapshot <path>`, `--against <path>`, `--format <json|table>`
584
710
  **Permission:** query-only+
585
711
 
712
+ #### `diff --against-orm`
713
+
714
+ Compare an ORM definition with the local SQL schema cache. This mode reads
715
+ `config.schema`; it does not open a database connection, refresh the cache, or
716
+ execute a proposal. An empty cache fails with
717
+ `Schema cache is empty. Run 'dbcli schema' first.` Snapshot mode remains a
718
+ separate `--snapshot` / `--against` workflow.
719
+
720
+ ```bash
721
+ # Prisma and normalized JSON accept exactly one file
722
+ dbcli diff --against-orm prisma/schema.prisma --format json
723
+ dbcli diff --against-orm schema.normalized.json --orm-format json --format table
724
+
725
+ # DDL accepts repeatable or comma-separated paths and real filesystem globs
726
+ dbcli diff --against-orm "migrations/*.sql" --format markdown
727
+ dbcli diff --against-orm migrations/base.sql,migrations/accounts.sql \
728
+ --against-orm migrations/orders.sql --orm-format ddl --format json
729
+
730
+ # Ignore patterns are comma-separated and match qualified table identity
731
+ dbcli diff --against-orm prisma/schema.prisma --ignore 'public.audit_*,public.Legacy'
732
+ ```
733
+
734
+ | Option | Behavior |
735
+ | :--- | :--- |
736
+ | `--against-orm <paths>` | Repeatable or comma-separated input. DDL inputs support real filesystem globs; matches are deduplicated and put in deterministic path order, then parsed as one shared ordered context so an index in a later file can attach to a table declared in an earlier file. Prisma and normalized JSON accept exactly one file, and globs are rejected for those formats. |
737
+ | `--orm-format prisma\|ddl\|json` | Override extension/content detection. Without it, dbcli detects Prisma, DDL, or normalized JSON from the path and content. |
738
+ | `--ignore <globs>` | Comma-separated, case-sensitive table globs. Patterns match the qualified display identity (for example `public.Users`). `_prisma_migrations` is always unmanaged. |
739
+ | `--format json\|table\|markdown` | Select machine JSON, human table, or Markdown output. Markdown is available only in ORM drift mode. |
740
+ | `--recovery` | On an I/O, configuration, empty-cache, invalid-format, or unsupported-engine failure, emit and save a structured recovery envelope. Invalid Prisma/DDL constructs normally become `unparsed` entries instead of throwing. |
741
+
742
+ The command supports PostgreSQL, MySQL, and MariaDB configurations. Only
743
+ error-level **scored drift** determines the report's drift exit code: one or more
744
+ scored errors exits `1`; warnings, infos, `unmanaged`, or `unparsed` entries alone
745
+ exit `0`. Command/configuration failures independently exit code `1`. The four
746
+ drift categories and tolerance rules are:
747
+
748
+ | Category | Severity and comparison rule |
749
+ | :--- | :--- |
750
+ | `missing_in_db` | `error` — a table, column, or index exists in the ORM definition but not in the cached DB schema. |
751
+ | `missing_in_orm` | `warn` — a table, column, or index exists in the cached DB schema but not in the ORM definition. |
752
+ | `mismatch` | `error` when the type family or nullability differs; `info` for same-family type spelling, default, or primary-key differences. |
753
+ | `unmanaged` | `info`, excluded from error/warn scoring — the table matched the built-in or user `--ignore` patterns. |
754
+
755
+ Type-family tolerance deliberately treats engine spellings such as `text` and
756
+ `varchar(191)` as the same family: the spelling difference is still visible as
757
+ `info`, while an integer/text family difference is an `error`. Indexes compare
758
+ by structural index signatures — ordered, case-folded column names plus
759
+ uniqueness — rather than by engine-specific index names. Duplicate signatures
760
+ are emitted once. Drift entries sort deterministically by table, object, category,
761
+ and detail using Unicode code-point order, never locale-dependent collation.
762
+
763
+ **Schema and table identity.** Storage preserves exact, case-sensitive schema
764
+ and table names from the database catalog. Exact, case-sensitive `(schema, table)`
765
+ tuples are the comparison key, so PostgreSQL `users` and `"Users"` can coexist.
766
+ DDL resolution rules: unquoted SQL identifiers fold to lowercase; quoted identifiers match exactly.
767
+ For example, unquoted `Users` resolves to `users`, and quoted
768
+ `"Users"` resolves only to `Users`. Quote state comes from the parsed identifier representation;
769
+ dbcli never infers it from display text, catalog spelling, or a
770
+ Prisma mapping. Qualified components resolve independently, and unqualified ORM
771
+ identities use the cached DB default schema when one is known. Qualified display
772
+ names and `--ignore` matching remain case-sensitive. Duplicate exact or
773
+ duplicate resolved table identities fail closed instead of overwriting one
774
+ another.
775
+
776
+ **Prisma subset.** The parser supports `model` blocks; scalar `String`, `Int`,
777
+ `BigInt`, `Float`, `Decimal`, `Boolean`, `DateTime`, `Json`, and `Bytes` fields;
778
+ `?`; relation-side `[]`; `@id`, `@unique`, `@default(...)`, `@map("...")`,
779
+ `@@map("...")`, `@@index([...])`, `@@unique([...])`; relations with
780
+ `fields` / `references`; and the validated native mappings `@db.Text`,
781
+ `@db.VarChar(n)`, `@db.Uuid`, `@db.Timestamptz([precision])`, `@db.Date`,
782
+ `@db.SmallInt`, and `@db.JsonB`. Views, composite types, enums used as scalar
783
+ columns, multi-schema datasource configuration, malformed declarations, unknown
784
+ attributes, and unsupported native mappings are never guessed.
785
+
786
+ Prisma and DDL constructs outside the supported subset are retained in
787
+ `unparsed` with a `blocked:` reason. These entries are separate from scored drift:
788
+ inspect and resolve them before treating an otherwise clean summary as complete.
789
+ Multi-file DDL is consumed as one deterministic shared ordered statement context,
790
+ so later `CREATE INDEX` statements can reference tables declared in earlier
791
+ files. PostgreSQL `PARTITION BY` and MySQL/MariaDB table engine, charset, and
792
+ other `CREATE TABLE` table options are unsupported: the construct produces a
793
+ `blocked:` `unparsed` entry and does not emit a managed ORM table.
794
+ The normalized JSON escape hatch is Zod-validated and uses an array of tables
795
+ with explicit exact `identity` objects; optional parsed identifiers must include
796
+ their `quoted` flags, and every normalized JSON `unparsed.reason` must start with
797
+ `blocked:`.
798
+
799
+ ```json
800
+ {
801
+ "ormSource": "prisma",
802
+ "entries": [
803
+ {
804
+ "category": "missing_in_db",
805
+ "severity": "error",
806
+ "table": "public.users",
807
+ "object": "email",
808
+ "detail": "column 'email' (text) is defined in prisma but absent in the database",
809
+ "proposedCommands": [
810
+ "# escalate: schema-qualified table 'public.users' is not losslessly representable by dbcli migrate — run: dbcli skill tasks plan migration-review"
811
+ ]
812
+ }
813
+ ],
814
+ "unparsed": [],
815
+ "summary": { "errors": 1, "warns": 0, "infos": 0, "unmanaged": 0 }
816
+ }
817
+ ```
818
+
819
+ Missing unqualified columns and indexes may receive shell-safe, dry-run-by-default
820
+ `dbcli migrate add-column` or `add-index` proposal strings. Simple arguments stay
821
+ unquoted; unsafe shell characters are POSIX single-quoted. Table creation,
822
+ removal, mismatch, and DB-only drift escalate to `migration-review`. A
823
+ schema-qualified target, or index columns that the current `migrate --columns`
824
+ CLI cannot represent losslessly, also escalates instead of emitting a corrupt
825
+ command. Any table, column, or type positional beginning with `-` also escalates
826
+ so Commander cannot reinterpret it as an option. A leading-dash option value is
827
+ rendered with option-safe attached syntax, for example `--default=-1` or
828
+ `--columns=--config,email`. Proposals are text only and never add `--execute`.
829
+
830
+ For a guided, cache-refreshing review, use the built-in `orm-drift-review` pack:
831
+
832
+ ```bash
833
+ dbcli skill tasks plan orm-drift-review \
834
+ --param orm_path=prisma/schema.prisma \
835
+ --format json
836
+ ```
837
+
838
+ The plan is `blacklist list` → `schema --format json` →
839
+ `diff --against-orm ... --format json`. Run any proposed `migrate` command in its
840
+ default dry-run mode, capture the emitted DDL, confirm its exact target, and pass
841
+ both values to the separate migration review:
842
+
843
+ ```sh
844
+ dbcli skill tasks plan migration-review \
845
+ --param "table=${exact_table}" \
846
+ --param "ddl=${captured_ddl}"
847
+ ```
848
+
849
+ Both parameters are required. Keep each expansion as one quoted shell argument;
850
+ never use `eval`, and consider `--execute` only after the plan and captured DDL
851
+ have been reviewed.
852
+
586
853
  ### snapshot
587
854
 
588
855
  Capture a **result fingerprint** of a query (not schema): `rowCount` plus per-column
@@ -1713,8 +1980,12 @@ a read-only (`plan-only`) pack taking a required `table` parameter that walks
1713
1980
  in recent audit activity. Additional read-only packs ship for common agent
1714
1981
  workflows: `audit-permissions` (permission/blacklist audit), `safe-backfill`
1715
1982
  (plan a write with blacklist+schema+risk checks), `schema-drift-review` (cached
1716
- vs live schema diff), and `connection-health` (reachability/config/capacity
1717
- triage). Run `dbcli skill tasks list` for the full set.
1983
+ vs live schema diff), `orm-drift-review` (ORM definition vs cached DB schema),
1984
+ and `connection-health` (reachability/config/capacity
1985
+ triage). **MongoDB packs:** `mongo-safe-backfill` (dry-run–previewed backfill)
1986
+ and `mongo-schema-drift-review` (sampled dot-path drift, with a `sample_size` knob
1987
+ to damp sampling noise); filter them with `dbcli skill tasks list --engine mongodb`.
1988
+ Run `dbcli skill tasks list` for the full set.
1718
1989
 
1719
1990
  ```bash
1720
1991
  dbcli skill tasks plan analyze-table-perf --param table=betting_logs --format json