Skip to content

Conversation

@mdelapenya
Copy link
Member

What does this PR do?

Use the Run function in postgres

Why is it important?

Migrate modules to the new API, improving consistency and leveraging the latest testcontainers functionality.

Related issues

@mdelapenya mdelapenya requested a review from a team as a code owner October 7, 2025 15:48
@mdelapenya mdelapenya added the chore Changes that do not impact the existing functionality label Oct 7, 2025
@netlify
Copy link

netlify bot commented Oct 7, 2025

Deploy Preview for testcontainers-go ready!

Name Link
🔨 Latest commit e966d61
🔍 Latest deploy log https://app.netlify.com/projects/testcontainers-go/deploys/68e53aed1652f0000875081d
😎 Deploy Preview https://deploy-preview-3425--testcontainers-go.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link

coderabbitai bot commented Oct 7, 2025

Summary by CodeRabbit

  • New Features
    • Unified, option-based handling for SSL certificates and custom config files.
  • Refactor
    • Migrated Postgres container options to a new customizer-based API; update integrations using database/user/password and related options.
    • Simplified run flow with environment derived from the container for more reliable initialization.
  • Bug Fixes
    • Clearer, more specific error messages during startup and inspection.

Walkthrough

Refactors Postgres module to use testcontainers.ContainerCustomizer-based options and testcontainers.Run. Updates WithDatabase/WithUsername/WithPassword signatures, reworks Run to compose customizers, adds container inspection to sync env-derived fields, and adapts SSL and config-file helpers to WithFiles/WithEntrypoint/WithCmdArgs flows. Error messages updated.

Changes

Cohort / File(s) Summary
API option signature changes
modules/postgres/postgres.go
WithDatabase, WithUsername, WithPassword now return testcontainers.ContainerCustomizer (via WithEnv) instead of CustomizeRequestOption.
Run flow migration
modules/postgres/postgres.go
Replaces GenericContainerRequest construction with a slice of ContainerCustomizers (Env, ExposedPorts, Cmd) and calls testcontainers.Run; initializes PostgresContainer fields from defaults or inspected env; updates error messages (“run postgres”, “inspect postgres”).
SSL/config handling update
modules/postgres/postgres.go
WithSSLCert uses WithFiles and WithEntrypoint; WithConfigFile uses WithFiles and WithCmdArgs; removes direct mutation of request fields.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant PG as Postgres.Run
  participant TC as testcontainers.Run
  participant D as Docker Daemon
  participant I as Inspect

  C->>PG: Run(ctx, img, opts...)
  PG->>PG: Build moduleOpts (WithEnv, WithExposedPorts, WithCmd, opts...)
  PG->>TC: Run(ctx, img, moduleOpts...)
  TC->>D: Create/Start container
  D-->>TC: Container handle
  TC-->>PG: Container
  PG->>I: Inspect container env
  I-->>PG: Final env (DB, USER, PASSWORD)
  PG->>PG: Update PostgresContainer fields
  PG-->>C: PostgresContainer

  rect rgba(200,255,200,0.2)
  note right of PG: Changed: uses ContainerCustomizer<br/>and post-start inspect
  end

  alt Error starting
    TC-->>PG: error
    PG-->>C: wrap "run postgres" error
  else Error inspecting
    I-->>PG: error
    PG-->>C: wrap "inspect postgres" error
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A bunny taps the docker drum,
New knobs to twist—customizers come.
Env carrots lined in tidy rows,
Inspect the patch, see how it grows.
SSL mittens, config snug,
Hop! Postgres hums—warm rabbit hug. 🐇💾

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title concisely and clearly describes the key change of migrating the Postgres module to use the Run function, aligning with the pull request’s primary objective without extraneous detail.
Description Check ✅ Passed The description directly explains what the PR does and why it matters, outlining the migration to the new API and providing related issue context, which matches the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@mdelapenya mdelapenya force-pushed the use-run-claude-postgres branch from 3c322b3 to e966d61 Compare October 7, 2025 16:08
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

