testcontainers/testcontainers-rs-modules-community

initSQL for postgres container

kaning opened this issue · 6 comments

Feature request description

When running a test container, sometimes you might want to create a schema, user, role on the database before running your tests.

I believe you we have the .with_user, and .with_password options. Is it possible to have a .with_initsql method on the Postgres implementation that executes arbitrary SQL scripts on the database on start up?

Image reference

[dev-dependencies]
testcontainers = "0.20.0"
testcontainers-modules = { version = "0.8.0", features = ["postgres"] }

Hi @kaning!

It’s similar to a request here testcontainers/testcontainers-rs#669 (you can find a workaround there for now)

We need to consider adding this functionality for database-modules (like in Java). At least for a subset of modules.

At least, under a separate feature (if we will need to involve sqlx or something else)

Thank you for the response... I'll try that workaround

I don't think we need to close the issue. Because it seems to be a common use-case and we still need to consider/add this functionality

Should with_initsql be

  • fn with_initsql(mut self, initsql: impl AsRef<Path>) -> Self

or

  • fn with_initsql(mut self, initsql: &str) -> Self

I think it should be &str, most common use-case is to pass some static script. Rust provides convenient include_str! macro if you need a file content

Now it's possible by utilizing with_copy_to (thanks to @guenhter 🚀 )

So the easiest way at the moment is:

let image = Postgres::default()
        .with_copy_to(
            "/docker-entrypoint-initdb.d/init.sql",
            include_bytes!("initdb.sql").to_vec(), // path to your script, or just content from constant
        );
image.start().await?;

We can provide some shortcuts for DB modules