Skip to content

Add MySQL and PostgreSQL connectors to Go syncer - #18162

Merged
JinHai-CN merged 16 commits into
infiniflow:mainfrom
mkaaad:feat/connector-go-migration
Aug 13, 2026
Merged

JinHai-CN merged 16 commits into
infiniflow:mainfrom
mkaaad:feat/connector-go-migration

Conversation

@mkaaad

@mkaaad mkaaad commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

As title

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Aug 12, 2026
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds MySQL and PostgreSQL connectors with validation, query generation, document conversion, synchronization, and pruning. It also adds FlexibleTime for SQL and JSON timestamp handling and updates sync timestamp boundaries.

Changes

RDBMS connectors and sync timestamp handling

Layer / File(s) Summary
Flexible timestamp contract
internal/entity/flexible_time.go, internal/entity/flexible_time_test.go, internal/entity/connector.go
Adds FlexibleTime with SQL scanning, value conversion, JSON serialization, timestamp parsing, and indexed varchar(255) sync-log fields. Tests cover SQL and JSON behavior.
MySQL connector execution
internal/syncer/connector/mysql.go, internal/syncer/connector/mysql_test.go
Adds MySQL configuration, validation, query construction, row normalization, document generation, batched synchronization, pruning, cleanup, and tests.
PostgreSQL connector execution
internal/syncer/connector/postgresql.go, internal/syncer/connector/postgresql_test.go
Adds PostgreSQL configuration, validation, public-schema discovery, query construction, row normalization, document generation, batched synchronization, pruning, cleanup, and tests.
Connector registration
internal/syncer/syncer.go, go.mod
Registers MySQL and PostgreSQL connectors and declares PostgreSQL driver dependencies.
Sync timestamp wiring
internal/dao/connector.go, internal/dao/sync_task.go, internal/syncer/sync_runner.go
Converts flexible poll timestamps at sync boundaries and wraps stored timestamps with entity.NewFlexibleTime.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Syncer
  participant Connector
  participant Database
  participant SyncSession
  Syncer->>Connector: OpenSync(request)
  Connector->>Database: Execute configured or discovered query
  Database-->>SyncSession: Stream rows
  SyncSession-->>Syncer: Return document batches
Loading

Possibly related PRs

Suggested labels: go

Poem

A rabbit checks each timestamp bright,
Then streams rows through day and night.
MySQL and PostgreSQL align,
Sync logs store time in flexible design.
Batches end when sessions close—
The rabbit nods, and onward goes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says "As title" and does not provide the required summary or background context for reviewers. Replace "As title" with a brief summary of the connector changes, their purpose, and relevant background context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change by identifying the addition of MySQL and PostgreSQL connectors to the Go syncer.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (2)
internal/syncer/connector/rdbms_test.go (2)

72-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the generated DSN in the fixture.

The stub discards dsn, so no test covers RDBMSConnector.open. The MySQL DSN options (charset=utf8mb4, parseTime, loc=UTC) and the PostgreSQL URL escaping of the user name, password, and database are both unverified. Capture the DSN and assert it in at least one MySQL test and one PostgreSQL test.

♻️ Proposed fixture change
-	connector.openDB = func(dsn string) (*sql.DB, error) {
-		return db, nil
-	}
+	connector.openDB = func(dsn string) (*sql.DB, error) {
+		lastDSN = dsn
+		return db, nil
+	}

