Numberedheadings | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||||||||||||||
Automating SQL TasksThere 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. psqlFull 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. psql in pgAdmin
Run pqsl from the Command PromptYou can run pgsql directly from a command prompt (in AppStream, use the OSGeo4W Shell command from the menu).
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:
psql Meta-commandsAs 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 . Basics | ||||||||||||||||||||||
\h | get help with SQL | |||||||||||||||||||||
\? | get help with PSQL | |||||||||||||||||||||
\g OR ; | execute a query | |||||||||||||||||||||
\q | quit | |||||||||||||||||||||
\cd | change directory | |||||||||||||||||||||
\echo [STRING] | write string to standard output | |||||||||||||||||||||
\i [FILE] | execute commands from file | |||||||||||||||||||||
\o [FILE] | send all query results to file | |||||||||||||||||||||
\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 |
|
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)
If you have time, make a change to the function and call it again - note that to update the function, you can select it in pgAdmin then right-click > Scripts > CREATE Script, then amend the function definition run the statement
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 .
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 .
QGIS
Because QGIS can be used to run SQL on a Postgres database, and it also has a workflow tool (the Graphical Modeller), it can be used to automate tasks in Postgres.
Open QGIS, and go to Processing > Graphical Modeler
In the Algorithms panel, search for Postgres, and double-click on PostgreSQL Execute SQL to include the process in your model
Double-click on the process in the model window to open it
In the dialog:
Set the Description to Add column
Set the Database (connection name) to the connection you created earlier
In the SQL query field, add
ALTER TABLE test_table ADD COLUMN testedit_date date
Click OK to save these settings
In the Model Designer, click the Run model button or F5 to run the model
In pgAdmin, check that the new field has been added to the data, and right-click > Delete/Drop to remove it so we can run the process again
In the Graphical Modeler, add another PostgreSQL Execute SQL process to the model in the same way as before
This time, rename the process Add values, and add some data to the table you have just updated, using the following SQL in the SQL query field
INSERT INTO test_table(col1,col2, test_from_qgis) VALUES('3','4','test_value')
Under Dependencies, add a dependency on the previous process - this will make this process run after the previous one
Click OK - your model should look something like this
Run the model, then check the results in pgAdmin
When you are finished, save the model for future use