Skip to content

Conversation

@Newbie012
Copy link
Collaborator

@Newbie012 Newbie012 commented Nov 12, 2025

Summary by CodeRabbit

  • New Features

    • Improved INSERT validation: detects missing required columns across many cases (defaults, identity columns, CTEs, inherited tables, multi-row inserts, SELECT sources, ON CONFLICT, OVERRIDING) and returns clearer, actionable error messages.
  • Tests

    • Added a comprehensive INSERT test suite covering numerous edge cases and introduced a reusable test helper to simplify and standardize test execution.
  • Chores

    • CI matrix adjusted for PostgreSQL versions and a release changeset added.

@changeset-bot
Copy link

changeset-bot bot commented Nov 12, 2025

🦋 Changeset detected

Latest commit: 231f67f

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

This PR includes changesets to release 17 packages
Name Type
@ts-safeql/generate Patch
@ts-safeql/eslint-plugin Patch
@ts-safeql/shared Patch
@ts-safeql/sql-ast Patch
@ts-safeql-demos/basic-flat-config Patch
@ts-safeql-demos/basic-migrations-raw Patch
@ts-safeql-demos/basic-transform-type Patch
@ts-safeql-demos/basic Patch
@ts-safeql-demos/big-project Patch
@ts-safeql-demos/config-file-flat-config Patch
@ts-safeql-demos/from-config-file Patch
@ts-safeql-demos/multi-connections Patch
@ts-safeql-demos/playground Patch
@ts-safeql-demos/postgresjs-custom-types Patch
@ts-safeql-demos/postgresjs-demo Patch
@ts-safeql-demos/vercel-postgres Patch
@ts-safeql/test-utils Patch

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

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

@vercel
Copy link

vercel bot commented Nov 12, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Preview Comments Updated (UTC)
safeql Ignored Ignored Preview Nov 13, 2025 8:24am

@coderabbitai
Copy link

coderabbitai bot commented Nov 12, 2025

Warning

Rate limit exceeded

@Newbie012 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 51 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c493bb9 and 231f67f.

📒 Files selected for processing (2)
  • packages/generate/src/generate-insert.test.ts (1 hunks)
  • packages/shared/src/errors.ts (1 hunks)

Walkthrough

Adds INSERT-statement validation into the generator pipeline, a new validation utility, a test helper for running generator tests in transactions, comprehensive INSERT tests, a changeset, and a small schema metadata extension for identity columns.

Changes

Cohort / File(s) Summary
Changeset
\.changeset/shiny-books-glow.md
New changeset declaring a patch bump for @ts-safeql/generate with description "improve insert statement validation."
Validation utility
packages/generate/src/utils/validate-insert.ts
New module exporting isParsedInsertResult and validateInsertResult; inspects parsed INSERT ASTs, resolves target table columns from metadata, detects missing non-nullable/no-default/non-identity columns, and throws a PostgresError with hint/sourcemap when violations are found.
Generator integration
packages/generate/src/generate.ts
Invokes insert-result validation after parsing when applicable; removes redundant reparse; adds colIdentity to PgColRow and selects attidentity into column metadata; imports validation utilities.
Test helper
packages/generate/src/test-utils.ts
New exported createTestQuery and SQL type alias; provides a reusable test runner that reserves transactions, applies schema, executes generator flow, maps errors, and asserts expected results or errors.
Tests — harness refactor
packages/generate/src/generate.test.ts
Replaced in-file test harness with external createTestQuery from test-utils; initializes testQuery in beforeAll and delegates test execution to the helper; removed some exported generator types/signatures from the module.
Tests — INSERT scenarios
packages/generate/src/generate-insert.test.ts
New comprehensive INSERT validation test suite covering: missing not-null columns, defaults and DEFAULT VALUES, identity columns, SELECT-source inserts, OVERRIDING clauses, ON CONFLICT, generated columns, multi-row inserts, CTE targets, and inherited tables.
CI workflow
.github/workflows/ci.yml
Workflow adjusted to use a fixed ubuntu-latest runner and a matrix for postgres-version ([16, 17]) for the Postgres image; removed dynamic runs-on matrix entries.

Sequence Diagram(s)

sequenceDiagram
    participant Test
    participant Generator
    participant Parser
    participant Validator
    rect rgba(100,180,120,0.06)
    Test->>Generator: run generate(sql, options)
    end

    Generator->>Parser: parse(sql.text)
    Parser-->>Generator: ParseResult

    alt parsed is INSERT
        rect rgba(180,200,255,0.06)
        Generator->>Validator: validateInsertResult(parsed, pgColsBySchemaAndTableName, query)
        Validator-->>Generator: ok or throw PostgresError
        end
    end

    alt validation passed or not INSERT
        Generator->>Generator: describe(parsed) / continue generation
        Generator-->>Test: result or error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay attention to:
    • packages/generate/src/utils/validate-insert.ts — column-resolution logic, identity and default handling, error/sourcemap construction.
    • packages/generate/src/generate.ts — integration point, removal of duplicate parse, and new colIdentity field propagation.
    • packages/generate/src/generate-insert.test.ts — extensive edge-case tests and expected normalized error messages.
    • packages/generate/src/test-utils.ts — transaction reservation, error mapping, and test isolation behavior.

