File: simplesql-postgresql.c

package info (click to toggle)
guile-simplesql 2.3.2-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,672 kB
  • ctags: 97
  • sloc: sh: 8,413; ansic: 834; lisp: 42; makefile: 23
file content (280 lines) | stat: -rw-r--r-- 8,207 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/* sqpgsql.c:  PostgreSQL backend for Guile SimpleSQL

   Copyright (C) 2001, 2004 David J. Lambert.
   Copyright (C) 1999 Stephen R. Kifer <srkifer@mboxes.com>
   Copyright (C) 1999 forcer <forcer@mindless.com>
   Copyright (C) 1996-98 Hal Roberts

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
   USA  */

#include "guile-simplesql.h"

#include <libguile.h>
#include <postgresql/libpq-fe.h>
#include <string.h>


static void *sqpgsql_open (const char *dbname, const char *host, int port, const char *,
			   const char *user, const char *pass, SCM *err);
static SCM sqpgsql_query (void *conn, const char *query, int querylen );
static void sqpgsql_close(void *conn);
static SCM sqpgsql_convert_query_result(PGconn *conn, PGresult *res );
static SCM sqpgsql_pgsql_sql2scm (PGresult *res,
				  int row,
				  int field,
				  char *field_type );
static SCM sqpgsql_convert_time (struct tm *bd_time, char *zt);


/* Init function for the PostgreSQL API */
void
sq_pgsql_init (void)
{
    sql_register_api("PostgreSQL", sqpgsql_open, sqpgsql_query, sqpgsql_close);
}


/* Open a connection to the PostgreSQL database.  Returns a PGconn
   object.  */
static void
*sqpgsql_open (const char *dbname, const char *pghost, int port, const char *socket,
	       const char *user, const char *pass, SCM *err)
{
    char *pgoptions, *pgtty, *pgport, pgport_buf[3*sizeof(int)];
    PGconn *conn;

    pgoptions = NULL;
    pgtty = NULL;
    
    if (!port && !socket)
	pgport = NULL;
    else if (! socket)
    {
	pgport = pgport_buf;
	sprintf (pgport, "%i", port);
    }
    else
	pgport = (char *) socket;

    conn = PQsetdbLogin(pghost, socket ? socket : pgport, pgoptions, pgtty, dbname, user, pass);
    if (PQstatus(conn) == CONNECTION_BAD){
	*err = scm_makfrom0str (PQerrorMessage(conn));
	PQfinish(conn);
	return NULL;
    }
    return conn;
}


/*
  db is our PGconn object
  query is a string containing the query (not null terminated)
  querylen is the length of the query
  The return value is the list of vectors
  Send the query, and conver the result set at once
*/
static SCM sqpgsql_query ( void *conn,
			   const char *query,
			   int querylen )
{
  PGresult  *res;
  SCM scm_result;
  char *cquery;

  cquery = malloc (querylen + 1);
  if (!cquery)
      scm_misc_error("sql-query", "Unable to allacate memory.", SCM_EOL);
  strncpy (cquery, query, querylen);
  cquery[querylen] = '\0';
  res = PQexec((PGconn*)conn, cquery);
  free (cquery);

  if (PQresultStatus(res) == PGRES_TUPLES_OK) {
    scm_result = sqpgsql_convert_query_result((PGconn*)conn, res);
  } else if (PQresultStatus(res) == PGRES_COMMAND_OK) {
    scm_result = scm_i_mem2number (PQcmdTuples(res),
				   strlen(PQcmdTuples(res)),
				   10);
  } else {
    scm_misc_error("sql-query", "~S",
		   scm_cons (scm_makfrom0str (PQresultErrorMessage(res)),
			     SCM_EOL));
  }
  PQclear(res);
  return scm_result;
}

/*
  Close the connection.
*/
static void sqpgsql_close ( void *conn ) 
{
  PQfinish(conn);
}


/* Walk through the PGresult result.  Build a list of vectors, the
   first containing the result tables' headers, the others containing
   the the result values.  */
