Running system command with argument in a PostgreSQL function - linux

I'm not sure if I was specific in the question, but I'm having trouble creating a Postgres function that runs a Linux shell command, with one detail: it's a function in a Trigger after insert and I need to use some NEW columns.
While in MySQL, using the plugin "MySQL UDF" it was pretty simple, trigger worked like this:
BEGIN
DECLARE result int(10);
SET result = sys_exec('/usr/bin/php /var/www/html/.../regras.php NEW.uniqueid NEW.linkedid NEW.eventtype');
END
But on PostgreSQL I tried the language PL/sh, wich enables running any shell script, so I wrote the following function:
CREATE FUNCTION tarifador_func2() RETURNS TRIGGER
LANGUAGE plsh
AS $$
#!/bin/sh
/usr/bin/php /var/www/html/...regras.php NEW.uniqueid NEW.linkedid NEW.eventtype
$$;
It does execute the .php file in proper way, the problem is the language does not recognize the NEW variables I'm giving as arguments to the PHP, so in the args[] what I got is "NEW.uniqueid", "NEW.linkedid" and "NEW.eventtype".
So, anyone knows how can I properly use the NEW argument in PL/sh?
Another possible solution might be to manually set the three values I need via the arguments on crating the trigger, but it's not allowed to use NEW in the arguments.

You can access some values in plsh triggers.
UPDATE offers only OLD
INSERT offers only NEW (duh)
DELETE I didn't test
So you get those values using arguments, like $1, $2
You function would look kinda like this:
CREATE FUNCTION tarifador_func2() RETURNS TRIGGER
LANGUAGE plsh
AS $$
#!/bin/sh
/usr/bin/php /var/www/html/...regras.php $3 $6 $1
$$;
Notice that I didn't use $1 $2 $3, that is because plsh extension dumps ALL columns into arguments in order they are declared in your table. So you might do something like INSERT INTO table1 (column3) VALUES (6); and it will be under $3 in plsh, assuming this is third column in table.
As a side note, metadata of trigger is available thru env vars.

As far as I know, you cannot access the NEWand OLD tuple in PL/sh.
I would use PL/Perl or PL/Python for this purpose.
Here is an example in PL/Python:
CREATE OR REPLACE FUNCTION pytrig() RETURNS trigger
LANGUAGE plpythonu AS
$$import os
os.system("/usr/bin/php /home/laurenz/hello.php '" + TD["new"]["val"] + "'")$$;
CREATE TABLE test (id integer PRIMARY KEY, val text);
CREATE TRIGGER pytrig AFTER INSERT ON test FOR EACH ROW
EXECUTE PROCEDURE pytrig();

Related

Linux Date not showing the date value sometimes