🐰
I sniffed the AST where the INSERTs hide,
I counted each column with twitchy-eyed pride,
I wrapped tests in transactions, rolled back the tide,
I chased down defaults and identities wide,
I nudged a tiny patch, then hopped to the side. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'improve insert stmt validation' directly reflects the main objective of the PR, which introduces comprehensive INSERT statement validation across multiple files including new validation utilities and test coverage.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 81c6b0a and 47bd948.

📒 Files selected for processing (6)
  • .changeset/shiny-books-glow.md (1 hunks)
  • packages/generate/src/generate-insert.test.ts (1 hunks)
  • packages/generate/src/generate.test.ts (2 hunks)
  • packages/generate/src/generate.ts (4 hunks)
  • packages/generate/src/test-utils.ts (1 hunks)
  • packages/generate/src/utils/validate-insert.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
packages/generate/src/utils/validate-insert.ts (3)
packages/ast-types/src/index.ts (3)
  • RawStmt (803-807)
  • InsertStmt (852-860)
  • ParseResult (4-7)
packages/generate/src/generate.ts (1)
  • PgColRow (630-641)
packages/shared/src/errors.ts (2)
  • QuerySourceMapEntry (210-214)
  • PostgresError (216-280)
packages/generate/src/generate.ts (1)
packages/generate/src/utils/validate-insert.ts (2)
  • isParsedInsertResult (10-14)
  • validateInsertResult (16-62)
packages/generate/src/generate.test.ts (1)
packages/generate/src/test-utils.ts (1)
  • createTestQuery (11-84)
packages/generate/src/generate-insert.test.ts (3)
packages/generate/src/test-utils.ts (2)
  • SQL (9-9)
  • createTestQuery (11-84)
packages/test-utils/src/setup-test-database.ts (2)
  • setupTestDatabase (19-32)
  • generateTestDatabaseName (34-36)
packages/shared/src/common.ts (1)
  • normalizeIndent (102-114)
packages/generate/src/test-utils.ts (2)
packages/generate/src/generate.ts (3)
  • createGenerator (97-110)
  • ResolvedTargetEntry (33-33)
  • GenerateParams (50-60)
packages/shared/src/errors.ts (2)
  • isPostgresError (282-292)
  • InternalError (132-167)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/generate/src/utils/validate-insert.ts (1)

64-82: Fix positional INSERT validation.

When an INSERT omits the explicit column list (e.g., INSERT INTO test_tbl VALUES (DEFAULT, 'abc')), PostgreSQL maps the provided values onto every table column from left to right. Currently, stmt.cols is an empty array [] for such queries, but line 65 checks if (stmt.cols) which is truthy even for empty arrays. This causes lines 66-68 to return an empty array, incorrectly flagging all NOT NULL columns as missing even though the statement is valid.

Apply this diff to check array length instead:

 function getInsertColumns(stmt: LibPgQueryAST.InsertStmt, tableCols: PgColRow[]): string[] {
-  if (stmt.cols) {
+  if (stmt.cols && stmt.cols.length > 0) {
     return stmt.cols
       .map((col) => col.ResTarget?.name)
       .filter((name): name is string => Boolean(name));
   }

   if (stmt.selectStmt === undefined) {
     return [];
   }

   const valuesFromSelect = stmt.selectStmt.SelectStmt?.valuesLists?.at(0)?.List?.items;

   if (valuesFromSelect !== undefined) {
     return tableCols.slice(0, valuesFromSelect.length).map((c) => c.colName);
   }

   return tableCols.map((c) => c.colName);
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47bd948 and 313698d.

📒 Files selected for processing (2)
  • packages/generate/src/generate-insert.test.ts (1 hunks)
  • packages/generate/src/utils/validate-insert.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/generate/src/generate-insert.test.ts
🧰 Additional context used
🧬 Code graph analysis (1)
packages/generate/src/utils/validate-insert.ts (3)
packages/ast-types/src/index.ts (3)
  • RawStmt (803-807)
  • InsertStmt (852-860)
  • ParseResult (4-7)
packages/generate/src/generate.ts (1)
  • PgColRow (630-641)
packages/shared/src/errors.ts (2)
  • QuerySourceMapEntry (210-214)
  • PostgresError (216-280)
🔇 Additional comments (2)
packages/generate/src/utils/validate-insert.ts (2)

1-14: LGTM!

The type definition and type guard are well-structured and correctly validate whether a parsed result contains an INSERT statement.


16-43: LGTM!

The validation logic correctly identifies NOT NULL columns without defaults that are missing from the INSERT statement. The filter at lines 37-39 appropriately checks for non-nullable columns (colNotNull), absence of defaults (!colHasDef), non-identity columns (colIdentity === ""), and verifies they're not in the insert list.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 313698d and ae8149f.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml (1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.8)
.github/workflows/ci.yml

23-23: expecting a single ${{...}} expression or array value for matrix variations, but found plain text node

(syntax-check)


24-24: expecting a single ${{...}} expression or array value for matrix variations, but found plain text node

(syntax-check)

@Newbie012 Newbie012 merged commit c1919e2 into main Nov 13, 2025
5 checks passed
@Newbie012 Newbie012 deleted the feat-improve-instert-stmt-validation branch November 13, 2025 08:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants