testcontainers / testcontainers-rs-modules-community

Community maintained modules for Testcontainers for Rust
https://docs.rs/crate/testcontainers-modules/
MIT License
90 stars 43 forks source link

initSQL for postgres container #164

Closed kaning closed 2 months ago

kaning commented 4 months ago

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"] }

DDtKey commented 4 months ago

Hi @kaning!

It’s similar to a request here https://github.com/testcontainers/testcontainers-rs/issues/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)

kaning commented 4 months ago

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

DDtKey commented 4 months ago

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

CommanderStorm commented 3 months ago

Should with_initsql be

DDtKey commented 3 months ago

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

DDtKey commented 2 months ago

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