Hello,
INTRO: I would like to build simple application in C to deal with
PostgreSQL, but part of work should be done by RUBY.
PROBLEM: I don’t want to make new connection with PGSQL in Ruby script
but attach existing one (‘conn’ variable as below) from C.
QUESTION: Is it possible to attach to Postgres connection from C in Ruby
script? And how to do it?
Szymon Drejewicz
···
#=======================================================================
#include <stdlib.h>
#include <libpq-fe.h>
#include <ruby.h>
#include “postgres.c”
int main(int argc, char** argv) {
PGresult *result;
PGconn *conn;
int nFields;
int i;
int j;
conn = PQconnectdb("");
if(PQstatus(conn) == CONNECTION_OK) {
printf(“connection made\n”);
result = PQexec(conn, “SELECT COUNT(*) FROM studenci”);
printf("Wy¶wietlam wynik za pomoc± C:\n");
/* first, print out the attribute names */
nFields = PQnfields(result);
for (i = 0; i < nFields; i++)
printf("%-15s", PQfname(result, i));
printf("\n\n");
/* next, print out the rows */
for (i = 0; i < PQntuples(result); i++) {
for (j = 0; j < nFields; j++)
printf("%-15s", PQgetvalue(result, i, j));
printf("\n");
}
printf("Teraz spróbujê przekazaæ wynik SELECTA do skryptu Ruby'ego,
który wy¶wietli to samo co powy¿ej:");
ruby_init();
ruby_options(argc,argv);
/* Udostêpniam Ruby’emu po³±czenie z PostgreSQL’em /
ruby_init_loadpath();
rb_require(“postgres”);
//-----------------PROBLEM BEGIN
VALUE DBconn = Data_Wrap_Struct(rb_cPGconn, 0, free_pgconn, conn);
// rb_obj_call_init(DBconn,0,0);
VALUE connection = conn;
rb_define_variable("$conn",&connection);
rb_eval_string(“puts ‘\nTEST\n’”);
rb_eval_string("a = $conn.query('select count() from
studenci’)[0][0] \n puts a");
//-----------------PROBLEM END
}
else
printf(“connection failed: %s\n”, PQerrorMessage(conn));
PQfinish(conn);
return EXIT_SUCCESS;
}