I have defined a variable inside one of the shell script to create the file name with date value in it.
I used "date +%Y%m%d" command to insert the current date which was defined in date_val variable.
And I have defined the filename variable to have "${path}/sample_${date_val}.txt
For few days it was creating the file name properly as /programfiles/sample_20180308.txt
But today the filename was created without date as /programfiles/sample_.txt
When I try to execute the command "date +%Y%m%d" in linux, it is returning the correct value - 20180309.
Any idea why the filename was created without the date value ??? . I did not modify anything in my script too. So wondering what might have gone wrong.
Sample excerpt of my script is given below for easy understanding :
EDITED
path=/programfiles
date_val=$(date +%Y%m%d )
file_name=${path}/sample_${date_val}.txt
Although incredibly unlikely, it's certainly possible for date to fail, based on the source code. Under the covers, it calls either clock_gettime() or gettimeofday(), both of which can fail.
The date program will also refuse to output anything to standard output if the date from either of those two functions is out of range during the call to (which is possible if they fail).
It's also possible that the date program could "disappear" for various reasons, such as actually being hidden or permissions changed, or a shortage of resources like file handles when attempting to open the executable.
As mentioned, all these possibilities are a stretch, unlikely to happen in the real world.
If you want to handle the case where you get inadequate output from date, you can simply try until you get a valid one, something like (with the possibility of adding some limit to detect if it's never any good):
todaysDate="$(date +%Y%m%d)"
while [[ ! $x =~ ^[0-9]{8}$ ]] ; do
sleep 1
todaysDate="$(date +%Y%m%d)"
done
# todaysDate now guaranteed to be eight digits.

Organize code in unix bash scripting

I am used to object oriented programming. Now, I have just started learning unix bash scripting via linux.
I have a unix script with me. I wanted to break it down into "modules" or preferably programs similar to "more", "ls", etc., and then use pipes to link all my programs together. E.g., "some input" myProg1 | myProg2 | myProg3.
I want to organize my code and make it look neater, instead of all in one script. Also, it will be easy to do testing and development.
Is it possible to do this, especially as a newbie ?
There are a few things you could take a look at, for example the usage of aliases in bash and storing them in either bashrc or a seperate file called by bashrc
that will make running commands easier..
take a look here for expanding commands into aliases (simple aliases are easy)
You can also look into using functions in your code (lots of bash scripts in above link's home folder to make sense of functions browse this site :) which has much better examples...
Take a look here for some piping tails into script
pipe tail output into another script
The thing with bash is its flexibility, so for example if something starts to get too messy for bash you could always write a perl/Java any lang and then call this from within your bash script, capture its output and do something else..
Unsure why all the pipes anyways here is something that may be of help:
./example.sh 20
function one starts with 20
In function 2 20 + 10 = 30
Function three returns 10 + 10 = 40
------------------------------------------------
------------------------------------------------
Local function variables global:
Result2: 30 - Result3: 40 - value2: 10 - value1: 20
The script:
example.sh
#!/bin/bash
input=$1;
source ./shared.sh
one
echo "------------------------------------------------"
echo "------------------------------------------------"
echo "Local function variables global:"
echo "Result2: $result2 - Result3: $result3 - value2: $value2 - value1: $value1"
shared.sh
function one() {
value1=$input
echo "function one starts with $value1"
two;
}
function two() {
value2=10;
result2=$(expr $value1 + $value2)
echo "In function 2 $value1 + $value2 = $result2"
three;
}
function three() {
local value3=10;
result3=$(expr $value2 + $result2;)
echo "Function three returns $value2 + $value3 = $result3"
}
I think the pipes you mean can actually be functions and each function can call one another.. and then you give the script the value which it passes through the functions..
bash is pretty flexible about passing values around, so long as the function being called before has the variable the next function being called by it can reuse it or it can be called from main program
I also split out the functions which can be sourced by another script to carry out the same functions
E2A Thanks for the upvote, I have also decided to include this link
http://tldp.org/LDP/abs/html/sample-bashrc.html
There is an awesome .bashrc to be reused, it has a lot of functions which will also give some insight into how to simplify a lot of daily repetitive commands such as that require piping, an alias can be written to do all of them for you..
You can do one thing.
Just as a C program can be divided into a header file and a source file for reducing complexity, you can divide your bash script into two scripts - a header and a main script but with some differences.
Header file - This will contain all the common variables defined and functions defined which will be used by your main script.
Your script - This will only contain function calls and other logic.You need to use "source <"header-file path">" in your script at starting to get all the functions and variables declared in the header available to your script.
Shell scripts have standard input and output like any other program on Unix, so you can use them in pipes. Splitting your scripts is a good solution because you can later use them in pipes with other commands.
I organize my Bash projects in the following way :
Each command is put in its own file
Reusable functions are kept in a library file which is just a classic script with only functions
All files are in the same directory, so commands can find the library with $(dirname $0)/library
Configuration is stored in another file as environment variables
To keep things clear, you should not use global variables to communicate between functions and main program.
I prepare a template for scripts with the following parts prepared :
Header with name and copyright
Read configuration with source
Load library with source
Check parameters
Function to display help, which is called if asked for or if parameters are wrong
My best advice is : always write the help function, as the next person who will need it is ... yourself !
To install your project you simply copy all files, and explain what to configure in the configuration file.

Save Result of Shell Script SQLite Select Statement to Variable

I'm pretty new to shell scripts and am only doing them because its about time I learnt and I need to for work.
I have been looking around and have tried multiple methods to get this working but can't seem to figure it out.
I have a script in which I want to access an SQLite database and store the result of a select statement in a variable.
What I've Tried So Far
This one just echoes whats inside the apostrophe. If I remove the dollar sign before the apostrophe I get the same outcome.
track_name=$'sqlite3 "$database_name" << EOF
select name from track where id = "$required_track";
exit;
EOF'
Here I get a syntax error near "track_name"
sqlite3 "$database_name" << EOF
track_name='select name from track where id = "$required_track";'
exit;
EOF
I have successfully executed the select statement without trying to store it in a variable but its not much use to me without being able to store it...
Any help would be much appreciated
To store the output of a command into a BASH variable you should use:
VAR_NAME=$(command);
For example, if you want to store your system current time into a variable or
the results of a list directory command ejecution:
DATE_EXAMPLE_VAR=$(date); #Stores 'date' command output into DATE_EXAMPLE_VAR
echo $DATE_EXAMPLE_VAR; #Shows DATE_EXAMPLE_VAR contents
DIRCONTENTS=$(ls); #Stores a list of your current directory contents.
Similarly, this should work for sqlite3:
track_name=$(sqlite3 "$database_name" "select name from track where id = $required_track")

Passing data into perl script from command line

I have a perl script the creates a report based on an xml definition. Currently these definitions all exist as .xml files.
So I have the script run-report.pl, which can take a path to a definition file and create the report.
Now I want to create run-reports-from-db.pl, which will generate the report definition based on same database entries. I don't want to create temp files to pass to run-report.pl, I would just like to pass in the definition somehow.
So instead of saying:
run-report.pl -def=./path/to/def.xml
I want to be able to say:
run-report.pl --stream
And have the report definition available in <STDIN>
I am sure there is pretty trivial way to do this???
If I understand your question correctly, all you need is one | (pipe).
./generate-xml-from-db.pl | ./run-report.pl --stream
Anything the first process in the pipeline prints to stdout will appear in the second process's stdin.
As long as you read from STDIN, you have it available. Notice what happens with you take the code below name it something like echo.pl run it at the command line and paste reams of text.
#!/usr/bin/perl -w
use 5.010;
use strict;
use warnings;
while ( <> ) {
say;
}
<> is the Perl shorthand for "read from STDIN".
As long as the method you're using to launch the process has a way to get a hold of the standard input and outputs, you can just write it to that handle. You have to use the ways that are available to you. In Java, for example, you'd have to get the input stream of the process, in a batch command you have to pipe it. At a GUI terminal you can cut and paste.

Sybase, execute string as sql query

In Sybase SQL, I would like to execute a String containing SQL.
I would expect something like this to work
declare #exec_str char(100)
select #exec_str = "select 1"
execute #exec_str
go
from the documentation of the exec command
execute | exec
is used to execute a stored procedure or an extended stored
procedure (ESP). This keyword is
necessary if there are multiple
statements in the batch.
execute is also used to execute a string containing Transact-SQL.
However my above example gives an error. Am I doing something wrong?
You need bracketing:
execute ( #exec_str )

Resources