postgresqlunit-testinggotestcontainers

Postgres Testcontainers for Golang: WithInitScripts with multiple scripts does not work


Setting up the test like this:

postgresContainer, err := postgres.RunContainer(ctx,
        testcontainers.WithImage("docker.io/postgres:16-alpine"),
        postgres.WithDatabase(dbName),
        postgres.WithUsername(dbUser),
        postgres.WithPassword(dbPassword),
        postgres.WithInitScripts(filepath.Join("..", "postgres_migrations", "v1_create_bands.sql"),
            filepath.Join("..", "tests", "postgres_scripts", "bands_init.sql")),
        testcontainers.WithWaitStrategy(
            wait.ForLog("database system is ready to accept connections").
                WithOccurrence(2).
                WithStartupTimeout(5*time.Second)),
    )

v1_create_bands.sql:

CREATE TABLE bands (
    id INT PRIMARY KEY,
    name VARCHAR(255)
);

bands_init.sql:

INSERT INTO bands(id, name) VALUES 
(1, 'Band1'),
(2, 'Band2');

When I run the test I get the error relation "bands" does not exist at character 13 while trying to run bands_init.sql.

But if I copy the CREATE TABLE statement into bands_init.sql I get the error relation "bands" already exists!

If I leave only bands_init.sql as the only script with 2 statements then the test passes correctly. I don't understand what is going on here.


Solution

  • The part I missed is that the error in the second scenario was while running v1_create_bands.sql. So the scripts are simply executed in alphabetical order, not in the order of passing them to the function. I renamed bands_init.sql so that it is alphabetically greater than v1_create_bands.sql, and then the test passed.