static SCM
sqpgsql_convert_query_result (PGconn *conn, PGresult *res)
{
    long f, r;
    int num_fields, num_rows;
    char *field_name, *field_types, *querystr;
    SCM scm_fields, scm_rows, scm_data, scm_result;
    PGresult *field_res;

    querystr = malloc(100);

    /* get number of fields in query result and reserve space for
       field_types to hold the field types */
    num_fields = PQnfields(res);
    num_rows = PQntuples(res);
    field_types = malloc(num_fields * 32);
  
    scm_fields = scm_make_vector (scm_int2num (num_fields),
				  scm_int2num (0));

    /* Loop through the returned fields, storing field names in the
       first scheme vector and field type in the string array
       field_types. */
    for (f = 0; f < num_fields; f++) {
	/* store field name */
	field_name = PQfname(res, f);
	scm_vector_set_x(scm_fields, scm_int2num (f),
			 scm_makfrom0str (field_name));
	/* get field type */
	sprintf(querystr,
		"select typname from pg_type where oid = %d ;",
		PQftype(res, f));
	field_res = PQexec(conn, querystr);

	strncpy((char*)(field_types + (f * 32)),
		PQgetvalue(field_res, 0, 0),
		32);
	PQclear(field_res);
    }

    /* Query PostgreSQL for current date format in use */
    /*
      date_style_res = PQexec(conn, "SHOW DateStyle;");
      date_style = PQcmdStatus(date_style_res);
      printf("%s", date_style);
    */

    /* Loop through the rows and then columns of the query result,
       calling sqpgsql_pgsql_sql2scm to convert the results to scheme
       values. */
    scm_result = scm_rows = scm_cons(scm_fields, SCM_EOL);
    for (r = 0; r < num_rows; r++) {
	scm_data = scm_make_vector(scm_int2num (num_fields),
				   scm_int2num (0));
	for (f = 0; f < num_fields; f++) {
	    scm_vector_set_x (scm_data,
			      scm_int2num (f),
			      sqpgsql_pgsql_sql2scm(res, r, f,
						    (char*)(field_types +
							    (f * 32)))
		);
	}
	SCM_SETCDR(scm_rows,
		   scm_cons(scm_data,
			    SCM_CDR(scm_rows)));
	scm_rows = SCM_CDR(scm_rows);
    }
    /* PQclear(date_style_res); */
    free(field_types);
    free(querystr);
    return scm_result;
}

/*
  The main conversion routine for PostgreSQL types.
  Converts fields from res to the Scheme representation.
*/
SCM sqpgsql_pgsql_sql2scm ( PGresult *res,
			    int row,
			    int field,
			    char *field_type )
{
  struct tm tm;
  int field_len;
  char *field_value, *time_zone;

  /* if it's a null value, return a scm null */
  if (PQgetisnull(res, row, field))
    return SCM_EOL;

  field_value = PQgetvalue(res, row, field);
  field_len = PQgetlength(res, row, field);

  /* else, figure out type and convert value */
  /* number types */
  if ( !strcmp(field_type, "int2") ||
       !strcmp(field_type, "int4") ||
       !strcmp(field_type, "int8") ||
       !strcmp(field_type, "float4") ||
       !strcmp(field_type, "float8") ||
       !strcmp(field_type, "numeric") ||
       !strcmp(field_type, "serial") ||
       !strcmp(field_type, "oid") ) {
    return scm_i_mem2number (field_value, field_len, 10);
    /* string types */
  } else if ( !strcmp(field_type, "char") ||
	      !strcmp(field_type, "bpchar") ||
	      !strcmp(field_type, "name") ||
	      !strcmp(field_type, "text") ||
	      !strcmp(field_type, "varchar") ) {
    return sq_latin1_string(field_value,
			    field_len);
    /* date types */
  } 
#ifdef HAVE_STRPTIME
  else if ( !strcmp(field_type, "timestamp") ) {
      time_zone = strptime (field_value, "%Y-%m-%d %T", &tm);
      return sqpgsql_convert_time(&tm, time_zone);
  }
#endif
  else if (!strcmp(field_type, "date") ||
	   !strcmp(field_type, "abstime") ||
	   !strcmp(field_type, "datetime") ||
	   !strcmp(field_type, "time") ||
	   !strcmp(field_type, "timestamp") ||
	   !strcmp(field_type, "timespan") ||
	   !strcmp(field_type, "tinterval") ) {
      return sq_latin1_string(field_value, field_len);
    /* bool type */
  } else if ( !strcmp(field_type, "bool") ) {
    if ((strncmp(field_value, "t", 1) == 0)) {
      return SCM_BOOL_T;
    } else {
      return SCM_BOOL_F;
    }
  } else {
    scm_misc_error("sql-query",
		   "Unknown field type ~S in result set",
		   scm_cons (scm_makfrom0str (field_type), SCM_EOL));
  }
}


/* This function just creates the time representation we chose.  */
static SCM
sqpgsql_convert_time(struct tm *bd_time, char *zt)
{
    return _simplesql_filltime (bd_time, 0, "");
}