Return the captured value from the helper, or accept a *string out-parameter, so individual tests can assert it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms_test.go` around lines 72 - 74, Update the
RDBMS connector test fixture around the openDB stub to capture the generated dsn
instead of discarding it, expose that value to individual tests, and assert it
in at least one MySQL test and one PostgreSQL test. Verify the MySQL options
charset=utf8mb4, parseTime, and loc=UTC, plus URL escaping for the PostgreSQL
user name, password, and database.

302-325: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a coverage case for the connection-probe failure.

The comment states that the test verifies "failure paths", but the test only covers the missing-user-name branch. The probe failure at rdbms.go lines 132-134 wraps the driver error with the dialect display name, and no test exercises it. Add a case that uses mock.ExpectQuery("SELECT 1").WillReturnError(...) and asserts the wrapped message.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms_test.go` around lines 302 - 325, Extend
TestRDBMSConnectorValidate with a separate fixture whose SELECT 1 expectation
uses WillReturnError, then call Validate and assert the error includes both the
injected driver error and the dialect display name. Keep the existing successful
probe and missing-username cases unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@go.mod`:
- Around line 150-153: Update the github.com/jackc/pgx/v5 entry in go.mod to
remove the // indirect marker because internal/syncer/connector/rdbms.go
directly blank-imports its stdlib package; leave the pgpassfile, pgservicefile,
and puddle entries marked indirect.

In `@internal/entity/flexible_time_test.go`:
- Line 25: Update the relevant FlexibleTime scan test case to pass
[]byte("2026-08-12 15:32:12.99303409") so the byte-string path is exercised, and
remove or correct the stale comments at the test and value assertions to
accurately describe native time.Time behavior.

In `@internal/syncer/connector/rdbms.go`:
- Around line 252-283: The RDBMS connector interpolates unvalidated identifiers
into SQL. In internal/syncer/connector/rdbms.go lines 252-283, add and use
quoteRDBMSIdentifier for timestampColumn, idColumn, and every contentColumns
entry, applying dialect-specific quoting and rejecting invalid names in
Validate; in lines 227-230, also quote each discovered table name in the SELECT
construction. No direct changes are required outside these two sites.
- Around line 564-573: Add targeted //nolint:rowserrcheck directives with brief
reasons to both openNextQuery methods, covering the assignments where
QueryContext returns *sql.Rows stored in the session field; do not alter the
existing rows.Err checks or broader linter configuration.
- Around line 523-525: Clamp non-positive batch sizes to defaultRDBMSBatchSize
before constructing either session: update OpenSync at
internal/syncer/connector/rdbms.go#L523-L525 to pass the clamped value into
rdbmsSyncSession, and apply the same change in OpenPrune at
internal/syncer/connector/rdbms.go#L593-L595 for rdbmsPruneSession. Preserve
configured positive batch sizes.

---

Nitpick comments:
In `@internal/syncer/connector/rdbms_test.go`:
- Around line 72-74: Update the RDBMS connector test fixture around the openDB
stub to capture the generated dsn instead of discarding it, expose that value to
individual tests, and assert it in at least one MySQL test and one PostgreSQL
test. Verify the MySQL options charset=utf8mb4, parseTime, and loc=UTC, plus URL
escaping for the PostgreSQL user name, password, and database.
- Around line 302-325: Extend TestRDBMSConnectorValidate with a separate fixture
whose SELECT 1 expectation uses WillReturnError, then call Validate and assert
the error includes both the injected driver error and the dialect display name.
Keep the existing successful probe and missing-username cases unchanged.
🪄 Autofix

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 Plus

Run ID: 34978190-dcb1-41a2-8276-d19aa3feee51

📥 Commits

Reviewing files that changed from the base of the PR and between 9cece9c and da6fe7f.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (10)
  • go.mod
  • internal/dao/connector.go
  • internal/dao/sync_task.go
  • internal/entity/connector.go
  • internal/entity/flexible_time.go
  • internal/entity/flexible_time_test.go
  • internal/syncer/connector/rdbms.go
  • internal/syncer/connector/rdbms_test.go
  • internal/syncer/sync_runner.go
  • internal/syncer/syncer.go

Comment thread go.mod Resolved
Comment thread internal/entity/flexible_time_test.go Resolved
Comment thread internal/syncer/connector/rdbms.go Outdated
Comment on lines +252 to +283
func (c *RDBMSConnector) buildTimeFilteredQuery(base string, start, end *time.Time) string {
conditions := []string{}
if start != nil {
conditions = append(conditions, fmt.Sprintf("ragflow_src.%s >= %s", c.timestampColumn, formatRDBMSDatetime(c.dbType, *start)))
}
if end != nil {
conditions = append(conditions, fmt.Sprintf("ragflow_src.%s <= %s", c.timestampColumn, formatRDBMSDatetime(c.dbType, *end)))
}
query := c.wrapQuery(base)
if len(conditions) > 0 {
query = query + " WHERE " + strings.Join(conditions, " AND ")
}
return query
}

// buildSlimQuery selects only the columns needed to identify documents.
func (c *RDBMSConnector) buildSlimQuery(base string) string {
columns := []string{}
if c.idColumn != "" {
columns = []string{c.idColumn}
} else {
columns = c.contentColumns
}
if len(columns) == 0 {
return c.wrapQuery(base)
}
selects := make([]string, 0, len(columns))
for _, column := range columns {
selects = append(selects, fmt.Sprintf("ragflow_src.%s", column))
}
return fmt.Sprintf("SELECT %s FROM (%s) AS ragflow_src", strings.Join(selects, ", "), stripRDBMSOrderBy(base))
}

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Unquoted SQL identifiers in internal/syncer/connector/rdbms.go. The connector builds every identifier by raw string interpolation with no validation and no dialect quoting. Add one quoteRDBMSIdentifier(dbType, name) helper that rejects names outside a strict pattern and applies backticks for MySQL or double quotes for PostgreSQL, then route all identifier interpolation through it.

  • internal/syncer/connector/rdbms.go#L252-L283: validate and quote c.timestampColumn, c.idColumn, and each entry of c.contentColumns before you build the predicate and the slim SELECT list; reject invalid names in Validate.
  • internal/syncer/connector/rdbms.go#L227-L230: quote each discovered table name in fmt.Sprintf("SELECT * FROM %s", table) so mixed-case and reserved-word PostgreSQL tables resolve correctly.
📍 Affects 1 file
  • internal/syncer/connector/rdbms.go#L252-L283 (this comment)
  • internal/syncer/connector/rdbms.go#L227-L230
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms.go` around lines 252 - 283, The RDBMS
connector interpolates unvalidated identifiers into SQL. In
internal/syncer/connector/rdbms.go lines 252-283, add and use
quoteRDBMSIdentifier for timestampColumn, idColumn, and every contentColumns
entry, applying dialect-specific quoting and rejecting invalid names in
Validate; in lines 227-230, also quote each discovered table name in the SELECT
construction. No direct changes are required outside these two sites.

