Re: Executing External Programs

From: Tor Løjborg <tor(at)borgcube(dot)dk>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Executing External Programs
Date: 2003-05-17 19:08:38
Message-ID: 200305172108.38086.tor@borgcube.dk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> Is there a way (maybe creating a function) to execute an external program
> from within postgre with a query?

Yes there is. This C function executes a command with the system function,
system waits for your command to complete and then returns the exit status.
Rember your command will run with postgres effective UID and GID.

When you've compiled and loaded it, try something like :

SELECT sys_ex('echo hello >> /usr/local/pgsql/testfile');

Regards, Tor.

#include "postgres.h"
#include "fmgr.h"
#include <string.h>
#include "executor/spi.h"
#include "utils/elog.h"

extern Datum sys_ex(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(sys_ex);
Datum
sys_ex(PG_FUNCTION_ARGS)
{
char *command;
int32 returns;
char *wrn;
char *say = "Executes command : ";

command = (char *) DatumGetCString(DirectFunctionCall1(textout,
PointerGetDatum(PG_GETARG_TEXT_P(0))));

wrn = (char *) palloc (sizeof(say) + sizeof(command));
strcpy(wrn,say);
strcat(wrn,command);
elog(NOTICE, wrn);
returns = (int32) system(command);
if (returns != 0 )
{
elog(NOTICE,"EXTERNAL COMMAND FAILED!");
}
PG_RETURN_INT32(returns);
}

In response to

Browse pgsql-general by date

  From Date Subject
Next Message ahoward 2003-05-17 19:33:54 Re: 7.3.2, pam, on Linux 2.4.18-18.7.x i686
Previous Message alex b. 2003-05-17 19:01:27 query duration