automation script for postgresql - postgresql

Could you please help how can I run automation script for postgresql after installing postgresql on Ubuntu? I need to automatize DB preparation before using it (create table, insert data, alter permissions).
I need to do it with the current rights of the user.
E.g., I have the only user admin_ubuntu. He has all rights to run psql.
All scripts are written but how can I run the script? usually, I need to edit configs ( I believe, /etc/postgresql/9.1/main/pg_hba.conf). But I do not want to do it.
So, what I need is just to run sql which will make a lot of things. How can I do it to run it? The problem is that I need to do a lot of things to allow to run sql when the OS is immaculate (empty).
It will be made every time when the Ubuntu will have been installed.

you should be able to run shell provisioning - following is example of what you can do:
# creating user
sudo -u postgres psql -c "CREATE USER admin WITH PASSWORD 'password';"
# creating new db if needed .. might need 2 (dev/test)
createdb -U vagrant mydevdb
# if you have more complex things you'll need to put that in a create_db.sql file and run the script as
sudo -u postgres psql < create_db.sql
The create_db.sql file can contain any CREATE TABLE statement

Sharing some scripts here that show how to create databases, roles, schemas and tables. Not meant to be taken as best practice or acceptable for production, but hopefully it will help with getting started with PostgreSQL. Any code fragment surrounded by _ e.g. _variable_, indicate a string that should be replaced accordingly. Standard shell commands begin with $.
PostgreSQL Installation
My environment is an Ubuntu server/container where PostgreSQL was installed and started with:
$ apt install postgresql-12
$ pg_ctlcluster 12 main start
This automatically adds a postgres Linux user, which has superuser privileges in PostgreSQL, allowing the installation to be tested with:
$ sudo su postgres
$ psql
Which should result in a prompt like postgres=#. If that's the case, you should be able to follow the steps below with the default /etc/postgresql/12/main/pg_hba.conf settings.
Database and Role Creation
After saving this to a setup.sql file, it can be run with $ sudo -u postgres psql < setup.sql:
CREATE ROLE testadmin WITH LOGIN CREATEDB PASSWORD 'secret5';
CREATE DATABASE testdb OWNER testadmin;
CREATE ROLE _current-linux-user_ WITH LOGIN CREATEDB INHERIT;
GRANT pg_read_server_files TO testadmin;
GRANT pg_read_server_files TO _current-linux-user_;
GRANT testadmin to _current-linux-user_;
While playing around, it was useful to start everything from scratch, running $ sudo -u postgres psql < teardown.sql:
DROP DATABASE testdb;
DROP ROLE testadmin;
DROP ROLE _current-linux-user_;
Loading the Database From CSV Files
There's a reason we created a role with the same login name as the current user. It allows us to connect to the database by simply doing $ psql testdb which shows a prompt like testdb=>.
First we'll need the CSV files to populate the testdb database, I used the two below for an example food database. Be careful to not leave blank lines at the end of the files, otherwise there will be an ERROR: missing data for column.
categories.csv:
Category ID,Category Name
1,Fruit
2,Nut
3,Vegetable
4,Grain
5,Fungus
6,Alga
7,Seed
items.csv:
Food Name,Category,Nutrition
Peach,1,"Vitamin A, C, Potassium, Magnesium, Iron"
Brazil nut,7,"Iron, Calcium, Protein"
Broccoli,3,"Vitamin C, Magnesium"
Bean,4,"Magnesium, Iron, Calcium, Protein"
Mushroom,5,"Iron, Magnesium, Sodium, Protein"
Now we can run $ psql testdb < schema.sql:
CREATE SCHEMA food
CREATE TABLE food.categories (category_id integer PRIMARY KEY, category text)
CREATE TABLE food.items (id serial, name text, category_id integer REFERENCES food.categories (category_id), nutrition text);
/* Load data from CSV files into tables */
COPY food.categories(category_id, category)
FROM '/path/to/categories.csv' WITH (FORMAT csv, HEADER ON);
COPY food.items(name, category_id, nutrition)
FROM '/path/to/items.csv' WITH (FORMAT csv, HEADER ON);
/* Test */
SELECT * FROM food.categories;
SELECT * FROM food.items;
SELECT name,category FROM food.items INNER JOIN food.categories
ON food.items.category_id = food.categories.category_id;
Which results in the following output:
CREATE SCHEMA
COPY 7
COPY 5
category_id | category
-------------+-----------
1 | Fruit
2 | Nut
3 | Vegetable
4 | Grain
5 | Fungus
6 | Alga
7 | Seed
(7 rows)
id | name | category_id | nutrition
----+------------+-------------+------------------------------------------
1 | Peach | 1 | Vitamin A, C, Potassium, Magnesium, Iron
2 | Brazil nut | 7 | Iron, Calcium, Protein
3 | Broccoli | 3 | Vitamin C, Magnesium
4 | Bean | 4 | Magnesium, Iron, Calcium, Protein
5 | Mushroom | 5 | Iron, Magnesium, Sodium, Protein
(5 rows)
name | category
------------+-----------
Peach | Fruit
Brazil nut | Seed
Broccoli | Vegetable
Bean | Grain
Mushroom | Fungus
(5 rows)
Specifying the CSV format allows us to enclose the default delimiter, which is , in quotes inside a data column. The default loading is text which could lead to an ERROR: extra data after last expected column. Another source of this error is forgetting to include all the fields in the COPY command, e.g. nutrition.
Login With New User
What about the testadmin user we just created? We can connect to the database with a password as follows:
$ psql -U testadmin -d testdb -h localhost
Password for user testadmin:
psql (12.8 (Ubuntu 12.8-0ubuntu0.20.04.1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.
testdb=>
If you forget to use -h localhost you'll likely get a psql: error: FATAL: Peer authentication failed for user "testadmin".
There is excellent documentation for the above commands on the official site.

Related

User permission to list databases

I have exported all databases using pg_dumpall, then I imported them using psql. for the database "command" the are 2 users, "jo" is the owner and "ko" can manipulate all tables(list, edit, delete).
when I connect to the database using the user "jo" psql -U jo -h localhost -d command I can list all tables.
I run the command \z login I get
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+-------+-------+--------------------+-------------------+----------
command| login | table | jo=arwdDxt/jo +| |
| | | ko=arwdDxt/jo +| |
but when I connect using "ko" psql -U ko -h localhost -d command, I run the \dt I get
Did not find any relations.
when I run select * from command.login; I get the data inside the login table, when run select * from login I get the error
ERROR: relation "login" does not exist
LINE 1: select * from login;
How can I list the tables using the user "ko" ?
Simple: put schema command on the search_path and give user ko USAGE permissions on the schema.

PostGIS only works with root user

I have a database and am trying to use PostGis with it.
When I run:
$ psql -h localhost -d $APP_DB_NAME -U $APP_DB_USER
# SELECT PostGIS_version();
I get the following error:
ERROR: function postgis_version() does not exist
LINE 1: SELECT PostGIS_version();
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
But when I enter the database as root:
$ sudo su postgres -c psql $APP_DB_NAME
# SELECT PostGIS_version();
It runs fine:
postgis_version
---------------------------------------
2.1 USE_GEOS=1 USE_PROJ=1 USE_STATS=1
(1 row)
I am installing the PostGis extension as the root user, since my user doesn't have super_user access.
$ su - postgres -c psql $APP_DB_NAME
# CREATE EXTENSION postgis;
My guess is that the owner of the schema in which postgis is installed is not the user you're logging in as, but rather the "root" user (which is postgres).
$ psql postgres
postgres=# \dn
List of schemas
Name | Owner
--------------------+----------
public | postgres
pg_catalog | postgres
my_data | someuser
When connecting as postgres, postgis will work in this case, but if you connect as any other user, it will fail, and say it's not there, even though if you try to create extension postgis it will say it's installed already.
To correct this, make sure all the schemas are owned by the user you're actually connecting as:
ALTER SCHEMA public OWNER TO my_user;

Where are PostgreSQL database files in the cluster directory?

On OSX, I recently installed PostgreSQL via Homebrew:
brew install postgresql
I then created a new database cluster:
initdb /usr/local/var/postgres
I confirm that postgresql server is running with the expected database cluster:
$ ps auxwww | grep postgres
0:00.03 /usr/local/opt/postgresql/bin/postgres -D /usr/local/var/postgres
I create a new database:
createdb mynewdb
I see that it exists.
$ psql
<user>=# \l
mynewdb | <user> | UTF8 | en_US.UTF-8 | en_US.UTF-8
But, I see no obvious changes to the cluster directory (e.g., just by checking contents ls -lt).
Where is the database written / stored in the cluster directory (or sub-directories)?
as #ahorsewithnoname says they are in the base directory, (on some other platfotms data/base)
the numeric name is the OID of the database and in the directory will be files named for the OID of the table or index they relate to.
databse oids can be determined with this query. oid is like a hidden unique id column.
select oid,* from pg_catalog.pg_database;
table and index oids can be found like this,
select * from pg_catalog.pg_class;
column relifilenode for the base of the filename (thanks #jjames)

create new role?

I'm a newbie to PostgreSQL.
I'm trying to create a new role named pgdba like below...
localhost.localdomain:[/home/postgres]createuser -d -i -l -P -r -s pgdba
new role's password : pgdba
retype password : pgdba
password : postgres
localhost.localdomain:[/home/postgres]psql
Password: postgres
psql (9.0.1)
Type "help" for help.
postgres=# select * from pg_shadow;
usename | usesysid | usecreatedb | usesuper | usecatupd | passwd | valuntil | useconfig
----------+----------+-------------+----------+-----------+-------------------------------------+----------+-----------
postgres | 10 | t | t | t | md53175bce1d3201d16594cebf9d7eb3f9d | |
pgdba | 16385 | t | t | t | md53cd688326933adcdedd77097c95d131d | |
(2 rows)
postgres=# \q
localhost.localdomain:[/home/postgres]psql -U pgdba
Password for user pgdba: pgdba
FATAL: database "pgdba" does not exist
psql: FATAL: database "pgdba" does not exist
What am I doing wrong?
See how the message is that database pgdba does not exist?
By default, PostgreSQL will connect to a database named after the current user (see the psql docs. Since you aren't specifying a database to connect to, it's trying to connect to a DB named pgdba - which doesn't exist.
Try:
psql -U pgdba postgres
to connect to the postgres database using role pgdba.
You may also need to examine pg_hba.conf (see docs if you wish to tweak the authentication rules.
BTW, you are running an outdated PostgreSQL version with known bugs. Please update to 9.0.8, the latest patch release in the 9.0 series. You do not need to dump and reload your database or use pg_upgrade for this, it's a simple drop-in replacement. See the release notes for all the fixes you're missing.
Also, rather than SELECTing from pg_shadow, consider using psql's user information functions \du and \dg, which produce much better formatted and integrated information.

GeoDjango: editing the standard PostGIS template to include OSGB36

I've just installed GeoDjango (yay) and now I'm trying to follow these instructions to set up an existing GeoDjango project, which needs OSGB36:
After you've installed and got a PostGIS template, log
in to it and update the proj4text column of SRID 27700 to include
+datum=OSGB36, and update SRID 29902 to have +datum=ire65.
However. If I connect to the postgis_template created as part of the GeoDjango install, it doesn't appear to have any rows or columns at all:
domesday=# \c template_postgis
psql (8.4.4)
You are now connected to database "template_postgis".
template_postgis=# \d
No relations found.
How do I make the edits necessary to update SRID 27700 and SRID 29902 as described here? Have I created template_postgis wrong? I didn't see any errors during install.
What you should see is:
template_postgis=# \d
List of relations
Schema | Name | Type | Owner
--------+------------------+-------+----------
public | geometry_columns | table | postgres
public | spatial_ref_sys | table | postgres
(2 rows)
Since you're not, you probably had a problem running:
$ psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql
On my (Ubuntu+PG8.3) system, that file is actually called lwpostgis.sql. I had similar issues when installing the first time.