Skip to content

refactor(rain): split query builders and tests into focused files#25

Merged
cungminh2710 merged 2 commits into
mainfrom
minhc/refactor-query
Mar 29, 2026
Merged

refactor(rain): split query builders and tests into focused files#25
cungminh2710 merged 2 commits into
mainfrom
minhc/refactor-query

Conversation

@cungminh2710
Copy link
Copy Markdown
Contributor

What this PR for?

Refactors the monolithic query builder implementation into focused file-level units for select, insert, update, delete, SQL compilation, and shared helpers, without changing behavior or package boundaries. Also reorganizes the query test suite into matching focused test files while preserving existing assertions and keeping the full fmt, lint, and test suite green.

What did you do for validating the changes?

Anything else you want to add? (Optional)

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Mar 29, 2026

Greptile Summary

This PR refactors the 1 491-line monolithic query.go into seven focused files (query_common.go, query_compile.go, query_select.go, query_insert.go, query_update.go, query_delete.go, query_model_assignments.go) and mirrors that split across eight matching test files — all within the same rain package, so public API and behaviour are unchanged.

Key changes:

  • All logic is a pure file-level extraction; no algorithmic or API changes were made.
  • query_test.go is reduced to shared external-test fixtures (defineTables, type declarations); actual test functions are distributed across the focused test files.
  • Internal test helpers are consolidated in query_internal_test.go, keeping runtime and compile-path tests separate.
  • postgres_integration_test.go replaces a manual driver-name loop with slices.Contains — a clean idiomatic simplification.
  • One duplicate ErrNoConnection assertion remains in query_compile_internal_test.go (lines 43–50), and a number of the new top-level test functions are missing t.Parallel() calls that the rest of the suite uses.

Confidence Score: 5/5

Safe to merge — purely structural refactoring with no behavioral or API changes.

All production logic is a verbatim file-level split from the original query.go; no algorithmic changes, no public API changes, and the test suite (including integration and benchmark tests) is confirmed green. The only findings are a duplicate test assertion and missing t.Parallel() calls — both P2 style issues that do not affect correctness or reliability.

query_compile_internal_test.go (duplicate ErrNoConnection assertion); query_insert_test.go and query_write_test.go (missing t.Parallel() on top-level tests).

Important Files Changed