🧹 Nitpick comments (4)
modules/postgres/postgres.go (4)

73-78: Guard against missing base CMD when appending config_file args

WithCmdArgs appends to req.Cmd; if no base cmd is set (used outside Run), the container may start with only flags. Add a safeguard to ensure "postgres" is present.

-        if err := testcontainers.WithFiles(cfgFile)(req); err != nil {
+        if err := testcontainers.WithFiles(cfgFile)(req); err != nil {
           return err
         }
-
-        return testcontainers.WithCmdArgs("-c", "config_file=/etc/postgresql.conf")(req)
+        // Ensure a base command exists before appending args
+        if len(req.Cmd) == 0 {
+          if err := testcontainers.WithCmd("postgres")(req); err != nil {
+            return err
+          }
+        }
+        return testcontainers.WithCmdArgs("-c", "config_file=/etc/postgresql.conf")(req)

84-86: Avoid setting POSTGRES_DB when empty to preserve image defaults

Setting POSTGRES_DB to an empty string overrides the image’s “default to POSTGRES_USER” behavior. Make empty a no‑op.

-func WithDatabase(dbName string) testcontainers.ContainerCustomizer {
-  return testcontainers.WithEnv(map[string]string{"POSTGRES_DB": dbName})
-}
+func WithDatabase(dbName string) testcontainers.ContainerCustomizer {
+  return testcontainers.CustomizeRequestOption(func(req *testcontainers.GenericContainerRequest) error {
+    if dbName == "" {
+      return nil
+    }
+    if req.Env == nil {
+      req.Env = map[string]string{}
+    }
+    req.Env["POSTGRES_DB"] = dbName
+    return nil
+  })
+}

132-137: Trim username to avoid accidental whitespace

Small hardening; keep default fallback.

-func WithUsername(user string) testcontainers.ContainerCustomizer {
-  if user == "" {
+func WithUsername(user string) testcontainers.ContainerCustomizer {
+  user = strings.TrimSpace(user)
+  if user == "" {
     user = defaultUser
   }
   return testcontainers.WithEnv(map[string]string{"POSTGRES_USER": user})
 }

235-261: Tighten TLS file permissions and script mode

  • CA & server cert: set FileMode to 0o644 instead of defaultPermission (0o600)
  • Server key: keep defaultPermission (0o600)
  • Entrypoint script: set FileMode to 0o755
  • Entrypoint already delegates to /usr/local/bin/docker-entrypoint.sh "$@"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86bebae and e966d61.

📒 Files selected for processing (1)
  • modules/postgres/postgres.go (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
modules/postgres/postgres.go (3)
options.go (7)
  • WithFiles (524-529)
  • WithCmdArgs (470-475)
  • ContainerCustomizer (22-24)
  • WithEnv (75-85)
  • WithExposedPorts (454-459)
  • WithCmd (462-467)
  • WithEntrypoint (438-443)
modules/mysql/mysql.go (1)
  • Run (54-121)
generic.go (1)
  • Run (122-149)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test (1.25.x, modules/postgres) / test: modules/postgres/1.25.x
  • GitHub Check: test (1.24.x, modules/postgres) / test: modules/postgres/1.24.x
  • GitHub Check: Analyze (go)
🔇 Additional comments (4)
modules/postgres/postgres.go (4)

124-126: LGTM; combine with central validation in Run

Return type change is correct. We should validate empty passwords in Run (see comment at Lines 155-167).


169-178: LGTM: container struct initialization

Defaults are fine and will be reconciled by the inspect step.


181-183: LGTM: clearer error context

“run postgres” improves diagnostics.


184-205: LGTM: env sync via Inspect

Accurately derives POSTGRES_DB/USER/PASSWORD from container env.

@mdelapenya mdelapenya merged commit b7e70d0 into testcontainers:main Oct 7, 2025
17 checks passed
@mdelapenya mdelapenya deleted the use-run-claude-postgres branch October 7, 2025 19:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Changes that do not impact the existing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant