zonkyio / embedded-postgres

Java embedded PostgreSQL component for testing
Apache License 2.0
352 stars 47 forks source link

How to connect to instance with psql? #37

Closed velbur closed 4 years ago

velbur commented 4 years ago

Can i create an instance something like

final EmbeddedPostgres pg = EmbeddedPostgres.start();

and connect to it with psq? psql -h 127.0.0.1 -U postgres -p 5432 -d postgres

tomix26 commented 4 years ago

Yes, you can. All you need to do is set a port number when initializing the postgres instance. Because if the port parameter is not specified, a random port number is generated.

EmbeddedPostgres pg = EmbeddedPostgres.builder().setPort(5432).start();

velbur commented 4 years ago

Thank you for information about port nuber. But is it possible to specify that it waits for connection? I need to do some manipulation with database and then connect to it from the external environment, for example psql.

tomix26 commented 4 years ago

After completing the start method, the database should be ready to connect.

velbur commented 4 years ago

Example code.

public class Main {
    public static void main(String[] args) throws IOException, SQLException {
        EmbeddedPostgres pg = EmbeddedPostgres.builder().setPort(5432).start();
    }
}

it active only one or two seconds

tomix26 commented 4 years ago

This is because the database is running only while the java process is running. When the java process is terminated then all postgres instances created by this java process are terminated too.

The following solution is a bit naive, but it should work:

public class Main {
    public static void main(String[] args) throws IOException, SQLException, InterruptedException {
        EmbeddedPostgres pg = EmbeddedPostgres.builder().setPort(5432).start();
        Thread.sleep(Long.MAX_VALUE); // waits forever
    }
}
velbur commented 4 years ago

Maybe somehow possible save state of database and pass structure to new instance of embedded posgres?

tomix26 commented 4 years ago

This library is primarily intended for integration testing, so from my point of view it is not needed.

velbur commented 4 years ago

Ok, thanks a lot for the answers.