Filename Overview
pkg/rain/query_common.go New file housing shared types extracted from query.go: queryRunner, joinClause, assignment, returningClause, selectTableSource, tableDefSource, subqueryTableSource, cteDefinition, and closeRows helper — identical logic to original.
pkg/rain/query_compile.go New file containing the SQL compilation engine (compileContext, writeExpression, writeRaw, writeColumn, joinPredicates) — split cleanly from query.go with no logic changes.
pkg/rain/query_select.go SelectQuery extracted to its own file; all fields, methods, and runtime helpers (Scan, Count, Exists, cache paths) faithfully moved from query.go with no behavioral changes.
pkg/rain/query_insert.go InsertQuery and InsertConflictBuilder moved to their own file; insertAssignments, validateInsertRowShape, writeConflictClause all intact and unchanged from the original.
pkg/rain/query_update.go UpdateQuery extracted cleanly with ToSQL, Exec, Scan, and Unbounded guard logic — no changes from original.
pkg/rain/query_delete.go DeleteQuery extracted cleanly with ToSQL, Exec, Scan, and Unbounded guard logic — no changes from original.
pkg/rain/query_model_assignments.go Model-to-assignment helpers (assignmentsFromModel, mergeAssignments, validateAssignmentTarget, fieldValueForInsert, dereferenceValue) extracted to a focused file — logic unchanged.
pkg/rain/query_compile_internal_test.go New internal test file covers query builder error paths and compile/assignment helpers; contains a duplicated ErrNoConnection assertion for InsertQuery.Scan (lines 43–50).
pkg/rain/query_internal_test.go Shared internal test fixtures and helpers (table definitions, openInternalQueryDB, createInternalQuerySchema, countingRunner) extracted to their own file — clean separation of concerns.
pkg/rain/query_runtime_internal_test.go Runtime execution tests (insert/update/delete exec, cache hit/miss/expiry/bypass, relation loading, chunked batches) grouped into a focused file; all existing assertions preserved.
pkg/rain/query_select_test.go External SELECT compilation tests split out; TestSelectToSQL is missing t.Parallel() unlike the other top-level tests in the file, but no behavioral issues.
pkg/rain/query_insert_test.go External INSERT compilation tests split out; all TestInsert* functions are missing t.Parallel() calls, unlike the broader suite convention, but no behavioral impact.
pkg/rain/query_write_test.go External UPDATE/DELETE and dialect feature tests; TestInsertUpdateDeleteToSQL, TestReturningUnsupportedDialect, TestReturningSupportedOperations are missing t.Parallel() — consistent with TestInsert* style.
pkg/rain/query_test.go Now contains only shared external-test fixtures (type definitions, defineTables, defineExpandedTypesTable) — good use of this file as a test-package helper hub.
pkg/rain/postgres_integration_test.go Driver registration guard simplified from a manual loop to slices.Contains — functionally identical, slightly more readable.
pkg/rain/sqlite_benchmark_test.go Benchmark file untouched in logic; any diff here is cosmetic or imports-only as part of the test reorganization.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    subgraph "Production code (new split)"
        QC[query_common.go\nqueryRunner · joinClause · assignment\nreturningClause · selectTableSource\ncloseRows]
        QCP[query_compile.go\ncompileContext · writeExpression\nwriteRaw · joinPredicates]
        QMA[query_model_assignments.go\nassignmentsFromModel\nmergeAssignments\nvalidateAssignmentTarget]
        QS[query_select.go\nSelectQuery]
        QI[query_insert.go\nInsertQuery\nInsertConflictBuilder]
        QU[query_update.go\nUpdateQuery]
        QD[query_delete.go\nDeleteQuery]
    end

    QC --> QS
    QC --> QI
    QC --> QU
    QC --> QD
    QCP --> QS
    QCP --> QI
    QCP --> QU
    QCP --> QD
    QMA --> QI

    subgraph "Test code (new split)"
        QT[query_test.go\nExternal fixtures\ndefineTables]
        QIT[query_internal_test.go\nInternal fixtures\ndefineInternalQueryTables\nopenInternalQueryDB]
        QCIT[query_compile_internal_test.go\nBuilder error paths\nCompile context helpers]
        QRIT[query_runtime_internal_test.go\nExecution · Cache\nRelations]
        QST[query_select_test.go\nTestSelectToSQL\nTestSelectAdvancedComposition]
        QINT[query_insert_test.go\nTestInsert*]
        QWT[query_write_test.go\nTestUpdate* · TestDelete*\nTestDialectFeatures]
    end

    QT --> QST
    QT --> QINT
    QT --> QWT
    QIT --> QCIT
    QIT --> QRIT
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: pkg/rain/query_compile_internal_test.go
Line: 43-50

Comment:
**Duplicate `ErrNoConnection` assertion for `InsertQuery.Scan`**

Lines 43–45 and 47–50 create an identical `InsertQuery` (no runner, same `table` and `returning`) and both assert that `Scan` returns `ErrNoConnection`. The second block is redundant and should be removed.

```suggestion
	insertNoRunner := &InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}
	if err := insertNoRunner.Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
		t.Fatalf("expected insert scan ErrNoConnection, got %v", err)
	}
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: pkg/rain/query_select_test.go
Line: 13

Comment:
**Missing `t.Parallel()` on top-level test functions**

`TestSelectToSQL` (this file, line 13) is missing `t.Parallel()`. The same pattern applies to several top-level functions in the other new test files: all eight `TestInsert*` functions in `query_insert_test.go`, and `TestInsertUpdateDeleteToSQL`, `TestReturningUnsupportedDialect`, and `TestReturningSupportedOperations` in `query_write_test.go`.

All of these are pure SQL-compilation tests with no shared mutable state, so they are safe to run in parallel. Adding `t.Parallel()` aligns them with the rest of the suite (e.g. `TestExpandedTypesCompileToSQL`, `TestSelectAdvancedComposition`, `TestDialectFeatures`) and avoids unnecessarily serialising an otherwise parallel test run.

```suggestion
func TestSelectToSQL(t *testing.T) {
	t.Parallel()
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "." | Re-trigger Greptile

Comment thread pkg/rain/query_compile_internal_test.go Outdated
Comment on lines +43 to +50
if err := (&InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}).Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
t.Fatalf("expected insert scan ErrNoConnection, got %v", err)
}

