10. Automating SQL TasksÂ
There will be times when you need a task in SQL to be automated, so that it can be triggered from another application, or scheduled to run at a specific time. This module describes a few options for doing this.
10.1. psql
Full database functionality is available through the psql command line shell application. This can be accessed from within pgAdmin, or on the command line - it is installed auomatically with Postgres, normally in the bin folder (e.g. C:\Program Files\PostgreSQL\13\bin\pgsql.exe), and so can be called from a batch file.
Full documentation on psql commands can be found here.
10.1.1. psql in pgAdmin
Got to Tools > PSQL Tool to start psql - you will see a screen like this, already connected to your database
Now type in an SQL command into the prompt, remembering to close the statement with a semicolon, for example:
select * from geometry_columns;
The full table will appear in the console
10.1.2. Run pqsl from the Command Prompt
You can run pgsql directly from a command prompt (in AppStream, use the OSGeo4W Shell command from the menu).
Start psql by typing the following, which includes the parameters for the database connection (use your own database name)
psql -h appstream_data.astuntechnology.com -d chris_guest3 -p 5432 -U postgis
Enter your password (postgis) at the prompt - you will see the following:
You can now enter an SQL statement in the same way as you did in pgAdmin, and press Enter to run it - try this with a SELECT statement on one of your tables, and donât forget to add a semi-colon ';' at the end
If you are working from the command line, and always using the same database, set the environment variables for the connection to avoid having use the parameters each time - for example:
set PGHOST=appstream_data.astuntechnology.com set PGUSER=postgis set PGPASSWORD=ppostgis set PGDATABASE=chris_guest3 set PGPORT=5432
10.1.3. psql Meta-commands
As well as being able to run SQL, psql includes a set of meta-commands, prefixed with a backslash, that are processed by psql itself. Meta-commands make psql useful for administration or scripting.
10.1.3.1. Basics
\h | get help with SQL |
\? | get help with PSQL |
\g OR ; | execute a query |
\q | quit |
\cd | change directory |
10.1.3.2. Input / Outputs
\echo [STRING] | write string to standard output |
\i [FILE] | execute commands from file |
\o [FILE] | send all query results to file |
10.1.3.3. Â Information
\d [OBJECTNAME] | describes tables, sequences views etc. |
\db | lists tablespaces |
\df | lists functions |
\dn | lists schemas |
\dp OR \z | lists tables, views sequences etc. |
\du | lists users |
\l | lists all databases |
\dt | lists tables |
Visit the PostgreSQL documentation for a more in depth guide to PSQL.
10.2. Functions
PostgreSQLÂ functions, also known as Stored Procedures, allow you to package queries so that they can be called when needed by any database user, with parameters if appropriate. Postgres/PostGIS are installed with a large number of built in functions - you will find them in the public schema.
Functions can be created in the language of your choice , including SQL, PL/pgSQL, C, and Python - the most common language for creating function is PL/pgSQL.
The basic syntax of a function is below:
CREATE [OR REPLACE] FUNCTION function_name (arguments) RETURNS return_datatype AS $block_name$ DECLARE declaration; [...] BEGIN < function_body > [...] RETURN { variable_name | value } END; $block_name$ LANGUAGE plpgsql;
Create a simple function below by running the code below in the Query Tool
CREATE OR REPLACE FUNCTION general.myfunction(a integer, b integer)
RETURNS integer AS
$$
BEGIN
return a*b;
END;
$$
LANGUAGE plpgsql;
Note that a schema name is not required - if it is not supplied, the function will be created in the public schema
Call the function using a SELECT statement in the Query Tool
select general.myfunction(4,3)
For more details on functions see https://www.postgresql.org/docs/9.4/static/sql-createfunction.html , and for details on PL/pgSQL see https://www.postgresql.org/docs/9.4/static/plpgsql.html .
10.3. Triggers
A trigger is a set of actions that run automatically when a specified change operation (SQL INSERT, UPDATE, DELETE or TRUNCATE statement) is performed on a specified table. Triggers are useful for tasks such as enforcing business rules, validating input data, and keeping an audit trail.
Create a test table by running the SQL below
CREATE TABLE test_table( col1 text, col2 text, col3 date);
Create a trigger function which sets col3 to todayâs date when the trigger is executed - this is the action the trigger will generated
CREATE OR REPLACE FUNCTION test_table_trig() RETURNS TRIGGER as
$$
BEGIN
new.col3 = current_date;
return new;
END;
$$
LANGUAGE plpgsql;
Now create the trigger which will fire at the time of execution
CREATE TRIGGER test_table_trigger
BEFORE INSERT
ON test_table
FOR EACH ROW
EXECUTE PROCEDURE test_table_trig();
Test the trigger by using INSERT to add a row to the table
INSERT INTO test_table(col1,col2) VALUES('1','2')
Look at the table data, and check that todayâs date has been added as a value for column 3
For more information on triggers and trigger functions see https://www.postgresql.org/docs/9.4/static/plpgsql-trigger.html .