1 ! See http://factor.sf.net/license.txt for BSD license.
3 ! adapted from libpq-fe.h version 7.4.7
4 ! tested on debian linux with postgresql 7.4.7
7 USING: kernel alien errors io prettyprint sequences namespaces arrays math ;
12 : connect-postgres ( host port pgopts pgtty db user pass -- conn )
14 dup PQstatus zero? [ "couldn't connect to database" throw ] unless ;
16 : with-postgres ( host port pgopts pgtty db user pass quot -- )
17 [ >r connect-postgres db set r>
18 [ db get PQfinish ] cleanup ] with-scope ; inline
20 : with-postgres-catch ( host port pgopts pgtty db user pass quot -- )
21 [ with-postgres ] catch [ "caught: " write print ] when* ;
23 : postgres-error ( ret -- ret )
24 dup zero? [ PQresultErrorMessage throw ] when ;
26 : (do-query) ( PGconn query -- PGresult* )
27 ! For queries that do not return rows, PQexec() returns PGRES_COMMAND_OK
28 ! For queries that return rows, PQexec() returns PGRES_TUPLES_OK
30 dup PQresultStatus PGRES_COMMAND_OK =
31 over PQresultStatus PGRES_TUPLES_OK =
33 [ PQresultErrorMessage CHAR: \n swap remove ] keep PQclear throw
36 : (do-command) ( PGconn query -- PGresult* )
40 "non-fatal error: " print
41 "\tQuery: " write "'" write write "'" print
45 : do-command ( str -- )
46 unit \ (do-command) add db get swap call ;
48 : prepare ( str quot word -- conn quot )
49 rot unit swap append swap append db get swap ;
51 : do-query ( str quot -- )
52 [ (do-query) query-res set ] prepare catch
53 [ rethrow ] [ query-res get PQclear ] if* ;
55 : result>seq ( -- seq )
56 query-res get [ PQnfields ] keep PQntuples
57 [ swap [ query-res get -rot PQgetvalue ] map-with ] map-with ;
59 : print-table ( seq -- )
60 [ [ write bl ] each "\n" write ] each ;