insertNoRunner := &InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}
if err := insertNoRunner.Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
t.Fatalf("expected insert returning scan ErrNoConnection, got %v", err)
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Duplicate ErrNoConnection assertion for InsertQuery.Scan

Lines 43–45 and 47–50 create an identical InsertQuery (no runner, same table and returning) and both assert that Scan returns ErrNoConnection. The second block is redundant and should be removed.

Suggested change
if err := (&InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}).Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
t.Fatalf("expected insert scan ErrNoConnection, got %v", err)
}
insertNoRunner := &InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}
if err := insertNoRunner.Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
t.Fatalf("expected insert returning scan ErrNoConnection, got %v", err)
}
insertNoRunner := &InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}
if err := insertNoRunner.Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
t.Fatalf("expected insert scan ErrNoConnection, got %v", err)
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: pkg/rain/query_compile_internal_test.go
Line: 43-50

Comment:
**Duplicate `ErrNoConnection` assertion for `InsertQuery.Scan`**

Lines 43–45 and 47–50 create an identical `InsertQuery` (no runner, same `table` and `returning`) and both assert that `Scan` returns `ErrNoConnection`. The second block is redundant and should be removed.

```suggestion
	insertNoRunner := &InsertQuery{dialect: db.Dialect(), table: users.TableDef(), returning: []schema.Expression{users.ID}}
	if err := insertNoRunner.Scan(context.Background(), &internalUserRow{}); !errors.Is(err, ErrNoConnection) {
		t.Fatalf("expected insert scan ErrNoConnection, got %v", err)
	}
```

How can I resolve this? If you propose a fix, please make it concise.

"github.com/hyperlocalise/rain-orm/pkg/schema"
)

func TestSelectToSQL(t *testing.T) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Missing t.Parallel() on top-level test functions

TestSelectToSQL (this file, line 13) is missing t.Parallel(). The same pattern applies to several top-level functions in the other new test files: all eight TestInsert* functions in query_insert_test.go, and TestInsertUpdateDeleteToSQL, TestReturningUnsupportedDialect, and TestReturningSupportedOperations in query_write_test.go.

All of these are pure SQL-compilation tests with no shared mutable state, so they are safe to run in parallel. Adding t.Parallel() aligns them with the rest of the suite (e.g. TestExpandedTypesCompileToSQL, TestSelectAdvancedComposition, TestDialectFeatures) and avoids unnecessarily serialising an otherwise parallel test run.

Suggested change
func TestSelectToSQL(t *testing.T) {
func TestSelectToSQL(t *testing.T) {
t.Parallel()
Prompt To Fix With AI
This is a comment left during a code review.
Path: pkg/rain/query_select_test.go
Line: 13

Comment:
**Missing `t.Parallel()` on top-level test functions**

`TestSelectToSQL` (this file, line 13) is missing `t.Parallel()`. The same pattern applies to several top-level functions in the other new test files: all eight `TestInsert*` functions in `query_insert_test.go`, and `TestInsertUpdateDeleteToSQL`, `TestReturningUnsupportedDialect`, and `TestReturningSupportedOperations` in `query_write_test.go`.

All of these are pure SQL-compilation tests with no shared mutable state, so they are safe to run in parallel. Adding `t.Parallel()` aligns them with the rest of the suite (e.g. `TestExpandedTypesCompileToSQL`, `TestSelectAdvancedComposition`, `TestDialectFeatures`) and avoids unnecessarily serialising an otherwise parallel test run.

```suggestion
func TestSelectToSQL(t *testing.T) {
	t.Parallel()
```

How can I resolve this? If you propose a fix, please make it concise.

@cungminh2710 cungminh2710 merged commit 24cedf9 into main Mar 29, 2026
4 checks passed
@cungminh2710 cungminh2710 deleted the minhc/refactor-query branch March 29, 2026 11:59
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.

1 participant