Comment thread internal/syncer/connector/rdbms.go Outdated
Comment on lines +523 to +525
func (s *rdbmsSyncSession) NextBatch(ctx context.Context) (SyncBatch, error) {
documents := make([]SourceDocument, 0, s.batchSize)
for len(documents) < s.batchSize {

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Non-positive batchSize produces a non-terminating session in internal/syncer/connector/rdbms.go. Validate rejects batchSize <= 0, but OpenSync and OpenPrune never call Validate, so a batch_size of 0 reaches both sessions. Both NextBatch loops then skip the body, return an empty batch with a nil error, and never return io.EOF. Clamp the value to defaultRDBMSBatchSize in OpenSync and OpenPrune before you construct the session.

  • internal/syncer/connector/rdbms.go#L523-L525: pass a clamped batch size into rdbmsSyncSession so the loop condition at line 525 can hold.
  • internal/syncer/connector/rdbms.go#L593-L595: pass the same clamped value into rdbmsPruneSession, because an empty prune snapshot can also drive incorrect deletions downstream.
📍 Affects 1 file
  • internal/syncer/connector/rdbms.go#L523-L525 (this comment)
  • internal/syncer/connector/rdbms.go#L593-L595
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms.go` around lines 523 - 525, Clamp
non-positive batch sizes to defaultRDBMSBatchSize before constructing either
session: update OpenSync at internal/syncer/connector/rdbms.go#L523-L525 to pass
the clamped value into rdbmsSyncSession, and apply the same change in OpenPrune
at internal/syncer/connector/rdbms.go#L593-L595 for rdbmsPruneSession. Preserve
configured positive batch sizes.

Comment thread internal/syncer/connector/rdbms.go Outdated
Comment on lines +564 to +573
func (s *rdbmsSyncSession) openNextQuery(ctx context.Context) error {
query := s.queries[s.queryIndex]
s.queryIndex++
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return fmt.Errorf("RDBMS query failed: %w", err)
}
s.rows = rows
return nil
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Resolve the rowserrcheck errors that fail the lint job.

golangci-lint reports rows.Err must be checked at line 567 and line 634. The code does check s.rows.Err() at line 538 and line 608, but the linter cannot follow the *sql.Rows value through the struct field, so this is a linter limitation rather than a defect. The finding is still reported at error level and blocks the pipeline. Add a targeted //nolint:rowserrcheck directive with a short reason on both openNextQuery methods, or exclude the linter for this file in the golangci-lint configuration.

🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 567-567: rows.Err must be checked

(rowserrcheck)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms.go` around lines 564 - 573, Add targeted
//nolint:rowserrcheck directives with brief reasons to both openNextQuery
methods, covering the assignments where QueryContext returns *sql.Rows stored in
the session field; do not alter the existing rows.Err checks or broader linter
configuration.

Source: Linters/SAST tools

@Haruko386 Haruko386 added the ci Continue Integration label Aug 12, 2026
@mkaaad
mkaaad force-pushed the feat/connector-go-migration branch from da6fe7f to 8d7b18f Compare August 12, 2026 08:32
The Python backend declares poll_range_start/end as DateTimeTzField over
varchar(255) and persists ISO strings, while the Go SyncLogs entity used
*time.Time, so every sync task failed with a scan error. Introduce
FlexibleTime (sql.Scanner/driver.Valuer) that parses both native times
and Python ISO strings, and pin the gorm tag to type:varchar(255) so
AutoMigrate leaves the shared schema untouched.
@mkaaad
mkaaad force-pushed the feat/connector-go-migration branch from d131da9 to 8747f1b Compare August 12, 2026 09:38

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/entity/flexible_time_test.go (1)

54-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test nil scanning after a prior value.

The current test scans nil into a zero-value FlexibleTime. It does not verify that Scan(nil) clears an existing timestamp. Initialize none before the nil scan, then assert that none.Time() is zero.

As per coding guidelines, “Preserve still-valid behavior with focused tests.”

Proposed test update
 var none FlexibleTime
+if err := none.Scan(time.Date(2026, 7, 1, 8, 0, 0, 0, time.UTC)); err != nil {
+	t.Fatalf("initialize value: %v", err)
+}
 if err := none.Scan(nil); err != nil {
 	t.Fatalf("scan nil: %v", err)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/flexible_time_test.go` around lines 54 - 60, Update the
nil-scanning test for FlexibleTime so the none variable is first populated with
a non-zero timestamp, then call Scan(nil) and retain the assertion that
none.Time() is zero. Keep the existing error assertion and focus the test on
clearing a previously stored value.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/entity/flexible_time_test.go`:
- Around line 54-60: Update the nil-scanning test for FlexibleTime so the none
variable is first populated with a non-zero timestamp, then call Scan(nil) and
retain the assertion that none.Time() is zero. Keep the existing error assertion
and focus the test on clearing a previously stored value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6eb9b354-fbb2-4c2a-ac77-d1e1e15be1b0

📥 Commits

Reviewing files that changed from the base of the PR and between da6fe7f and 121a86d.

📒 Files selected for processing (2)
  • internal/entity/connector.go
  • internal/entity/flexible_time_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/connector.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
internal/syncer/connector/rdbms.go (1)

401-401: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the always-true bool return.

rowToSourceDocument returns true on every path. The ok branch at Line 550 is dead. Return only SourceDocument.

♻️ Proposed simplification
-func (c *RDBMSConnector) rowToSourceDocument(row map[string]any, orderedColumns []string) (SourceDocument, bool) {
+func (c *RDBMSConnector) rowToSourceDocument(row map[string]any, orderedColumns []string) SourceDocument {
-	}, true
+	}
-		if doc, ok := s.connector.rowToSourceDocument(row, columns); ok {
-			documents = append(documents, doc)
-		}
+		documents = append(documents, s.connector.rowToSourceDocument(row, columns))

Also applies to: 550-552

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms.go` at line 401, Update
RDBMSConnector.rowToSourceDocument to return only SourceDocument, removing the
always-true bool result and any corresponding return values. Adjust its callers,
including the handling around the current ok branch near the function’s use, to
stop checking the dead boolean while preserving the existing document-processing
behavior.
internal/syncer/connector/rdbms_test.go (2)

522-524: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the missing-username cause as well.

The assertion accepts any error text that contains "postgresql". A connection error would also pass. Add the "username" substring check that the MySQL test uses at Line 322.

💚 Proposed change
-	if err := missing.Validate(context.Background()); err == nil || !strings.Contains(err.Error(), "postgresql") {
+	err := missing.Validate(context.Background())
+	if err == nil || !strings.Contains(err.Error(), "postgresql") || !strings.Contains(err.Error(), "username") {
 		t.Fatalf("Validate error = %v", err)
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms_test.go` around lines 522 - 524, Strengthen
the Validate assertion for the missing PostgreSQL username case in the
missing.Validate test by requiring the error text to contain both “postgresql”
and “username”, matching the MySQL test’s checks and rejecting unrelated
connection errors.

72-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Capture the DSN to cover open().

The stub discards dsn, so no test covers the DSN that open() builds. The PostgreSQL branch escapes the database name and encodes credentials in a URL, and the MySQL branch sets charset, ParseTime, and Loc. Record the DSN in the fixture and assert it in the PostgreSQL and MySQL tests.

♻️ Proposed change
-	connector.openDB = func(dsn string) (*sql.DB, error) {
-		return db, nil
-	}
+	connector.openDB = func(dsn string) (*sql.DB, error) {
+		lastDSN = dsn
+		return db, nil
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms_test.go` around lines 72 - 74, Update the
test fixture around connector.openDB to record the provided dsn, then assert the
captured DSN in both PostgreSQL and MySQL tests. Verify PostgreSQL escaping and
URL-encoded credentials, and verify MySQL includes charset, ParseTime, and Loc
parameters while preserving the existing open() behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/syncer/connector/rdbms.go`:
- Around line 50-56: Update the RDBMSConnector type documentation to describe
importing rows from both MySQL and PostgreSQL, reflecting the dialects exposed
by NewRDBMSConnector and NewPostgreSQLConnector; remove the MySQL-only wording
while preserving the remaining behavior description.
- Around line 180-200: Update RDBMSConnector configuration and its open method
to require encrypted connections for both PostgreSQL and MySQL. Add explicit
PostgreSQL sslmode=require to the DSN and configure the MySQL driver with TLS
enabled using its supported TLS configuration, preserving existing connection
settings.

---

Nitpick comments:
In `@internal/syncer/connector/rdbms_test.go`:
- Around line 522-524: Strengthen the Validate assertion for the missing
PostgreSQL username case in the missing.Validate test by requiring the error
text to contain both “postgresql” and “username”, matching the MySQL test’s
checks and rejecting unrelated connection errors.
- Around line 72-74: Update the test fixture around connector.openDB to record
the provided dsn, then assert the captured DSN in both PostgreSQL and MySQL
tests. Verify PostgreSQL escaping and URL-encoded credentials, and verify MySQL
includes charset, ParseTime, and Loc parameters while preserving the existing
open() behavior.

In `@internal/syncer/connector/rdbms.go`:
- Line 401: Update RDBMSConnector.rowToSourceDocument to return only
SourceDocument, removing the always-true bool result and any corresponding
return values. Adjust its callers, including the handling around the current ok
branch near the function’s use, to stop checking the dead boolean while
preserving the existing document-processing behavior.
🪄 Autofix

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 Plus

Run ID: 8291f7e4-a8c8-4c46-bf93-cf5c75d85d5f

📥 Commits

Reviewing files that changed from the base of the PR and between c677e9a and 121a86d.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (10)
  • go.mod
  • internal/dao/connector.go
  • internal/dao/sync_task.go
  • internal/entity/connector.go
  • internal/entity/flexible_time.go
  • internal/entity/flexible_time_test.go
  • internal/syncer/connector/rdbms.go
  • internal/syncer/connector/rdbms_test.go
  • internal/syncer/sync_runner.go
  • internal/syncer/syncer.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/entity/connector.go
  • internal/dao/sync_task.go
  • internal/syncer/syncer.go
  • go.mod
  • internal/dao/connector.go
  • internal/syncer/sync_runner.go
  • internal/entity/flexible_time_test.go
  • internal/entity/flexible_time.go

Comment thread internal/syncer/connector/rdbms.go Outdated
Comment on lines +50 to +56
// RDBMSConnector imports MySQL rows as documents.
//
// It mirrors the Python RDBMSConnector: a custom SQL query runs verbatim,
// otherwise every table is loaded. Rows become documents whose content is
// built from the configured content columns (or every column), the id column
// (or an MD5 of the content) forms the stable document id, and the timestamp
// column drives incremental sync and the document update time.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update the type doc comment for both dialects.

The comment states the connector imports MySQL rows. The type now serves MySQL and PostgreSQL through NewRDBMSConnector and NewPostgreSQLConnector.

📝 Proposed doc update
-// RDBMSConnector imports MySQL rows as documents.
+// RDBMSConnector imports MySQL or PostgreSQL rows as documents.

As per coding guidelines: "keep package and doc comments aligned with the current runtime path rather than migration history".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// RDBMSConnector imports MySQL rows as documents.
//
// It mirrors the Python RDBMSConnector: a custom SQL query runs verbatim,
// otherwise every table is loaded. Rows become documents whose content is
// built from the configured content columns (or every column), the id column
// (or an MD5 of the content) forms the stable document id, and the timestamp
// column drives incremental sync and the document update time.
// RDBMSConnector imports MySQL or PostgreSQL rows as documents.
//
// It mirrors the Python RDBMSConnector: a custom SQL query runs verbatim,
// otherwise every table is loaded. Rows become documents whose content is
// built from the configured content columns (or every column), the id column
// (or an MD5 of the content) forms the stable document id, and the timestamp
// column drives incremental sync and the document update time.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms.go` around lines 50 - 56, Update the
RDBMSConnector type documentation to describe importing rows from both MySQL and
PostgreSQL, reflecting the dialects exposed by NewRDBMSConnector and
NewPostgreSQLConnector; remove the MySQL-only wording while preserving the
remaining behavior description.

Source: Coding guidelines

Comment thread internal/syncer/connector/rdbms.go Outdated
Comment on lines +180 to +200
func (c *RDBMSConnector) open() (*sql.DB, error) {
if c.dbType == rdbmsTypePostgreSQL {
dsn := url.URL{
Scheme: "postgres",
User: url.UserPassword(c.username, c.password),
Host: fmt.Sprintf("%s:%d", c.host, c.port),
Path: "/" + url.PathEscape(c.database),
}
return c.openDB(dsn.String())
}
cfg := mysql.NewConfig()
cfg.User = c.username
cfg.Passwd = c.password
cfg.Net = "tcp"
cfg.Addr = fmt.Sprintf("%s:%d", c.host, c.port)
cfg.DBName = c.database
cfg.Params = map[string]string{"charset": "utf8mb4"}
cfg.ParseTime = true
cfg.Loc = time.UTC
return c.openDB(cfg.FormatDSN())
}

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find the Python RDBMS connector and inspect its connection settings.
fd -t f . --full-path -e py | xargs rg -n -C5 'RDBMSConnector|sslmode|ssl_mode|pymysql\.connect|psycopg' 2>/dev/null | head -100

Repository: infiniflow/ragflow

Length of output: 7470


🏁 Script executed:

#!/bin/bash
# Inspect the Python connection calls, the Go driver versions, and all RDBMS DSN construction.
printf '%s\n' '--- Python connector ---'
sed -n '130,205p' common/data_source/rdbms_connector.py
printf '%s\n' '--- Go module dependencies ---'
rg -n -C2 'lib/pq|go-sql-driver/mysql|mysql|postgres' go.mod go.sum 2>/dev/null | head -80
printf '%s\n' '--- Go connector references ---'
rg -n -C4 'openDB|rdbmsTypePostgreSQL|mysql.NewConfig|sslmode|TLS|tls' internal/syncer/connector internal 2>/dev/null | head -180

Repository: infiniflow/ragflow

Length of output: 17448


🌐 Web query:

pgx v5 PostgreSQL connection string default sslmode prefer plaintext fallback

💡 Result:

In pgx v5, the default sslmode is prefer [1][2][3]. This mode follows the standard libpq behavior, which attempts to establish an encrypted TLS connection first [1][2][3]. If the server does not support TLS or if the handshake fails, pgx will automatically attempt to establish a plaintext connection as a fallback [1][2][3]. Because this behavior involves a silent fallback to unencrypted communication, it is vulnerable to man-in-the-middle (MITM) attacks where an attacker could intercept the initial SSL request and force the client to downgrade to a plaintext connection to capture credentials [4]. To avoid this behavior and ensure encrypted connections, you should explicitly set sslmode to one of the following in your connection string: - verify-full: Ensures the connection is encrypted and verifies the server certificate against a trusted CA, matching the server's hostname. - verify-ca: Ensures the connection is encrypted and verifies the server certificate against a trusted CA. - require: Ensures the connection is encrypted (though it does not perform full certificate validation unless combined with specific CA settings) [2][3]. Example of an enforced TLS connection string: postgres://user:password@localhost:5432/dbname?sslmode=verify-full&sslrootcert=/path/to/ca.crt

Citations:


🌐 Web query:

go-sql-driver/mysql v1.7.0 default TLS configuration DSN tls parameter

💡 Result:

In the go-sql-driver/mysql driver version 1.7.0, the default value for the tls Data Source Name (DSN) parameter is false [1][2]. This means that by default, the driver does not enable TLS/SSL encrypted connections [1][2]. The tls parameter accepts the following values: - true: Enables TLS/SSL encrypted connection to the server [1][2]. - false: Disables TLS/SSL encryption [1][2]. - skip-verify: Enables TLS/SSL but skips certificate verification (useful for self-signed or invalid certificates) [1][2]. - preferred: Attempts to use TLS if the server advertises it, with a fallback to an unencrypted connection [1][2]. - : Uses a custom TLS configuration previously registered with mysql.RegisterTLSConfig [1][2][3]. Because the default is false, all connections are unencrypted unless explicitly configured otherwise via the DSN string [1][2]. Note that using skip-verify or preferred does not provide reliable security as they allow unencrypted connections or unverified server identities [1][2]. If you require secure connections, you should explicitly set tls=true or use a registered custom TLS configuration [1][2].

Citations:


Require explicit TLS settings for both database drivers.

pgx defaults to sslmode=prefer and can fall back to plaintext. go-sql-driver/mysql defaults to tls=false and uses plaintext. Add TLS settings to the connector configuration and require encrypted connections by default.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/rdbms.go` around lines 180 - 200, Update
RDBMSConnector configuration and its open method to require encrypted
connections for both PostgreSQL and MySQL. Add explicit PostgreSQL
sslmode=require to the DSN and configure the MySQL driver with TLS enabled using
its supported TLS configuration, preserving existing connection settings.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Aug 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/syncer/connector/mysql.go (1)

203-216: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Quote or validate SQL identifiers before interpolation.

c.timestampColumn, c.idColumn, and c.contentColumns come from connector config and are concatenated into SQL. A column value such as id FROM users; -- changes the statement. Case-sensitive or reserved-word column names also break without backticks.

Validate each identifier against ^[A-Za-z_][A-Za-z0-9_$]*$ and wrap it in backticks with internal backticks escaped. The same fix applies to the table names built in baseQueries (Line 180).

🔒 Proposed identifier quoting helper
// quoteMySQLIdentifier validates and quotes a SQL identifier.
func quoteMySQLIdentifier(name string) (string, error) {
	if name == "" || strings.ContainsAny(name, "`\x00") {
		return "", fmt.Errorf("invalid identifier: %q", name)
	}
	return "`" + name + "`", nil
}

Also applies to: 219-233

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql.go` around lines 203 - 216, Update
MySQLConnector query construction, including buildTimeFilteredQuery and
baseQueries, to validate configured table and column identifiers against the
allowed identifier pattern and quote them as escaped MySQL backtick identifiers
before interpolation. Apply this consistently to timestampColumn, idColumn,
contentColumns, and all configured table names; propagate an error when
validation fails rather than generating SQL.
🧹 Nitpick comments (8)
internal/syncer/connector/mysql.go (4)

491-495: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Row scan failures are silently dropped and can loop.

NextBatch discards the scanRow error without a log. A persistent scan failure, for example a type the driver cannot map, produces a silent data loss. Log the error at warn level with the query index. The continue is safe because rows.Next() advances, but the failure stays invisible.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql.go` around lines 491 - 495, Update the
scanRow error branch in NextBatch to log the failure at warn level before
continuing, including the query index and error details; preserve the existing
continue behavior so rows.Next() advances.

59-79: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

NewMySQLConnector never returns a non-nil error.

The function always returns nil for the error. Every caller must still handle it. Keep the signature if the registry requires a uniform constructor shape. Otherwise drop the error return, or validate required fields here and return a real error.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql.go` around lines 59 - 79, Update
NewMySQLConnector so it no longer unconditionally returns a nil error: either
remove the error return and adjust its callers if the registry permits, or
validate required configuration fields and return a meaningful error when
validation fails while preserving the constructor signature.

334-343: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

MD5 use here is an identity hash, not a security control.

The static analysis hint flags md5.Sum at Line 341. The digest builds a stable document id for Python parity. It is not an integrity or authentication check. Keep MD5 to preserve id compatibility with the Python connector. Add a short comment or a //nolint:gosec directive so future scans do not re-open this.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql.go` around lines 334 - 343, Add a brief
comment or targeted //nolint:gosec directive at the md5.Sum call in
MySQLConnector.buildDocumentID, documenting that MD5 is used only for stable
document identity and Python connector compatibility, not security. Preserve the
existing hash algorithm and generated ID format.

Source: Linters/SAST tools


260-279: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Hoist rows.Columns() out of the per-row path.

scanRow calls rows.Columns() and allocates two slices for every row. The column list is constant for one result set. Resolve the columns once when the query opens, then reuse them in the batch loop.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql.go` around lines 260 - 279, Resolve the
column names once when the query opens, then pass or reuse that result through
the batch loop instead of calling rows.Columns() inside MySQLConnector.scanRow.
Update scanRow to accept the existing columns and only allocate/scan row values,
preserving the current normalization and error behavior.
internal/syncer/connector/mysql_test.go (2)

292-314: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a coverage case for the failed SELECT 1 probe.

TestMySQLConnectorValidate covers the success path and the missing-username path. It does not cover the probe failure at Line 104 of internal/syncer/connector/mysql.go. Add a case with mock.ExpectQuery("SELECT 1").WillReturnError(...) and assert the wrapped message Failed to connect to MySQL.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql_test.go` around lines 292 - 314, Extend
TestMySQLConnectorValidate with a connector whose sqlmock expectation for SELECT
1 returns an error, then call Validate and assert it fails with an error
containing “Failed to connect to MySQL.” Preserve the existing success and
missing-username cases.

34-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The fixture ignores the DSN, so DSN construction stays untested.

connector.openDB discards the dsn argument. No test asserts the MySQL DSN produced by open(). The DSN sets charset=utf8mb4, parseTime=true, and loc=UTC, and those settings decide whether timestamp columns arrive as time.Time. Capture the DSN in the fixture and assert it in one test.

🧪 Proposed DSN capture
-	connector.openDB = func(dsn string) (*sql.DB, error) {
-		return db, nil
-	}
+	connector.openDB = func(dsn string) (*sql.DB, error) {
+		lastDSN = dsn
+		return db, nil
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/mysql_test.go` around lines 34 - 68, Update
newFixtureMySQLConnector and a test exercising open() to capture the dsn passed
to connector.openDB and assert it includes the expected MySQL parameters
charset=utf8mb4, parseTime=true, and loc=UTC. Keep the existing sqlmock behavior
while ensuring DSN construction is verified.
internal/syncer/connector/postgresql_test.go (2)

210-242: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The prune test omits the EOF assertion.

TestMySQLConnectorOpenPrune asserts that the second NextBatch call returns io.EOF. This test stops after the first batch. Add the same assertion so the PostgreSQL prune session termination is covered.

🧪 Proposed addition
 		t.Fatalf("slim documents = %+v", batch.Documents)
 	}
+	if _, err = session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {
+		t.Fatalf("NextBatch EOF = %v", err)
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/postgresql_test.go` around lines 210 - 242, Extend
TestPostgreSQLConnectorOpenPrune after validating the first batch by calling
session.NextBatch again and asserting that it returns io.EOF, matching the
termination check in TestMySQLConnectorOpenPrune.

33-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

PostgreSQLConnector.sanitizeQuery, stripOrderBy, and the MD5 fallback id have no tests.

mysql_test.go covers those three behaviors. PostgreSQLConnector declares its own copies of the methods, so the MySQL tests do not exercise them. Add the equivalent PostgreSQL cases, or consolidate the shared helpers so one test suite covers both connectors.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/postgresql_test.go` around lines 33 - 67, Add
PostgreSQL-specific tests for PostgreSQLConnector.sanitizeQuery, stripOrderBy,
and the MD5 fallback ID, mirroring the existing MySQL cases and using
newFixturePostgresConnector where database setup is needed. Alternatively,
consolidate the duplicated helpers so the existing shared test suite exercises
both connectors, while preserving each connector’s current behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/syncer/connector/postgresql.go`:
- Around line 299-459: The PostgreSQL and MySQL connectors duplicate shared
RDBMS behavior. Add one unexported embedded rdbmsConnector implementing the
listed row, query, value, and SQL helpers, with a small dialect interface for
table discovery, datetime formatting, and ID prefixes; update
internal/syncer/connector/postgresql.go:299-459 and
internal/syncer/connector/mysql.go:297-457 to embed it and remove duplicate
methods. Replace mysqlSyncSession/mysqlPruneSession at
internal/syncer/connector/mysql.go:459-594 and
postgresSyncSession/postgresPruneSession at
internal/syncer/connector/postgresql.go:461-596 with shared sessions accepting
the dialect error prefix. Make internal/syncer/connector/mysql_test.go:34-68 and
internal/syncer/connector/postgresql_test.go:33-67 use one shared sqlmock
fixture builder, retaining only thin dialect-specific wrappers.
- Around line 146-154: Update PostgreSQLConnector configuration and open to
append query parameters for connector-controlled sslmode and connect_timeout.
Default sslmode to prefer or a stronger mode and set a finite connection
timeout, preserving the existing URL-encoded credentials, host, port, and
database construction.
- Around line 161-181: Update the table-query generation in the discovered-table
flow to schema-qualify every name with public and quote identifiers, escaping
embedded double quotes before constructing each SELECT statement. Preserve the
existing table discovery behavior and add a focused test covering a mixed-case
table name.

---

Outside diff comments:
In `@internal/syncer/connector/mysql.go`:
- Around line 203-216: Update MySQLConnector query construction, including
buildTimeFilteredQuery and baseQueries, to validate configured table and column
identifiers against the allowed identifier pattern and quote them as escaped
MySQL backtick identifiers before interpolation. Apply this consistently to
timestampColumn, idColumn, contentColumns, and all configured table names;
propagate an error when validation fails rather than generating SQL.

---

Nitpick comments:
In `@internal/syncer/connector/mysql_test.go`:
- Around line 292-314: Extend TestMySQLConnectorValidate with a connector whose
sqlmock expectation for SELECT 1 returns an error, then call Validate and assert
it fails with an error containing “Failed to connect to MySQL.” Preserve the
existing success and missing-username cases.
- Around line 34-68: Update newFixtureMySQLConnector and a test exercising
open() to capture the dsn passed to connector.openDB and assert it includes the
expected MySQL parameters charset=utf8mb4, parseTime=true, and loc=UTC. Keep the
existing sqlmock behavior while ensuring DSN construction is verified.

In `@internal/syncer/connector/mysql.go`:
- Around line 491-495: Update the scanRow error branch in NextBatch to log the
failure at warn level before continuing, including the query index and error
details; preserve the existing continue behavior so rows.Next() advances.
- Around line 59-79: Update NewMySQLConnector so it no longer unconditionally
returns a nil error: either remove the error return and adjust its callers if
the registry permits, or validate required configuration fields and return a
meaningful error when validation fails while preserving the constructor
signature.
- Around line 334-343: Add a brief comment or targeted //nolint:gosec directive
at the md5.Sum call in MySQLConnector.buildDocumentID, documenting that MD5 is
used only for stable document identity and Python connector compatibility, not
security. Preserve the existing hash algorithm and generated ID format.
- Around line 260-279: Resolve the column names once when the query opens, then
pass or reuse that result through the batch loop instead of calling
rows.Columns() inside MySQLConnector.scanRow. Update scanRow to accept the
existing columns and only allocate/scan row values, preserving the current
normalization and error behavior.

In `@internal/syncer/connector/postgresql_test.go`:
- Around line 210-242: Extend TestPostgreSQLConnectorOpenPrune after validating
the first batch by calling session.NextBatch again and asserting that it returns
io.EOF, matching the termination check in TestMySQLConnectorOpenPrune.
- Around line 33-67: Add PostgreSQL-specific tests for
PostgreSQLConnector.sanitizeQuery, stripOrderBy, and the MD5 fallback ID,
mirroring the existing MySQL cases and using newFixturePostgresConnector where
database setup is needed. Alternatively, consolidate the duplicated helpers so
the existing shared test suite exercises both connectors, while preserving each
connector’s current behavior.
🪄 Autofix

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 Plus

Run ID: 5450d239-d87e-40fe-bfd1-0d87fa09fe1c

📥 Commits

Reviewing files that changed from the base of the PR and between 121a86d and 3c58c2f.

📒 Files selected for processing (5)
  • internal/syncer/connector/mysql.go
  • internal/syncer/connector/mysql_test.go
  • internal/syncer/connector/postgresql.go
  • internal/syncer/connector/postgresql_test.go
  • internal/syncer/syncer.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/syncer/syncer.go

Comment thread internal/syncer/connector/postgresql.go Resolved
Comment thread internal/syncer/connector/postgresql.go Resolved
Comment thread internal/syncer/connector/postgresql.go Resolved
mkaaad added 4 commits August 12, 2026 18:52
The metadata DSN renders time.Time in the local zone, so writing native
time values into the varchar poll_range columns produced tz-less local
strings that were re-parsed as UTC, skewing the incremental window by the
local offset on every sync. Serialize through FlexibleTime as UTC ISO
with a +00:00 offset, byte-compatible with Python's DateTimeTzField.
Append connector-controlled sslmode (default prefer) and a finite
connect_timeout to the connection URL so an unreachable host cannot hang a
sync worker, and schema-qualify with quoting of catalog-discovered table
names so mixed-case tables resolve correctly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/syncer/connector/postgresql_test.go`:
- Around line 251-281: Update the PostgreSQL connector’s DSN construction to
assign the database URL Path directly as "/" plus c.database, avoiding an extra
escaping pass. Extend the existing connector.open DSN test to use a database
containing a slash and assert parsed.Path equals "/my/db", while preserving the
current host and credential assertions.
🪄 Autofix

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 Plus

Run ID: ae2a26d2-f9d7-410a-87a6-812be364638a

📥 Commits

Reviewing files that changed from the base of the PR and between 10b1d3f and 4b436d5.

📒 Files selected for processing (2)
  • internal/syncer/connector/postgresql.go
  • internal/syncer/connector/postgresql_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/syncer/connector/postgresql.go

Comment on lines +251 to +281
"database": "mydb",
"credentials": map[string]any{
"username": "postgres",
"password": "p@ss:word",
},
}, nil)
connector.openDB = func(dsn string) (*sql.DB, error) {
captured = dsn
return nil, nil
}
if _, err := connector.open(); err != nil {
t.Fatalf("open failed: %v", err)
}
parsed, err := url.Parse(captured)
if err != nil {
t.Fatalf("parse dsn %q: %v", captured, err)
}
if got := parsed.Query().Get("sslmode"); got != "prefer" {
t.Fatalf("sslmode = %q", got)
}
if got := parsed.Query().Get("connect_timeout"); got != "30" {
t.Fatalf("connect_timeout = %q", got)
}
if parsed.User.Username() != "postgres" {
t.Fatalf("username = %q", parsed.User.Username())
}
if pass, _ := parsed.User.Password(); pass != "p@ss:word" {
t.Fatalf("password = %q", pass)
}
if parsed.Host != "127.0.0.1:5432" || parsed.Path != "/mydb" {
t.Fatalf("host/path = %q %q", parsed.Host, parsed.Path)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline internal/syncer/connector/postgresql.go --match PostgreSQLConnector --view expanded
sed -n '155,176p' internal/syncer/connector/postgresql.go
sed -n '245,283p' internal/syncer/connector/postgresql_test.go

Repository: infiniflow/ragflow

Length of output: 4630


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- dependency and connector context ---'
rg -n 'github.com/lib/pq|pgx|postgres' go.mod go.sum internal/syncer/connector/postgresql.go internal/syncer/connector/postgresql_test.go
sed -n '1,45p' internal/syncer/connector/postgresql.go
sed -n '160,174p' internal/syncer/connector/postgresql.go

printf '%s\n' '--- Go URL behavior ---'
cat >/tmp/url_probe.go <<'EOF'
package main

import (
	"fmt"
	"net/url"
)

func main() {
	for _, database := range []string{"mydb", "my/db", "my%2Fdb"} {
		u := url.URL{Scheme: "postgres", Host: "127.0.0.1:5432", Path: "/" + url.PathEscape(database)}
		raw := u.String()
		parsed, err := url.Parse(raw)
		fmt.Printf("database=%q escaped=%q raw=%q parsed.Path=%q err=%v\n",
			database, u.Path, raw, parsed.Path, err)
	}
}
EOF
go run /tmp/url_probe.go
rm -f /tmp/url_probe.go

Repository: infiniflow/ragflow

Length of output: 6302


🌐 Web query:

github.com/lib/pq parseURL database URL.Path PostgreSQL connection string path percent escape

💡 Result:

The github.com/lib/pq driver does not support percent-encoded characters in the host portion of a PostgreSQL connection URL [1][2]. This limitation exists because the library relies on the Go standard library's net/url package, which performs stricter validation of URLs than the native PostgreSQL libpq parser [1][2]. Specifically, if you attempt to use a percent-encoded path (such as %2F for a slash) to specify a Unix-domain socket in the host part of the URL (e.g., postgres://%2Ftmp%2Fpostgres/dbname), net/url will reject it as an "invalid URL escape" [1][2][3]. To work around this limitation in lib/pq: 1. Avoid using URL-style connection strings for configurations requiring percent-encoded host paths. 2. Instead, use the keyword/value format, where you can specify the host directly without percent-encoding: "host=/tmp/postgres dbname=dbname" [1][2]. While standard PostgreSQL libpq supports percent-encoded paths in URLs to handle non-standard Unix-domain socket directories [4][5], lib/pq explicitly documents that this will not work in the Go driver [1][2].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

gopath="$(go env GOPATH)"
printf '%s\n' "--- pgx module cache ---"
find "$gopath/pkg/mod" -path '*github.com/jackc/pgx*' -maxdepth 8 -type f \
  \( -name '*.go' -o -name 'go.mod' \) 2>/dev/null | head -80

printf '%s\n' '--- pgx URL/database parsing references ---'
rg -n -S 'url.Parse|URL\.Path|dbname|database|ParseConfig|ParseConfigWithOptions' \
  "$gopath/pkg/mod/github.com/jackc/pgx" 2>/dev/null | head -160 || true

Repository: infiniflow/ragflow

Length of output: 6471


🏁 Script executed:

#!/bin/bash
set -euo pipefail

mod=/home/jailuser/go/pkg/mod/github.com/jackc/pgx/[email protected]
printf '%s\n' '--- pgx connection-string parser ---'
rg -l -S 'func ParseConfig|func parseURL|url.Parse|dbname' "$mod" \
  -g '*.go' | sort | head -40

printf '%s\n' '--- relevant parser sections ---'
for f in $(rg -l -S 'func ParseConfig|func parseURL' "$mod" -g '*.go' | head -5); do
  echo "FILE: $f"
  rg -n -A12 -B8 -S 'func ParseConfig|func parseURL|url.Parse|dbname' "$f"
done

Repository: infiniflow/ragflow

Length of output: 10140


🏁 Script executed:

#!/bin/bash
set -euo pipefail

cat >/tmp/pgx_probe.go <<'EOF'
package main

import (
	"fmt"

	"github.com/jackc/pgx/v5/pgconn"
)

func main() {
	for _, dsn := range []string{
		"postgres://127.0.0.1:5432/my%252Fdb",
		"postgres://127.0.0.1:5432/my/db",
		"postgres://127.0.0.1:5432/my%2Fdb",
	} {
		cfg, err := pgconn.ParseConfig(dsn)
		if err != nil {
			fmt.Printf("dsn=%q error=%v\n", dsn, err)
			continue
		}
		fmt.Printf("dsn=%q database=%q\n", dsn, cfg.Database)
	}
}
EOF
go run /tmp/pgx_probe.go
rm -f /tmp/pgx_probe.go

Repository: infiniflow/ragflow

Length of output: 268


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '619,690p' /home/jailuser/go/pkg/mod/github.com/jackc/pgx/[email protected]/pgconn/config.go

Repository: infiniflow/ragflow

Length of output: 2017


Avoid double-escaping the database path.

For database: "my/db", the current code sends my%252Fdb. pgx parses this path as my%2Fdb, so it selects the wrong database. Set Path to "/" + c.database, and assert parsed.Path == "/my/db" in the DSN test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/connector/postgresql_test.go` around lines 251 - 281, Update
the PostgreSQL connector’s DSN construction to assign the database URL Path
directly as "/" plus c.database, avoiding an extra escaping pass. Extend the
existing connector.open DSN test to use a database containing a slash and assert
parsed.Path equals "/my/db", while preserving the current host and credential
assertions.

@JinHai-CN
JinHai-CN merged commit 3ce1b9b into infiniflow:main Aug 13, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants