dockerdocker-desktoptestcontainerstestcontainers-junit5

how to see PostgreSQLContainer database records


I have created PostgreSQLContainer as below

public static PostgreSQLContainer postgres = (PostgreSQLContainer) new PostgreSQLContainer<>("postgres")
        .withCreateContainerCmdModifier(cmd -> cmd.withName("postgres-sql"))
        .withNetworkAliases("postgres")
        .withStartupTimeoutSeconds(240)
        .withConnectTimeoutSeconds(240)
        .withNetwork(componentTestNetwork)
        .withFileSystemBind(pathToFile + "/postgres/", "/postgres", BindMode.READ_WRITE)
        .withExposedPorts(5432)
        .withStartupAttempts(10)
        .withInitScript("postgres/create_table.sql")
        .waitingFor(Wait.forHealthcheck());

Content of create_table.sql is as below:

CREATE SCHEMA IF NOT EXISTS techwriting;

CREATE TABLE IF NOT EXISTS techwriting.book(
id int NOT NULL,
name varchar(10) NOT NULL,
description varchar(10) NOT NULL,
CONSTRAINT book_pkey PRIMARY KEY (id));


INSERT INTO techwriting.book (id,name,description) VALUES
(1,'premchand','classical');
INSERT INTO techwriting.book (id,name,description) VALUES
(2,'nirala','horror');
INSERT INTO techwriting.book (id,name,description) VALUES
(3,'premchand','horror');
INSERT INTO techwriting.book (id,name,description) VALUES
(4,'premchand','xyz');

My Docker Desktop is up and I can see container for postgresql is created. Now I wanted to see the records that have been inserted from create_table.sql but I am not able to see them. How and where to find those records?

The only thing I found on Docker Desktop is volume for postgresql container. Which has certain info related to postgresql . I have attached here for reference. But again I am not able to see records which got inserted from create_table.sql . enter image description here


Solution

  • First, you can publish ports via testcontainers. Then you can connect to the database using some client. I prefer to do it via psql (or you can set up a temporary connection using pgAdmin), it comes with most postgres distributions:

    psql --host=localhost --port=<port_you_have_published> --username=<username> --dbname=<your_db_name> --password
    

    and then you're good to go, just select the stuff you want :)