testcontainers-rs-modules-community icon indicating copy to clipboard operation
testcontainers-rs-modules-community copied to clipboard

initSQL for postgres container

Open kaning opened this issue 1 year ago • 5 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"] }

kaning avatar Jul 07 '24 20:07 kaning

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)

DDtKey avatar Jul 07 '24 23:07 DDtKey

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

kaning avatar Jul 08 '24 08:07 kaning

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

DDtKey avatar Jul 08 '24 09:07 DDtKey

Should with_initsql be

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

or

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

CommanderStorm avatar Aug 19 '24 13:08 CommanderStorm

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 avatar Aug 19 '24 17:08 DDtKey

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

DDtKey avatar Sep 25 '24 11:09 DDtKey