1

Provided, I have to go through a route of

  1. Get into docker

  2. Get into postgreSQL database

  3. Create table

  4. Insert data

Which is very troublesome to do it frequently since I am testing. I want to write a bash script (.sh file) that do everything in 1 run.

Here are all my command line I need to run

docker exec -it <mycontainer> bash

psql -h localhost -p 5432 -U postgres

CREATE SCHEMA bank;

CREATE TABLE bank.holding (
    holding_id int,
    user_id int,
    holding_stock varchar(8),
    holding_quantity int,
    datetime_created timestamp,
    datetime_updated timestamp,
    primary key(holding_id)
);

insert into bank.holding values (102100, 2, 'VFIAX', 10, now(), now());
3
  • 1
    You will need to run them one at a time using the -c option to psql. For example psql -h localhost -p 5432 -U postgres -c 'create schema bank; and then sql -h localhost -p 5432 -U postgres -c 'create table bank.holding ( ... ); and so on. You can put all your command in a file and then use the -f (--file) option to read all commands from a file. That would likely be the better call, e.g. psql -h localhost -p 5432 -U postgres -f file-w-create.txt. Commented May 30, 2022 at 5:46
  • 1
    PostqreSQL Docker image provides a way initilize data using scripts. Please read section Initialization scripts from its official docs. TLDR; just mount your sql scrips inside /docker-entrypoint-initdb.d using docker volumes, and it will run on database init Commented May 30, 2022 at 6:27
  • 1
    Also consider using your application framework's database migration system to run these (and especially the CREATE TABLE commands). Commented May 30, 2022 at 10:37

1 Answer 1

2

Firstly, it will assist you on automating the procedure if you expose your container port

docker container run ... -p 5432:5432 ...

The above procedure will enable you to access the container port, by directly accessing your localhost:5432

Next run

psql -h localhost -p 5432 -U postgres -f bash_automation_script.txt

bash_automation_script.txt

CREATE SCHEMA bank;

CREATE TABLE bank.holding (
    holding_id int,
    user_id int,
    holding_stock varchar(8),
    holding_quantity int,
    datetime_created timestamp,
    datetime_updated timestamp,
    primary key(holding_id)
);

insert into bank.holding values (102100, 2, 'VFIAX', 10, now(), now());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.