I've created a function and saved it in a .sql file. I want to use this file and function to place the file on a system and then execute the included function via the command line, so the new data gets saved to the database on that system.
Currently, the content of my .sql file is:
CREATE OR REPLACE
FUNCTION device_authorisation_change(device_identification VARCHAR)
RETURNS VARCHAR AS
$$
DECLARE
OWNER varchar(255);
DEVICE_ID integer;
OWNER_ID integer;
DATE_TIME timestamp;
BEGIN
OWNER := 'MyDefaultOrganisation';
DATE_TIME := current_timestamp;
DEVICE_ID := (SELECT id from device dev where dev.device_identification = $1);
OWNER_ID := (SELECT id from owners own where own.owner_identification = OWNER);
DELETE FROM device_authorization
WHERE device = DEVICE_ID AND owner = OWNER_ID;
INSERT INTO device_authorization(id, creation_time, device, owner)
VALUES (nextval('device_authorization_id_seq'), DATE_TIME, DEVICE_ID, OWNER_ID);
RAISE NOTICE 'Deleted device authorisations for % for device: %' , OWNER, $1;
RETURN '';
END;
$$ LANGUAGE plpgsql;
When I try to run the file using the command, I used the following command
psql -d my_database -f ChangeOwnership.sql -v device_identification='TestDevice'
and the result shows that de device_identification seems to be NULL. However, the function gets stored to the database and I can execute this function (in pgAdmin) using
SELECT "device_authorisation_change"('TestDevice');
This time, the function executes well.
What I want to achieve is that I can run the sql script from command line, using (named) arguments, which immediately updates the data in the database. It is not necessary to save the function in the database, I actually like to avoid it, but if it complicates things then it's not a problem if it stays in the database.
Can anyone help me out?
DOstatement which executes anonymous code block if you don't need to create a function :)