ruby-postgres 0.7.1.2005.11.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/postgres.c ADDED
@@ -0,0 +1,2433 @@
1
+ /************************************************
2
+
3
+ postgres.c -
4
+
5
+ Author: matz
6
+ created at: Tue May 13 20:07:35 JST 1997
7
+
8
+ Author: ematsu
9
+ modified at: Wed Jan 20 16:41:51 1999
10
+
11
+ $Author: noboru $
12
+ $Date: 2003/01/06 01:38:20 $
13
+ ************************************************/
14
+
15
+ #include "ruby.h"
16
+ #include "rubyio.h"
17
+ #include "st.h"
18
+
19
+ /* grep '^#define' $(pg_config --includedir)/server/catalog/pg_type.h | grep OID */
20
+ #include "type-oids.h"
21
+ #include <libpq-fe.h>
22
+ #include <libpq/libpq-fs.h> /* large-object interface */
23
+ #include <stdio.h>
24
+ #include <stdlib.h>
25
+ #include <sys/types.h>
26
+
27
+ #ifndef HAVE_PG_ENCODING_TO_CHAR
28
+ #define pg_encoding_to_char(x) "SQL_ASCII"
29
+ #endif
30
+
31
+ #ifndef HAVE_PQFREEMEM
32
+ #define PQfreemem(ptr) free(ptr)
33
+ #endif
34
+
35
+ #ifndef StringValuePtr
36
+ #define StringValuePtr(x) STR2CSTR(x)
37
+ #endif
38
+
39
+ #define AssignCheckedStringValue(cstring, rstring) do { \
40
+ if (!NIL_P(temp = rstring)) { \
41
+ Check_Type(temp, T_STRING); \
42
+ cstring = StringValuePtr(temp); \
43
+ } \
44
+ } while (0)
45
+
46
+ #if RUBY_VERSION_CODE < 180
47
+ #define rb_check_string_type(x) rb_check_convert_type(x, T_STRING, "String", "to_str")
48
+ #endif
49
+
50
+ #define rb_check_hash_type(x) rb_check_convert_type(x, T_HASH, "Hash", "to_hash")
51
+
52
+ #define Data_Set_Struct(obj,ptr) do { \
53
+ Check_Type(obj, T_DATA); \
54
+ DATA_PTR(obj) = ptr; \
55
+ } while (0)
56
+
57
+ #define RUBY_CLASS(name) rb_const_get(rb_cObject, rb_intern(name))
58
+
59
+ #define SINGLE_QUOTE '\''
60
+
61
+ EXTERN VALUE rb_mEnumerable;
62
+ EXTERN VALUE rb_mKernel;
63
+ EXTERN VALUE rb_cTime;
64
+
65
+ static VALUE rb_cDate;
66
+ static VALUE rb_cDateTime;
67
+
68
+ static VALUE rb_cPGconn;
69
+ static VALUE rb_cPGresult;
70
+ static VALUE rb_ePGError;
71
+ static VALUE rb_cPGlarge;
72
+ static VALUE rb_cPGrow;
73
+
74
+ static VALUE pgresult_result_with_clear _((VALUE));
75
+ static VALUE pgresult_new _((PGresult*));
76
+
77
+ /* Large Object support */
78
+ typedef struct pglarge_object
79
+ {
80
+ PGconn *pgconn;
81
+ Oid lo_oid;
82
+ int lo_fd;
83
+ } PGlarge;
84
+
85
+ static VALUE pglarge_new _((PGconn*, Oid, int));
86
+ /* Large Object support */
87
+
88
+ static void free_pgconn(PGconn *);
89
+
90
+ static VALUE
91
+ pgconn_alloc(klass)
92
+ VALUE klass;
93
+ {
94
+ return Data_Wrap_Struct(klass, 0, free_pgconn, NULL);
95
+ }
96
+
97
+ static int build_key_value_string_i(VALUE key, VALUE value, VALUE result);
98
+
99
+ static PGconn *
100
+ try_connectdb(arg)
101
+ VALUE arg;
102
+ {
103
+ VALUE conninfo;
104
+
105
+ if (!NIL_P(conninfo = rb_check_string_type(arg))) {
106
+ /* do nothing */
107
+ }
108
+ else if (!NIL_P(conninfo = rb_check_hash_type(arg))) {
109
+ VALUE key_values = rb_ary_new2(RHASH(conninfo)->tbl->num_entries);
110
+ rb_hash_foreach(conninfo, build_key_value_string_i, key_values);
111
+ conninfo = rb_ary_join(key_values, rb_str_new2(" "));
112
+ }
113
+ else {
114
+ return NULL;
115
+ }
116
+
117
+ return PQconnectdb(StringValuePtr(conninfo));
118
+ }
119
+
120
+ static PGconn *
121
+ try_setdbLogin(args)
122
+ VALUE args;
123
+ {
124
+ VALUE temp;
125
+ char *host, *port, *opt, *tty, *dbname, *login, *pwd;
126
+ host=port=opt=tty=dbname=login=pwd=NULL;
127
+
128
+ rb_funcall(args, rb_intern("flatten!"), 0);
129
+
130
+ AssignCheckedStringValue(host, rb_ary_entry(args, 0));
131
+ if (!NIL_P(temp = rb_ary_entry(args, 1)) && NUM2INT(temp) != -1) {
132
+ temp = rb_obj_as_string(temp);
133
+ port = StringValuePtr(temp);
134
+ }
135
+ AssignCheckedStringValue(opt, rb_ary_entry(args, 2));
136
+ AssignCheckedStringValue(tty, rb_ary_entry(args, 3));
137
+ AssignCheckedStringValue(dbname, rb_ary_entry(args, 4));
138
+ AssignCheckedStringValue(login, rb_ary_entry(args, 5));
139
+ AssignCheckedStringValue(pwd, rb_ary_entry(args, 6));
140
+
141
+ return PQsetdbLogin(host, port, opt, tty, dbname, login, pwd);
142
+ }
143
+
144
+ static VALUE
145
+ pgconn_connect(argc, argv, self)
146
+ int argc;
147
+ VALUE *argv;
148
+ VALUE self;
149
+ {
150
+ VALUE args;
151
+ PGconn *conn = NULL;
152
+
153
+ rb_scan_args(argc, argv, "0*", &args);
154
+ if (RARRAY(args)->len == 1) {
155
+ conn = try_connectdb(rb_ary_entry(args, 0));
156
+ }
157
+ if (conn == NULL) {
158
+ conn = try_setdbLogin(args);
159
+ }
160
+
161
+ if (PQstatus(conn) == CONNECTION_BAD) {
162
+ VALUE message = rb_str_new2(PQerrorMessage(conn));
163
+ PQfinish(conn);
164
+ rb_raise(rb_ePGError, StringValuePtr(message));
165
+ }
166
+
167
+ Data_Set_Struct(self, conn);
168
+ return self;
169
+ }
170
+
171
+ /*
172
+ * See #new.
173
+ */
174
+ static VALUE
175
+ pgconn_s_connect(argc, argv, klass)
176
+ int argc;
177
+ VALUE *argv;
178
+ VALUE klass;
179
+ {
180
+ return rb_class_new_instance(argc, argv, klass);
181
+ }
182
+
183
+ static VALUE format_array_element(VALUE obj);
184
+
185
+ static VALUE
186
+ pgconn_s_format(self, obj)
187
+ VALUE self;
188
+ VALUE obj;
189
+ {
190
+ VALUE result;
191
+ int tainted;
192
+ long i;
193
+
194
+ switch(TYPE(obj)) {
195
+ case T_STRING:
196
+ return obj;
197
+
198
+ case T_TRUE:
199
+ case T_FALSE:
200
+ case T_FIXNUM:
201
+ case T_BIGNUM:
202
+ case T_FLOAT:
203
+ return rb_obj_as_string(obj);
204
+
205
+ case T_NIL:
206
+ return rb_str_new2("NULL");
207
+
208
+ case T_ARRAY:
209
+ result = rb_str_buf_new2("{");
210
+ tainted = OBJ_TAINTED(obj);
211
+ i;
212
+ for (i = 0; i < RARRAY(obj)->len; i++) {
213
+ VALUE element = format_array_element(RARRAY(obj)->ptr[i]);
214
+ if (OBJ_TAINTED(RARRAY(obj)->ptr[i])) tainted = Qtrue;
215
+ if (i > 0) rb_str_buf_cat2(result, ", ");
216
+ rb_str_buf_append(result, element);
217
+ }
218
+ rb_str_buf_cat2(result, "}");
219
+ if (tainted) OBJ_TAINT(result);
220
+ return result;
221
+
222
+ default:
223
+ if (rb_block_given_p()) {
224
+ return rb_yield(obj);
225
+ } else {
226
+ rb_raise(rb_ePGError, "can't format");
227
+ }
228
+ }
229
+ }
230
+
231
+ static VALUE
232
+ format_array_element(obj)
233
+ VALUE obj;
234
+ {
235
+ if (TYPE(obj) == T_STRING) {
236
+ obj = rb_funcall(obj, rb_intern("gsub"), 2, rb_reg_new("(?=[\\\\\"])", 9, 0), "\\");
237
+ return rb_funcall(obj, rb_intern("gsub!"), 2, rb_reg_new("^|$", 3, 0), "\"");
238
+ }
239
+ else {
240
+ return pgconn_s_format(NULL, obj);
241
+ }
242
+ }
243
+
244
+ /*
245
+ * call-seq:
246
+ * PGconn.quote( obj )
247
+ * PGconn.quote( obj ) { |obj| ... }
248
+ * PGconn.format( obj )
249
+ * PGconn.format( obj ) { |obj| ... }
250
+ *
251
+ * If _obj_ is a Number, String, Array, +nil+, +true+, or +false+ then
252
+ * #quote returns a String representation of that object safe for use in PostgreSQL.
253
+ *
254
+ * If _obj_ is not one of the above classes and a block is supplied to #quote,
255
+ * the block is invoked, passing along the object. The return value from the
256
+ * block is returned as a string.
257
+ *
258
+ * If _obj_ is not one of the recognized classes andno block is supplied,
259
+ * a PGError is raised.
260
+ */
261
+ static VALUE
262
+ pgconn_s_quote(self, obj)
263
+ VALUE self;
264
+ VALUE obj;
265
+ {
266
+ char* quoted;
267
+ int size;
268
+ VALUE result;
269
+
270
+ if (TYPE(obj) == T_STRING) {
271
+ quoted = ALLOCA_N(char, RSTRING(obj)->len * 2 + 1 + 2);
272
+ size = PQescapeString(quoted + 1, RSTRING(obj)->ptr, RSTRING(obj)->len);
273
+ *quoted = *(quoted + size + 1) = SINGLE_QUOTE;
274
+ result = rb_str_new(quoted, size + 2);
275
+ OBJ_INFECT(result, obj);
276
+ return result;
277
+ }
278
+ else {
279
+ return pgconn_s_format(self, obj);
280
+ }
281
+ }
282
+
283
+ static int
284
+ build_key_value_string_i(key, value, result)
285
+ VALUE key, value, result;
286
+ {
287
+ VALUE key_value;
288
+ if (key == Qundef) return ST_CONTINUE;
289
+ key_value = rb_str_dup(key);
290
+ rb_str_cat(key_value, "=", 1);
291
+ rb_str_concat(key_value, pgconn_s_quote(NULL, value));
292
+ rb_ary_push(result, key_value);
293
+ return ST_CONTINUE;
294
+ }
295
+
296
+ /*
297
+ * call-seq:
298
+ * PGconn.escape( str )
299
+ *
300
+ * Returns a SQL-safe version of the String _str_. Unlike #quote, does not wrap the String in '...'.
301
+ */
302
+ static VALUE
303
+ pgconn_s_escape(self, string)
304
+ VALUE self;
305
+ VALUE string;
306
+ {
307
+ char* escaped;
308
+ int size;
309
+ VALUE result;
310
+
311
+ Check_Type(string, T_STRING);
312
+
313
+ escaped = ALLOCA_N(char, RSTRING(string)->len * 2 + 1);
314
+ size = PQescapeString(escaped, RSTRING(string)->ptr, RSTRING(string)->len);
315
+ result = rb_str_new(escaped, size);
316
+ OBJ_INFECT(result, string);
317
+ return result;
318
+ }
319
+
320
+ /*
321
+ * call-seq:
322
+ * PGconn.escape_bytea( obj )
323
+ *
324
+ * Escapes binary data for use within an SQL command with the type +bytea+.
325
+ *
326
+ * Certain byte values must be escaped (but all byte values may be escaped)
327
+ * when used as part of a +bytea+ literal in an SQL statement. In general, to
328
+ * escape a byte, it is converted into the three digit octal number equal to
329
+ * the octet value, and preceded by two backslashes. The single quote (') and
330
+ * backslash (\) characters have special alternative escape sequences.
331
+ * #escape_bytea performs this operation, escaping only the minimally required bytes.
332
+ *
333
+ * See the PostgreSQL documentation on PQescapeBytea[http://www.postgresql.org/docs/current/interactive/libpq-exec.html#LIBPQ-EXEC-ESCAPE-BYTEA] for more information.
334
+ */
335
+ static VALUE
336
+ pgconn_s_escape_bytea(self, obj)
337
+ VALUE self;
338
+ VALUE obj;
339
+ {
340
+ unsigned char c;
341
+ char *from, *to;
342
+ long idx;
343
+ size_t from_len, to_len;
344
+ VALUE ret;
345
+
346
+ Check_Type(obj, T_STRING);
347
+ from = RSTRING(obj)->ptr;
348
+ from_len = RSTRING(obj)->len;
349
+
350
+ to = (char *)PQescapeBytea(from, from_len, &to_len);
351
+
352
+ ret = rb_str_new(to, to_len - 1);
353
+ OBJ_INFECT(ret, obj);
354
+
355
+ PQfreemem(to);
356
+
357
+ return ret;
358
+ }
359
+
360
+ /*
361
+ * call-seq:
362
+ * PGconn.unescape_bytea( obj )
363
+ *
364
+ * Converts an escaped string representation of binary data into binary data --- the
365
+ * reverse of #escape_bytea. This is needed when retrieving +bytea+ data in text format,
366
+ * but not when retrieving it in binary format.
367
+ *
368
+ * See the PostgreSQL documentation on PQunescapeBytea[http://www.postgresql.org/docs/current/interactive/libpq-exec.html#LIBPQ-EXEC-ESCAPE-BYTEA] for more information.
369
+ */
370
+ static VALUE
371
+ pgconn_s_unescape_bytea(self, obj)
372
+ VALUE self;
373
+ VALUE obj;
374
+ {
375
+ char *from, *to;
376
+ size_t to_len;
377
+ VALUE ret;
378
+
379
+ Check_Type(obj, T_STRING);
380
+ from = StringValuePtr(obj);
381
+
382
+ to = (char *)PQunescapeBytea(from, &to_len);
383
+
384
+ ret = rb_str_new(to, to_len);
385
+ OBJ_INFECT(ret, obj);
386
+
387
+ PQfreemem(to);
388
+
389
+ return ret;
390
+ }
391
+
392
+ #ifndef HAVE_RB_DEFINE_ALLOC_FUNC
393
+ /*
394
+ * call-seq:
395
+ * PGconn.connect(host, port, options, tty, dbname, login, passwd) => conn
396
+ * PGconn.open( host, port, options, tty, dbname, login, passwd) => conn
397
+ * PGconn.new( host, port, options, tty, dbname, login, passwd) => conn
398
+ *
399
+ * _host_:: server hostname (String)
400
+ * _port_:: server port number (Integer)
401
+ * _options_:: backend options (String)
402
+ * _tty_:: tty to print backend debug message <i>(ignored in newer versions of PostgreSQL)</i> (String)
403
+ * _dbname_:: connecting database name (String)
404
+ * _login_:: login user name (String)
405
+ * _passwd_:: login password (String)
406
+ *
407
+ * On failure, it raises a PGError exception.
408
+ */
409
+ static VALUE
410
+ pgconn_s_new(argc, argv, klass)
411
+ int argc;
412
+ VALUE *argv;
413
+ VALUE klass;
414
+ {
415
+ VALUE obj = rb_obj_alloc(klass);
416
+ rb_obj_call_init(obj, argc, argv);
417
+ return obj;
418
+ }
419
+ #endif
420
+
421
+ /*
422
+ * See #new.
423
+ */
424
+ static VALUE
425
+ pgconn_init(argc, argv, self)
426
+ int argc;
427
+ VALUE *argv;
428
+ VALUE self;
429
+ {
430
+ return pgconn_connect(argc, argv, self);
431
+ }
432
+
433
+ static PGconn*
434
+ get_pgconn(obj)
435
+ VALUE obj;
436
+ {
437
+ PGconn *conn;
438
+
439
+ Data_Get_Struct(obj, PGconn, conn);
440
+ if (conn == 0) rb_raise(rb_ePGError, "closed connection");
441
+ return conn;
442
+ }
443
+
444
+ /*
445
+ * call-seq:
446
+ * conn.close()
447
+ *
448
+ * Closes the backend connection.
449
+ */
450
+ static VALUE
451
+ pgconn_close(obj)
452
+ VALUE obj;
453
+ {
454
+ PQfinish(get_pgconn(obj));
455
+ DATA_PTR(obj) = NULL;
456
+ return Qnil;
457
+ }
458
+
459
+ /*
460
+ * call-seq:
461
+ * conn.reset()
462
+ *
463
+ * Resets the backend connection. This method closes the backend connection and tries to re-connect.
464
+ */
465
+ static VALUE
466
+ pgconn_reset(obj)
467
+ VALUE obj;
468
+ {
469
+ PQreset(get_pgconn(obj));
470
+ return obj;
471
+ }
472
+
473
+ static PGresult*
474
+ get_pgresult(obj)
475
+ VALUE obj;
476
+ {
477
+ PGresult *result;
478
+ Data_Get_Struct(obj, PGresult, result);
479
+ if (result == NULL) rb_raise(rb_ePGError, "query not performed");
480
+ return result;
481
+ }
482
+
483
+ #ifndef HAVE_PQEXECPARAMS
484
+ PGresult *PQexecParams_compat(PGconn *conn, VALUE command, VALUE values);
485
+ #endif
486
+
487
+ /*
488
+ * call-seq:
489
+ * conn.exec( sql )
490
+ *
491
+ * Sends SQL query request specified by _sql_ to the PostgreSQL.
492
+ * Returns a PGresult instance on success.
493
+ * On failure, it raises a PGError exception.
494
+ */
495
+ static VALUE
496
+ pgconn_exec(argc, argv, obj)
497
+ int argc;
498
+ VALUE *argv;
499
+ VALUE obj;
500
+ {
501
+ PGconn *conn = get_pgconn(obj);
502
+ PGresult *result = NULL;
503
+ VALUE command, params;
504
+ char *msg;
505
+
506
+ rb_scan_args(argc, argv, "1*", &command, &params);
507
+
508
+ Check_Type(command, T_STRING);
509
+
510
+ if (RARRAY(params)->len <= 0) {
511
+ result = PQexec(conn, StringValuePtr(command));
512
+ }
513
+ else {
514
+ int len = RARRAY(params)->len;
515
+ int i;
516
+ #ifdef HAVE_PQEXECPARAMS
517
+ VALUE* ptr = RARRAY(params)->ptr;
518
+ const char ** values = ALLOCA_N(const char *, len);
519
+ VALUE formatted;
520
+ for (i = 0; i < len; i++, ptr++) {
521
+ if (*ptr == Qnil) {
522
+ values[i] = NULL;
523
+ }
524
+ else {
525
+ formatted = pgconn_s_format(NULL, *ptr);
526
+ values[i] = StringValuePtr(formatted);
527
+ }
528
+ }
529
+ result = PQexecParams(conn, StringValuePtr(command), len, NULL, values, NULL, NULL, 0);
530
+ #else
531
+ for (i = 0; i < len; i++) {
532
+ rb_ary_store(params, i, pgconn_s_quote(NULL, rb_ary_entry(params, i)));
533
+ }
534
+ result = PQexecParams_compat(conn, command, params);
535
+ #endif
536
+ }
537
+
538
+ if (!result) {
539
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
540
+ }
541
+
542
+ switch (PQresultStatus(result)) {
543
+ case PGRES_TUPLES_OK:
544
+ case PGRES_COPY_OUT:
545
+ case PGRES_COPY_IN:
546
+ case PGRES_EMPTY_QUERY:
547
+ case PGRES_COMMAND_OK: /* no data will be received */
548
+ return pgresult_new(result);
549
+
550
+ case PGRES_BAD_RESPONSE:
551
+ case PGRES_FATAL_ERROR:
552
+ case PGRES_NONFATAL_ERROR:
553
+ msg = RSTRING(rb_str_new2(PQresultErrorMessage(result)))->ptr;
554
+ break;
555
+ default:
556
+ msg = "internal error : unknown result status.";
557
+ break;
558
+ }
559
+ PQclear(result);
560
+ rb_raise(rb_ePGError, msg);
561
+ }
562
+
563
+ /*
564
+ * call-seq:
565
+ * conn.async_exec( sql )
566
+ *
567
+ * Sends an asyncrhonous SQL query request specified by _sql_ to the PostgreSQL.
568
+ * Returns a PGresult instance on success.
569
+ * On failure, it raises a PGError exception.
570
+ */
571
+ static VALUE
572
+ pgconn_async_exec(obj, str)
573
+ VALUE obj, str;
574
+ {
575
+ PGconn *conn = get_pgconn(obj);
576
+ PGresult *result;
577
+ char *msg;
578
+
579
+ int cs;
580
+ int ret;
581
+ fd_set rset;
582
+
583
+ Check_Type(str, T_STRING);
584
+
585
+ while (result = PQgetResult(conn)) {
586
+ PQclear(result);
587
+ }
588
+
589
+ if (!PQsendQuery(conn, RSTRING(str)->ptr)) {
590
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
591
+ }
592
+
593
+ cs = PQsocket(conn);
594
+ for(;;) {
595
+ FD_ZERO(&rset);
596
+ FD_SET(cs, &rset);
597
+ ret = rb_thread_select(cs + 1, &rset, NULL, NULL, NULL);
598
+ if (ret < 0) {
599
+ rb_sys_fail(0);
600
+ }
601
+
602
+ if (ret == 0) {
603
+ continue;
604
+ }
605
+
606
+ if (PQconsumeInput(conn) == 0) {
607
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
608
+ }
609
+
610
+ if (PQisBusy(conn) == 0) {
611
+ break;
612
+ }
613
+ }
614
+
615
+ result = PQgetResult(conn);
616
+
617
+ if (!result) {
618
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
619
+ }
620
+
621
+ switch (PQresultStatus(result)) {
622
+ case PGRES_TUPLES_OK:
623
+ case PGRES_COPY_OUT:
624
+ case PGRES_COPY_IN:
625
+ case PGRES_EMPTY_QUERY:
626
+ case PGRES_COMMAND_OK: /* no data will be received */
627
+ return pgresult_new(result);
628
+
629
+ case PGRES_BAD_RESPONSE:
630
+ case PGRES_FATAL_ERROR:
631
+ case PGRES_NONFATAL_ERROR:
632
+ msg = RSTRING(rb_str_new2(PQresultErrorMessage(result)))->ptr;
633
+ break;
634
+ default:
635
+ msg = "internal error : unknown result status.";
636
+ break;
637
+ }
638
+ PQclear(result);
639
+ rb_raise(rb_ePGError, msg);
640
+ }
641
+
642
+ /*
643
+ * call-seq:
644
+ * conn.query( sql )
645
+ *
646
+ * Sends SQL query request specified by _sql_ to the PostgreSQL.
647
+ * Returns an Array as the resulting tuple on success.
648
+ * On failure, it returns +nil+, and the error details can be obtained by #error.
649
+ */
650
+ static VALUE
651
+ pgconn_query(argc, argv, obj)
652
+ int argc;
653
+ VALUE *argv;
654
+ VALUE obj;
655
+ {
656
+ return pgresult_result_with_clear(pgconn_exec(argc, argv, obj));
657
+ }
658
+
659
+ /*
660
+ * call-seq:
661
+ * conn.async_query( sql )
662
+ *
663
+ * Sends an asynchronous SQL query request specified by _sql_ to the PostgreSQL.
664
+ * Returns an Array as the resulting tuple on success.
665
+ * On failure, it returns +nil+, and the error details can be obtained by #error.
666
+ */
667
+ static VALUE
668
+ pgconn_async_query(obj, str)
669
+ VALUE obj, str;
670
+ {
671
+ return pgresult_result_with_clear(pgconn_async_exec(obj, str));
672
+ }
673
+
674
+ /*
675
+ * call-seq:
676
+ * conn.get_notify()
677
+ *
678
+ * Returns an array of the unprocessed notifiers.
679
+ * If there is no unprocessed notifier, it returns +nil+.
680
+ */
681
+ static VALUE
682
+ pgconn_get_notify(obj)
683
+ VALUE obj;
684
+ {
685
+ PGconn* conn = get_pgconn(obj);
686
+ PGnotify *notify;
687
+ VALUE ary;
688
+
689
+ if (PQconsumeInput(conn) == 0) {
690
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
691
+ }
692
+ /* gets notify and builds result */
693
+ notify = PQnotifies(conn);
694
+ if (notify == NULL) {
695
+ /* there are no unhandled notifications */
696
+ return Qnil;
697
+ }
698
+ ary = rb_ary_new3(2, rb_tainted_str_new2(notify->relname), INT2NUM(notify->be_pid));
699
+ PQfreemem(notify);
700
+
701
+ /* returns result */
702
+ return ary;
703
+ }
704
+
705
+ static VALUE pg_escape_regex;
706
+ static VALUE pg_escape_str;
707
+ static ID pg_gsub_bang_id;
708
+
709
+ static void
710
+ free_pgconn(ptr)
711
+ PGconn *ptr;
712
+ {
713
+ PQfinish(ptr);
714
+ }
715
+
716
+ /*
717
+ * call-seq:
718
+ * conn.insert_table( table, values )
719
+ *
720
+ * Inserts contents of the _values_ Array into the _table_.
721
+ */
722
+ static VALUE
723
+ pgconn_insert_table(obj, table, values)
724
+ VALUE obj, table, values;
725
+ {
726
+ PGconn *conn = get_pgconn(obj);
727
+ PGresult *result;
728
+ VALUE s, buffer;
729
+ int i, j;
730
+ int res = 0;
731
+
732
+ Check_Type(table, T_STRING);
733
+ Check_Type(values, T_ARRAY);
734
+ i = RARRAY(values)->len;
735
+ while (i--) {
736
+ if (TYPE(RARRAY(RARRAY(values)->ptr[i])) != T_ARRAY) {
737
+ rb_raise(rb_ePGError, "second arg must contain some kind of arrays.");
738
+ }
739
+ }
740
+
741
+ buffer = rb_str_new(0, RSTRING(table)->len + 17 + 1);
742
+ /* starts query */
743
+ snprintf(RSTRING(buffer)->ptr, RSTRING(buffer)->len, "copy %s from stdin ", StringValuePtr(table));
744
+
745
+ result = PQexec(conn, StringValuePtr(buffer));
746
+ if (!result){
747
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
748
+ }
749
+ PQclear(result);
750
+
751
+ for (i = 0; i < RARRAY(values)->len; i++) {
752
+ struct RArray *row = RARRAY(RARRAY(values)->ptr[i]);
753
+ buffer = rb_tainted_str_new(0,0);
754
+ for (j = 0; j < row->len; j++) {
755
+ if (j > 0) rb_str_cat(buffer, "\t", 1);
756
+ if (NIL_P(row->ptr[j])) {
757
+ rb_str_cat(buffer, "\\N",2);
758
+ } else {
759
+ s = rb_obj_as_string(row->ptr[j]);
760
+ rb_funcall(s,pg_gsub_bang_id,2,pg_escape_regex,pg_escape_str);
761
+ rb_str_cat(buffer, StringValuePtr(s), RSTRING(s)->len);
762
+ }
763
+ }
764
+ rb_str_cat(buffer, "\n\0", 2);
765
+ /* sends data */
766
+ PQputline(conn, StringValuePtr(buffer));
767
+ }
768
+ PQputline(conn, "\\.\n");
769
+ res = PQendcopy(conn);
770
+
771
+ return obj;
772
+ }
773
+
774
+ /*
775
+ * call-seq:
776
+ * conn.putline()
777
+ *
778
+ * Sends the string to the backend server.
779
+ * Users must send a single "." to denote the end of data transmission.
780
+ */
781
+ static VALUE
782
+ pgconn_putline(obj, str)
783
+ VALUE obj, str;
784
+ {
785
+ Check_Type(str, T_STRING);
786
+ PQputline(get_pgconn(obj), StringValuePtr(str));
787
+ return obj;
788
+ }
789
+
790
+ /*
791
+ * call-seq:
792
+ * conn.getline()
793
+ *
794
+ * Reads a line from the backend server into internal buffer.
795
+ * Returns +nil+ for EOF, +0+ for success, +1+ for buffer overflowed.
796
+ * You need to ensure single "." from backend to confirm transmission completion.
797
+ * The sample program <tt>psql.rb</tt> (see source for postgres) treats this copy protocol right.
798
+ */
799
+ static VALUE
800
+ pgconn_getline(obj)
801
+ VALUE obj;
802
+ {
803
+ PGconn *conn = get_pgconn(obj);
804
+ VALUE str;
805
+ long size = BUFSIZ;
806
+ long bytes = 0;
807
+ int ret;
808
+
809
+ str = rb_tainted_str_new(0, size);
810
+
811
+ for (;;) {
812
+ ret = PQgetline(conn, RSTRING(str)->ptr + bytes, size - bytes);
813
+ switch (ret) {
814
+ case EOF:
815
+ return Qnil;
816
+ case 0:
817
+ rb_str_resize(str, strlen(StringValuePtr(str)));
818
+ return str;
819
+ }
820
+ bytes += BUFSIZ;
821
+ size += BUFSIZ;
822
+ rb_str_resize(str, size);
823
+ }
824
+ return Qnil;
825
+ }
826
+
827
+ /*
828
+ * call-seq:
829
+ * conn.endcopy()
830
+ *
831
+ * Waits until the backend completes the copying.
832
+ * You should call this method after #putline or #getline.
833
+ * Returns +nil+ on success; raises an exception otherwise.
834
+ */
835
+ static VALUE
836
+ pgconn_endcopy(obj)
837
+ VALUE obj;
838
+ {
839
+ if (PQendcopy(get_pgconn(obj)) == 1) {
840
+ rb_raise(rb_ePGError, "cannot complete copying");
841
+ }
842
+ return Qnil;
843
+ }
844
+
845
+ static void
846
+ notice_proxy(self, message)
847
+ VALUE self;
848
+ const char *message;
849
+ {
850
+ VALUE block;
851
+ if ((block = rb_iv_get(self, "@on_notice")) != Qnil) {
852
+ rb_funcall(block, rb_intern("call"), 1, rb_str_new2(message));
853
+ }
854
+ }
855
+
856
+ /*
857
+ * call-seq:
858
+ * conn.on_notice {|message| ... }
859
+ *
860
+ * Notice and warning messages generated by the server are not returned
861
+ * by the query execution functions, since they do not imply failure of
862
+ * the query. Instead they are passed to a notice handling function, and
863
+ * execution continues normally after the handler returns. The default
864
+ * notice handling function prints the message on <tt>stderr</tt>, but the
865
+ * application can override this behavior by supplying its own handling
866
+ * function.
867
+ */
868
+ static VALUE
869
+ pgconn_on_notice(self)
870
+ VALUE self;
871
+ {
872
+ VALUE block = rb_block_proc();
873
+ PGconn *conn = get_pgconn(self);
874
+ if (PQsetNoticeProcessor(conn, NULL, NULL) != notice_proxy) {
875
+ PQsetNoticeProcessor(conn, notice_proxy, (void *) self);
876
+ }
877
+ rb_iv_set(self, "@on_notice", block);
878
+ return self;
879
+ }
880
+
881
+ /*
882
+ * call-seq:
883
+ * conn.host()
884
+ *
885
+ * Returns the connected server name.
886
+ */
887
+ static VALUE
888
+ pgconn_host(obj)
889
+ VALUE obj;
890
+ {
891
+ char *host = PQhost(get_pgconn(obj));
892
+ if (!host) return Qnil;
893
+ return rb_tainted_str_new2(host);
894
+ }
895
+
896
+ /*
897
+ * call-seq:
898
+ * conn.port()
899
+ *
900
+ * Returns the connected server port number.
901
+ */
902
+ static VALUE
903
+ pgconn_port(obj)
904
+ VALUE obj;
905
+ {
906
+ char* port = PQport(get_pgconn(obj));
907
+ return INT2NUM(atol(port));
908
+ }
909
+
910
+ /*
911
+ * call-seq:
912
+ * conn.db()
913
+ *
914
+ * Returns the connected database name.
915
+ */
916
+ static VALUE
917
+ pgconn_db(obj)
918
+ VALUE obj;
919
+ {
920
+ char *db = PQdb(get_pgconn(obj));
921
+ if (!db) return Qnil;
922
+ return rb_tainted_str_new2(db);
923
+ }
924
+
925
+ /*
926
+ * call-seq:
927
+ * conn.options()
928
+ *
929
+ * Returns backend option string.
930
+ */
931
+ static VALUE
932
+ pgconn_options(obj)
933
+ VALUE obj;
934
+ {
935
+ char *options = PQoptions(get_pgconn(obj));
936
+ if (!options) return Qnil;
937
+ return rb_tainted_str_new2(options);
938
+ }
939
+
940
+ /*
941
+ * call-seq:
942
+ * conn.tty()
943
+ *
944
+ * Returns the connected pgtty.
945
+ */
946
+ static VALUE
947
+ pgconn_tty(obj)
948
+ VALUE obj;
949
+ {
950
+ char *tty = PQtty(get_pgconn(obj));
951
+ if (!tty) return Qnil;
952
+ return rb_tainted_str_new2(tty);
953
+ }
954
+
955
+ /*
956
+ * call-seq:
957
+ * conn.user()
958
+ *
959
+ * Returns the authenticated user name.
960
+ */
961
+ static VALUE
962
+ pgconn_user(obj)
963
+ VALUE obj;
964
+ {
965
+ char *user = PQuser(get_pgconn(obj));
966
+ if (!user) return Qnil;
967
+ return rb_tainted_str_new2(user);
968
+ }
969
+
970
+ /*
971
+ * call-seq:
972
+ * conn.status()
973
+ *
974
+ * MISSING: documentation
975
+ */
976
+ static VALUE
977
+ pgconn_status(obj)
978
+ VALUE obj;
979
+ {
980
+ return INT2NUM(PQstatus(get_pgconn(obj)));
981
+ }
982
+
983
+ /*
984
+ * call-seq:
985
+ * conn.error()
986
+ *
987
+ * Returns the error message about connection.
988
+ */
989
+ static VALUE
990
+ pgconn_error(obj)
991
+ VALUE obj;
992
+ {
993
+ char *error = PQerrorMessage(get_pgconn(obj));
994
+ if (!error) return Qnil;
995
+ return rb_tainted_str_new2(error);
996
+ }
997
+
998
+ /*
999
+ * call-seq:
1000
+ * conn.trace( port )
1001
+ *
1002
+ * Enables tracing message passing between backend.
1003
+ * The trace message will be written to the _port_ object,
1004
+ * which is an instance of the class +File+.
1005
+ */
1006
+ static VALUE
1007
+ pgconn_trace(obj, port)
1008
+ VALUE obj, port;
1009
+ {
1010
+ OpenFile* fp;
1011
+
1012
+ Check_Type(port, T_FILE);
1013
+ GetOpenFile(port, fp);
1014
+
1015
+ PQtrace(get_pgconn(obj), fp->f2?fp->f2:fp->f);
1016
+
1017
+ return obj;
1018
+ }
1019
+
1020
+ /*
1021
+ * call-seq:
1022
+ * conn.untrace()
1023
+ *
1024
+ * Disables the message tracing.
1025
+ */
1026
+ static VALUE
1027
+ pgconn_untrace(obj)
1028
+ VALUE obj;
1029
+ {
1030
+ PQuntrace(get_pgconn(obj));
1031
+ return obj;
1032
+ }
1033
+
1034
+ /*
1035
+ * call-seq:
1036
+ * conn.transaction_status()
1037
+ *
1038
+ * returns one of the following statuses:
1039
+ * PQTRANS_IDLE = 0 (connection idle)
1040
+ * PQTRANS_ACTIVE = 1 (command in progress)
1041
+ * PQTRANS_INTRANS = 2 (idle, within transaction block)
1042
+ * PQTRANS_INERROR = 3 (idle, within failed transaction)
1043
+ * PQTRANS_UNKNOWN = 4 (cannot determine status)
1044
+ *
1045
+ * See the PostgreSQL documentation on PQtransactionStatus[http://www.postgresql.org/docs/current/interactive/libpq-status.html#AEN24919] for more information.
1046
+ */
1047
+ static VALUE
1048
+ pgconn_transaction_status(obj)
1049
+ VALUE obj;
1050
+ {
1051
+ return INT2NUM(PQtransactionStatus(get_pgconn(obj)));
1052
+ }
1053
+
1054
+ #ifdef HAVE_PQSETCLIENTENCODING
1055
+
1056
+ static VALUE
1057
+ pgconn_protocol_version(obj)
1058
+ VALUE obj;
1059
+ {
1060
+ return INT2NUM(PQprotocolVersion(get_pgconn(obj)));
1061
+ }
1062
+
1063
+ static VALUE
1064
+ pgconn_server_version(obj)
1065
+ VALUE obj;
1066
+ {
1067
+ return INT2NUM(PQserverVersion(get_pgconn(obj)));
1068
+ }
1069
+
1070
+ static VALUE
1071
+ pgconn_lastval(obj)
1072
+ VALUE obj;
1073
+ {
1074
+ PGconn *conn = get_pgconn(obj);
1075
+ PGresult *result;
1076
+ VALUE lastval, error;
1077
+
1078
+ if (PQserverVersion(conn) < 80100) return Qnil;
1079
+
1080
+ result = PQexec(conn, "select lastval()");
1081
+ if (!result) rb_raise(rb_ePGError, PQerrorMessage(conn));
1082
+
1083
+ switch (PQresultStatus(result)) {
1084
+ case PGRES_TUPLES_OK:
1085
+ lastval = rb_cstr2inum(PQgetvalue(result, 0, 0), 10);
1086
+ PQclear(result);
1087
+ return lastval;
1088
+
1089
+ case PGRES_BAD_RESPONSE:
1090
+ case PGRES_FATAL_ERROR:
1091
+ case PGRES_NONFATAL_ERROR:
1092
+ error = rb_str_new2(PQresultErrorMessage(result));
1093
+ PQclear(result);
1094
+ rb_raise(rb_ePGError, StringValuePtr(error));
1095
+
1096
+ default:
1097
+ PQclear(result);
1098
+ rb_raise(rb_ePGError, "unknown lastval");
1099
+ }
1100
+ }
1101
+
1102
+ /*
1103
+ * call-seq:
1104
+ * conn.client_encoding() => String
1105
+ *
1106
+ * Returns the client encoding as a String.
1107
+ */
1108
+ static VALUE
1109
+ pgconn_client_encoding(obj)
1110
+ VALUE obj;
1111
+ {
1112
+ char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(get_pgconn(obj)));
1113
+ return rb_tainted_str_new2(encoding);
1114
+ }
1115
+
1116
+ /*
1117
+ * call-seq:
1118
+ * conn.set_client_encoding( encoding )
1119
+ *
1120
+ * Sets the client encoding to the _encoding_ String.
1121
+ */
1122
+ static VALUE
1123
+ pgconn_set_client_encoding(obj, str)
1124
+ VALUE obj, str;
1125
+ {
1126
+ Check_Type(str, T_STRING);
1127
+ if ((PQsetClientEncoding(get_pgconn(obj), StringValuePtr(str))) == -1){
1128
+ rb_raise(rb_ePGError, "invalid encoding name %s",str);
1129
+ }
1130
+ return Qnil;
1131
+ }
1132
+ #endif
1133
+
1134
+ static void
1135
+ free_pgresult(ptr)
1136
+ PGresult *ptr;
1137
+ {
1138
+ PQclear(ptr);
1139
+ }
1140
+
1141
+ #define PARSE(klass, string) rb_funcall(klass, rb_intern("parse"), 1, rb_tainted_str_new2(string));
1142
+
1143
+ static VALUE
1144
+ fetch_pgresult(result, row, column)
1145
+ PGresult *result;
1146
+ int row;
1147
+ int column;
1148
+ {
1149
+ if (PQgetisnull(result, row, column)) {
1150
+ return Qnil;
1151
+ }
1152
+
1153
+ char* string = PQgetvalue(result, row, column);
1154
+ switch (PQftype(result, column)) {
1155
+
1156
+ case BOOLOID:
1157
+ return *string == 't' ? Qtrue : Qfalse;
1158
+
1159
+ case BYTEAOID:
1160
+ return pgconn_s_unescape_bytea(rb_tainted_str_new2(string));
1161
+
1162
+ case INT8OID:
1163
+ case INT4OID:
1164
+ case INT2OID:
1165
+ return rb_cstr2inum(string, 10);
1166
+
1167
+ case NUMERICOID:
1168
+ return rb_funcall(rb_mKernel, rb_intern("BigDecimal"), 1, rb_tainted_str_new2(string));
1169
+
1170
+ case FLOAT8OID:
1171
+ case FLOAT4OID:
1172
+ return rb_float(rb_cstr_to_dbl(string, Qfalse));
1173
+
1174
+ case DATEOID:
1175
+ return PARSE(rb_cDate, string);
1176
+ case TIMEOID:
1177
+ case TIMETZOID:
1178
+ return PARSE(rb_cTime, string);
1179
+ case TIMESTAMPOID:
1180
+ case TIMESTAMPTZOID:
1181
+ return PARSE(rb_cDateTime, string);
1182
+
1183
+ default:
1184
+ return rb_tainted_str_new2(string);
1185
+ }
1186
+ }
1187
+
1188
+
1189
+ static VALUE
1190
+ pgresult_new(ptr)
1191
+ PGresult *ptr;
1192
+ {
1193
+ return Data_Wrap_Struct(rb_cPGresult, 0, free_pgresult, ptr);
1194
+ }
1195
+
1196
+ /*
1197
+ * call-seq:
1198
+ * res.status()
1199
+ *
1200
+ * Returns the status of the query. The status value is one of:
1201
+ * * +EMPTY_QUERY+
1202
+ * * +COMMAND_OK+
1203
+ * * +TUPLES_OK+
1204
+ * * +COPY_OUT+
1205
+ * * +COPY_IN+
1206
+ */
1207
+ static VALUE
1208
+ pgresult_status(obj)
1209
+ VALUE obj;
1210
+ {
1211
+ return INT2NUM(PQresultStatus(get_pgresult(obj)));
1212
+ }
1213
+
1214
+ /*
1215
+ * call-seq:
1216
+ * res.result()
1217
+ *
1218
+ * Returns an array of tuples (rows, which are themselves arrays) that represent the query result.
1219
+ */
1220
+
1221
+ /*
1222
+ * call-seq:
1223
+ * res.each{ |tuple| ... }
1224
+ *
1225
+ * Invokes the block for each tuple (row) in the result.
1226
+ *
1227
+ * Equivalent to <tt>res.result.each{ |tuple| ... }</tt>.
1228
+ */
1229
+ static VALUE
1230
+ pgresult_each(self)
1231
+ VALUE self;
1232
+ {
1233
+ int i, j;
1234
+
1235
+ PGresult *result = get_pgresult(self);
1236
+ int nt = PQntuples(result);
1237
+ int nf = PQnfields(result);
1238
+ VALUE fields[1] = { rb_ary_new2(nf) };
1239
+
1240
+ for (i = 0; i < nf; i++)
1241
+ rb_ary_push(fields[0], rb_tainted_str_new2(PQfname(result, i)));
1242
+
1243
+ for (i=0; i<nt; i++) {
1244
+ VALUE row = rb_funcall2(rb_cPGrow, rb_intern("new"), 1, fields);
1245
+ for (j=0; j<nf; j++) {
1246
+ rb_ary_store(row, j, fetch_pgresult(result, i, j));
1247
+ }
1248
+ rb_yield(row);
1249
+ }
1250
+
1251
+ return self;
1252
+ }
1253
+
1254
+ /*
1255
+ * call-seq:
1256
+ * res[ n ]
1257
+ *
1258
+ * Returns the tuple (row) corresponding to _n_. Returns +nil+ if <tt>_n_ >= res.num_tuples</tt>.
1259
+ *
1260
+ * Equivalent to <tt>res.result[n]</tt>.
1261
+ */
1262
+ static VALUE
1263
+ pgresult_aref(argc, argv, obj)
1264
+ int argc;
1265
+ VALUE *argv;
1266
+ VALUE obj;
1267
+ {
1268
+ PGresult *result;
1269
+ VALUE a1, a2, val;
1270
+ int i, j, nf, nt;
1271
+
1272
+ result = get_pgresult(obj);
1273
+ nt = PQntuples(result);
1274
+ nf = PQnfields(result);
1275
+ switch (rb_scan_args(argc, argv, "11", &a1, &a2)) {
1276
+ case 1:
1277
+ i = NUM2INT(a1);
1278
+ if( i >= nt ) return Qnil;
1279
+
1280
+ val = rb_ary_new();
1281
+ for (j=0; j<nf; j++) {
1282
+ VALUE value = fetch_pgresult(result, i, j);
1283
+ rb_ary_push(val, value);
1284
+ }
1285
+ return val;
1286
+
1287
+ case 2:
1288
+ i = NUM2INT(a1);
1289
+ if( i >= nt ) return Qnil;
1290
+ j = NUM2INT(a2);
1291
+ if( j >= nf ) return Qnil;
1292
+ return fetch_pgresult(result, i, j);
1293
+
1294
+ default:
1295
+ return Qnil; /* not reached */
1296
+ }
1297
+ }
1298
+
1299
+ /*
1300
+ * call-seq:
1301
+ * res.fields()
1302
+ *
1303
+ * Returns an array of Strings representing the names of the fields in the result.
1304
+ *
1305
+ * res=conn.exec("SELECT foo,bar AS biggles,jim,jam FROM mytable;")
1306
+ * res.fields => [ 'foo' , 'biggles' , 'jim' , 'jam' ]
1307
+ */
1308
+ static VALUE
1309
+ pgresult_fields(obj)
1310
+ VALUE obj;
1311
+ {
1312
+ PGresult *result;
1313
+ VALUE ary;
1314
+ int n, i;
1315
+
1316
+ result = get_pgresult(obj);
1317
+ n = PQnfields(result);
1318
+ ary = rb_ary_new2(n);
1319
+ for (i=0;i<n;i++) {
1320
+ rb_ary_push(ary, rb_tainted_str_new2(PQfname(result, i)));
1321
+ }
1322
+ return ary;
1323
+ }
1324
+
1325
+ /*
1326
+ * call-seq:
1327
+ * res.num_tuples()
1328
+ *
1329
+ * Returns the number of tuples (rows) in the query result.
1330
+ *
1331
+ * Similar to <tt>res.result.length</tt> (but faster).
1332
+ */
1333
+ static VALUE
1334
+ pgresult_num_tuples(obj)
1335
+ VALUE obj;
1336
+ {
1337
+ int n;
1338
+
1339
+ n = PQntuples(get_pgresult(obj));
1340
+ return INT2NUM(n);
1341
+ }
1342
+
1343
+ /*
1344
+ * call-seq:
1345
+ * res.num_fields()
1346
+ *
1347
+ * Returns the number of fields (columns) in the query result.
1348
+ *
1349
+ * Similar to <tt>res.result[0].length</tt> (but faster).
1350
+ */
1351
+ static VALUE
1352
+ pgresult_num_fields(obj)
1353
+ VALUE obj;
1354
+ {
1355
+ int n;
1356
+
1357
+ n = PQnfields(get_pgresult(obj));
1358
+ return INT2NUM(n);
1359
+ }
1360
+
1361
+ /*
1362
+ * call-seq:
1363
+ * res.fieldname( index )
1364
+ *
1365
+ * Returns the name of the field (column) corresponding to the index.
1366
+ *
1367
+ * res=conn.exec("SELECT foo,bar AS biggles,jim,jam FROM mytable;")
1368
+ * puts res.fieldname(2) => 'jim'
1369
+ * puts res.fieldname(1) => 'biggles'
1370
+ *
1371
+ * Equivalent to <tt>res.fields[_index_]</tt>.
1372
+ */
1373
+ static VALUE
1374
+ pgresult_fieldname(obj, index)
1375
+ VALUE obj, index;
1376
+ {
1377
+ PGresult *result;
1378
+ int i = NUM2INT(index);
1379
+ char *name;
1380
+
1381
+ result = get_pgresult(obj);
1382
+ if (i < 0 || i >= PQnfields(result)) {
1383
+ rb_raise(rb_eArgError,"invalid field number %d", i);
1384
+ }
1385
+ name = PQfname(result, i);
1386
+ return rb_tainted_str_new2(name);
1387
+ }
1388
+
1389
+ /*
1390
+ * call-seq:
1391
+ * res.fieldnum( name )
1392
+ *
1393
+ * Returns the index of the field specified by the string _name_.
1394
+ *
1395
+ * res=conn.exec("SELECT foo,bar AS biggles,jim,jam FROM mytable;")
1396
+ * puts res.fieldnum('foo') => 0
1397
+ *
1398
+ * Raises an ArgumentError if the specified _name_ isn't one of the field names;
1399
+ * raises a TypeError if _name_ is not a String.
1400
+ */
1401
+ static VALUE
1402
+ pgresult_fieldnum(obj, name)
1403
+ VALUE obj, name;
1404
+ {
1405
+ int n;
1406
+
1407
+ Check_Type(name, T_STRING);
1408
+
1409
+ n = PQfnumber(get_pgresult(obj), StringValuePtr(name));
1410
+ if (n == -1) {
1411
+ rb_raise(rb_eArgError,"Unknown field: %s", StringValuePtr(name));
1412
+ }
1413
+ return INT2NUM(n);
1414
+ }
1415
+
1416
+ /*
1417
+ * call-seq:
1418
+ * res.type( index )
1419
+ *
1420
+ * Returns the data type associated with the given column number.
1421
+ *
1422
+ * The integer returned is the internal +OID+ number (in PostgreSQL) of the type.
1423
+ * If you have the PostgreSQL source available, you can see the OIDs for every column type in the file <tt>src/include/catalog/pg_type.h</tt>.
1424
+ */
1425
+ static VALUE
1426
+ pgresult_type(obj, index)
1427
+ VALUE obj, index;
1428
+ {
1429
+ PGresult* result = get_pgresult(obj);
1430
+ int i = NUM2INT(index);
1431
+ if (i < 0 || i >= PQnfields(result)) {
1432
+ rb_raise(rb_eArgError, "invalid field number %d", i);
1433
+ }
1434
+ return INT2NUM(PQftype(result, i));
1435
+ }
1436
+
1437
+ /*
1438
+ * call-seq:
1439
+ * res.size( index )
1440
+ *
1441
+ * Returns the size of the field type in bytes. Returns <tt>-1</tt> if the field is variable sized.
1442
+ *
1443
+ * res = conn.exec("SELECT myInt, myVarChar50 FROM foo;")
1444
+ * res.size(0) => 4
1445
+ * res.size(1) => -1
1446
+ */
1447
+ static VALUE
1448
+ pgresult_size(obj, index)
1449
+ VALUE obj, index;
1450
+ {
1451
+ PGresult *result;
1452
+ int i = NUM2INT(index);
1453
+ int size;
1454
+
1455
+ result = get_pgresult(obj);
1456
+ if (i < 0 || i >= PQnfields(result)) {
1457
+ rb_raise(rb_eArgError,"invalid field number %d", i);
1458
+ }
1459
+ size = PQfsize(result, i);
1460
+ return INT2NUM(size);
1461
+ }
1462
+
1463
+ /*
1464
+ * call-seq:
1465
+ * res.value( tup_num, field_num )
1466
+ *
1467
+ * Returns the value in tuple number <i>tup_num</i>, field number <i>field_num</i>. (Row <i>tup_num</i>, column <i>field_num</i>.)
1468
+ *
1469
+ * Equivalent to <tt>res.result[<i>tup_num</i>][<i>field_num</i>]</tt> (but faster).
1470
+ */
1471
+ static VALUE
1472
+ pgresult_getvalue(obj, tup_num, field_num)
1473
+ VALUE obj, tup_num, field_num;
1474
+ {
1475
+ PGresult *result;
1476
+ int i = NUM2INT(tup_num);
1477
+ int j = NUM2INT(field_num);
1478
+
1479
+ result = get_pgresult(obj);
1480
+ if (i < 0 || i >= PQntuples(result)) {
1481
+ rb_raise(rb_eArgError,"invalid tuple number %d", i);
1482
+ }
1483
+ if (j < 0 || j >= PQnfields(result)) {
1484
+ rb_raise(rb_eArgError,"invalid field number %d", j);
1485
+ }
1486
+
1487
+ return fetch_pgresult(result, i, j);
1488
+ }
1489
+
1490
+
1491
+ /*
1492
+ * call-seq:
1493
+ * res.value_byname( tup_num, field_name )
1494
+ *
1495
+ * Returns the value in tuple number <i>tup_num</i>, for the field named <i>field_name</i>.
1496
+ *
1497
+ * Equivalent to (but faster than) either of:
1498
+ * res.result[<i>tup_num</i>][ res.fieldnum(<i>field_name</i>) ]
1499
+ * res.value( <i>tup_num</i>, res.fieldnum(<i>field_name</i>) )
1500
+ *
1501
+ * <i>(This method internally calls #value as like the second example above; it is slower than using the field index directly.)</i>
1502
+ */
1503
+ static VALUE
1504
+ pgresult_getvalue_byname(obj, tup_num, field_name)
1505
+ VALUE obj, tup_num, field_name;
1506
+ {
1507
+ return pgresult_getvalue(obj, tup_num, pgresult_fieldnum(obj, field_name));
1508
+ }
1509
+
1510
+
1511
+ /*
1512
+ * call-seq:
1513
+ * res.getlength( tup_num, field_num )
1514
+ *
1515
+ * Returns the (String) length of the field in bytes.
1516
+ *
1517
+ * Equivalent to <tt>res.value(<i>tup_num</i>,<i>field_num</i>).length</tt>.
1518
+ */
1519
+ static VALUE
1520
+ pgresult_getlength(obj, tup_num, field_num)
1521
+ VALUE obj, tup_num, field_num;
1522
+ {
1523
+ PGresult *result;
1524
+ int i = NUM2INT(tup_num);
1525
+ int j = NUM2INT(field_num);
1526
+
1527
+ result = get_pgresult(obj);
1528
+ if (i < 0 || i >= PQntuples(result)) {
1529
+ rb_raise(rb_eArgError,"invalid tuple number %d", i);
1530
+ }
1531
+ if (j < 0 || j >= PQnfields(result)) {
1532
+ rb_raise(rb_eArgError,"invalid field number %d", j);
1533
+ }
1534
+ return INT2FIX(PQgetlength(result, i, j));
1535
+ }
1536
+
1537
+ /*
1538
+ * call-seq:
1539
+ * res.getisnull( tup_num, field_num ) => true or false
1540
+ *
1541
+ * Returns +true+ if the specified value is +nil+; +false+ otherwise.
1542
+ *
1543
+ * Equivalent to <tt>res.value(<i>tup_num</i>,<i>field_num</i>)==+nil+</tt>.
1544
+ */
1545
+ static VALUE
1546
+ pgresult_getisnull(obj, tup_num, field_num)
1547
+ VALUE obj, tup_num, field_num;
1548
+ {
1549
+ PGresult *result;
1550
+ int i = NUM2INT(tup_num);
1551
+ int j = NUM2INT(field_num);
1552
+
1553
+ result = get_pgresult(obj);
1554
+ if (i < 0 || i >= PQntuples(result)) {
1555
+ rb_raise(rb_eArgError,"invalid tuple number %d", i);
1556
+ }
1557
+ if (j < 0 || j >= PQnfields(result)) {
1558
+ rb_raise(rb_eArgError,"invalid field number %d", j);
1559
+ }
1560
+ return PQgetisnull(result, i, j) ? Qtrue : Qfalse;
1561
+ }
1562
+
1563
+ /*
1564
+ * call-seq:
1565
+ * res.print( file, opt )
1566
+ *
1567
+ * MISSING: Documentation
1568
+ */
1569
+ static VALUE
1570
+ pgresult_print(obj, file, opt)
1571
+ VALUE obj, file, opt;
1572
+ {
1573
+ VALUE value;
1574
+ ID mem;
1575
+ OpenFile* fp;
1576
+ PQprintOpt po;
1577
+
1578
+ Check_Type(file, T_FILE);
1579
+ Check_Type(opt, T_STRUCT);
1580
+ GetOpenFile(file, fp);
1581
+
1582
+ memset(&po, 0, sizeof(po));
1583
+
1584
+ mem = rb_intern("header");
1585
+ value = rb_struct_getmember(opt, mem);
1586
+ po.header = value == Qtrue ? 1 : 0;
1587
+
1588
+ mem = rb_intern("align");
1589
+ value = rb_struct_getmember(opt, mem);
1590
+ po.align = value == Qtrue ? 1 : 0;
1591
+
1592
+ mem = rb_intern("standard");
1593
+ value = rb_struct_getmember(opt, mem);
1594
+ po.standard = value == Qtrue ? 1 : 0;
1595
+
1596
+ mem = rb_intern("html3");
1597
+ value = rb_struct_getmember(opt, mem);
1598
+ po.html3 = value == Qtrue ? 1 : 0;
1599
+
1600
+ mem = rb_intern("expanded");
1601
+ value = rb_struct_getmember(opt, mem);
1602
+ po.expanded = value == Qtrue ? 1 : 0;
1603
+
1604
+ mem = rb_intern("pager");
1605
+ value = rb_struct_getmember(opt, mem);
1606
+ po.pager = value == Qtrue ? 1 : 0;
1607
+
1608
+ mem = rb_intern("fieldSep");
1609
+ value = rb_struct_getmember(opt, mem);
1610
+ if (!NIL_P(value)) {
1611
+ Check_Type(value, T_STRING);
1612
+ po.fieldSep = StringValuePtr(value);
1613
+ }
1614
+
1615
+ mem = rb_intern("tableOpt");
1616
+ value = rb_struct_getmember(opt, mem);
1617
+ if (!NIL_P(value)) {
1618
+ Check_Type(value, T_STRING);
1619
+ po.tableOpt = StringValuePtr(value);
1620
+ }
1621
+
1622
+ mem = rb_intern("caption");
1623
+ value = rb_struct_getmember(opt, mem);
1624
+ if (!NIL_P(value)) {
1625
+ Check_Type(value, T_STRING);
1626
+ po.caption = StringValuePtr(value);
1627
+ }
1628
+
1629
+ PQprint(fp->f2?fp->f2:fp->f, get_pgresult(obj), &po);
1630
+ return obj;
1631
+ }
1632
+
1633
+ /*
1634
+ * call-seq:
1635
+ * res.cmdtuples()
1636
+ *
1637
+ * Returns the number of tuples (rows) affected by the SQL command.
1638
+ *
1639
+ * If the SQL command that generated the PGresult was not one of +INSERT+, +UPDATE+, +DELETE+, +MOVE+, or +FETCH+, or if no tuples (rows) were affected, +0+ is returned.
1640
+ */
1641
+ static VALUE
1642
+ pgresult_cmdtuples(obj)
1643
+ VALUE obj;
1644
+ {
1645
+ long n;
1646
+ n = strtol(PQcmdTuples(get_pgresult(obj)),NULL, 10);
1647
+ return INT2NUM(n);
1648
+ }
1649
+ /*
1650
+ * call-seq:
1651
+ * res.cmdstatus()
1652
+ *
1653
+ * Returns the status string of the last query command.
1654
+ */
1655
+ static VALUE
1656
+ pgresult_cmdstatus(obj)
1657
+ VALUE obj;
1658
+ {
1659
+ return rb_tainted_str_new2(PQcmdStatus(get_pgresult(obj)));
1660
+ }
1661
+
1662
+ /*
1663
+ * call-seq:
1664
+ * res.oid()
1665
+ *
1666
+ * Returns the +oid+.
1667
+ */
1668
+ static VALUE
1669
+ pgresult_oid(obj)
1670
+ VALUE obj;
1671
+ {
1672
+ Oid n = PQoidValue(get_pgresult(obj));
1673
+ if (n == InvalidOid)
1674
+ return Qnil;
1675
+ else
1676
+ return INT2NUM(n);
1677
+ }
1678
+
1679
+ /*
1680
+ * call-seq:
1681
+ * res.clear()
1682
+ *
1683
+ * Clears the PGresult object as the result of the query.
1684
+ */
1685
+ static VALUE
1686
+ pgresult_clear(obj)
1687
+ VALUE obj;
1688
+ {
1689
+ PQclear(get_pgresult(obj));
1690
+ DATA_PTR(obj) = 0;
1691
+
1692
+ return Qnil;
1693
+ }
1694
+
1695
+ static VALUE
1696
+ pgresult_result_with_clear(self)
1697
+ VALUE self;
1698
+ {
1699
+ VALUE rows = rb_funcall(self, rb_intern("rows"), 0);
1700
+ pgresult_clear(self);
1701
+ return rows;
1702
+ }
1703
+
1704
+ /* Large Object support */
1705
+ static PGlarge*
1706
+ get_pglarge(obj)
1707
+ VALUE obj;
1708
+ {
1709
+ PGlarge *pglarge;
1710
+ Data_Get_Struct(obj, PGlarge, pglarge);
1711
+ if (pglarge == 0) rb_raise(rb_ePGError, "invalid large object");
1712
+ return pglarge;
1713
+ }
1714
+
1715
+ /*
1716
+ * call-seq:
1717
+ * conn.lo_import( file ) => pglarge
1718
+ *
1719
+ * Import a file to a large object. Returns a PGlarge instance on success. On failure, it raises a PGError exception.
1720
+ */
1721
+ static VALUE
1722
+ pgconn_loimport(obj, filename)
1723
+ VALUE obj, filename;
1724
+ {
1725
+ Oid lo_oid;
1726
+
1727
+ PGconn *conn = get_pgconn(obj);
1728
+
1729
+ Check_Type(filename, T_STRING);
1730
+
1731
+ lo_oid = lo_import(conn, StringValuePtr(filename));
1732
+ if (lo_oid == 0) {
1733
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
1734
+ }
1735
+ return pglarge_new(conn, lo_oid, -1);
1736
+ }
1737
+
1738
+ /*
1739
+ * call-seq:
1740
+ * conn.lo_export( oid, file )
1741
+ *
1742
+ * Saves a large object of _oid_ to a _file_.
1743
+ */
1744
+ static VALUE
1745
+ pgconn_loexport(obj, lo_oid,filename)
1746
+ VALUE obj, lo_oid, filename;
1747
+ {
1748
+ PGconn *conn = get_pgconn(obj);
1749
+ int oid;
1750
+ Check_Type(filename, T_STRING);
1751
+
1752
+ oid = NUM2INT(lo_oid);
1753
+ if (oid < 0) {
1754
+ rb_raise(rb_ePGError, "invalid large object oid %d",oid);
1755
+ }
1756
+
1757
+ if (!lo_export(conn, oid, StringValuePtr(filename))) {
1758
+ rb_raise(rb_ePGError, PQerrorMessage(conn));
1759
+ }
1760
+ return Qnil;
1761
+ }
1762
+
1763
+ /*
1764
+ * call-seq:
1765
+ * conn.lo_create( [mode] ) => pglarge
1766
+ *
1767
+ * Returns a PGlarge instance on success. On failure, it raises PGError exception.
1768
+ * <i>(See #lo_open for information on _mode_.)</i>
1769
+ */
1770
+ static VALUE
1771
+ pgconn_locreate(argc, argv, obj)
1772
+ int argc;
1773
+ VALUE *argv;
1774
+ VALUE obj;
1775
+ {
1776
+ Oid lo_oid;
1777
+ int mode;
1778
+ VALUE nmode;
1779
+ PGconn *conn;
1780
+
1781
+ if (rb_scan_args(argc, argv, "01", &nmode) == 0) {
1782
+ mode = INV_READ;
1783
+ }
1784
+ else {
1785
+ mode = FIX2INT(nmode);
1786
+ }
1787
+
1788
+ conn = get_pgconn(obj);
1789
+ lo_oid = lo_creat(conn, mode);
1790
+ if (lo_oid == 0){
1791
+ rb_raise(rb_ePGError, "can't creat large object");
1792
+ }
1793
+
1794
+ return pglarge_new(conn, lo_oid, -1);
1795
+ }
1796
+
1797
+ /*
1798
+ * call-seq:
1799
+ * conn.lo_open( oid, [mode] ) => pglarge
1800
+ *
1801
+ * Open a large object of _oid_. Returns a PGlarge instance on success.
1802
+ * The _mode_ argument specifies the mode for the opened large object,
1803
+ * which is either +INV_READ+, or +INV_WRITE+.
1804
+ * * If _mode_ On failure, it raises a PGError exception.
1805
+ * * If _mode_ is omitted, the default is +INV_READ+.
1806
+ */
1807
+ static VALUE
1808
+ pgconn_loopen(argc, argv, obj)
1809
+ int argc;
1810
+ VALUE *argv;
1811
+ VALUE obj;
1812
+ {
1813
+ Oid lo_oid;
1814
+ int fd, mode;
1815
+ VALUE nmode, objid;
1816
+ PGconn *conn = get_pgconn(obj);
1817
+
1818
+ switch (rb_scan_args(argc, argv, "02", &objid, &nmode)) {
1819
+ case 1:
1820
+ lo_oid = NUM2INT(objid);
1821
+ mode = INV_READ;
1822
+ break;
1823
+ case 2:
1824
+ lo_oid = NUM2INT(objid);
1825
+ mode = FIX2INT(nmode);
1826
+ break;
1827
+ default:
1828
+ mode = INV_READ;
1829
+ lo_oid = lo_creat(conn, mode);
1830
+ if (lo_oid == 0){
1831
+ rb_raise(rb_ePGError, "can't creat large object");
1832
+ }
1833
+ }
1834
+ if((fd = lo_open(conn, lo_oid, mode)) < 0) {
1835
+ rb_raise(rb_ePGError, "can't open large object");
1836
+ }
1837
+ return pglarge_new(conn, lo_oid, fd);
1838
+ }
1839
+
1840
+ /*
1841
+ * call-seq:
1842
+ * conn.lo_unlink( oid )
1843
+ *
1844
+ * Unlinks (deletes) the postgres large object of _oid_.
1845
+ */
1846
+ static VALUE
1847
+ pgconn_lounlink(obj, lo_oid)
1848
+ VALUE obj, lo_oid;
1849
+ {
1850
+ PGconn *conn;
1851
+ int oid = NUM2INT(lo_oid);
1852
+ int result;
1853
+
1854
+ if (oid < 0){
1855
+ rb_raise(rb_ePGError, "invalid oid %d",oid);
1856
+ }
1857
+ conn = get_pgconn(obj);
1858
+ result = lo_unlink(conn,oid);
1859
+
1860
+ return Qnil;
1861
+ }
1862
+
1863
+ static void
1864
+ free_pglarge(ptr)
1865
+ PGlarge *ptr;
1866
+ {
1867
+ if ((ptr->lo_fd) > 0) {
1868
+ lo_close(ptr->pgconn,ptr->lo_fd);
1869
+ }
1870
+ free(ptr);
1871
+ }
1872
+
1873
+ static VALUE
1874
+ pglarge_new(conn, lo_oid ,lo_fd)
1875
+ PGconn *conn;
1876
+ Oid lo_oid;
1877
+ int lo_fd;
1878
+ {
1879
+ VALUE obj;
1880
+ PGlarge *pglarge;
1881
+
1882
+ obj = Data_Make_Struct(rb_cPGlarge, PGlarge, 0, free_pglarge, pglarge);
1883
+ pglarge->pgconn = conn;
1884
+ pglarge->lo_oid = lo_oid;
1885
+ pglarge->lo_fd = lo_fd;
1886
+
1887
+ return obj;
1888
+ }
1889
+
1890
+ /*
1891
+ * call-seq:
1892
+ * lrg.oid()
1893
+ *
1894
+ * Returns the large object's +oid+.
1895
+ */
1896
+ static VALUE
1897
+ pglarge_oid(obj)
1898
+ VALUE obj;
1899
+ {
1900
+ PGlarge *pglarge = get_pglarge(obj);
1901
+
1902
+ return INT2NUM(pglarge->lo_oid);
1903
+ }
1904
+
1905
+ /*
1906
+ * call-seq:
1907
+ * lrg.open( [mode] )
1908
+ *
1909
+ * Opens a large object.
1910
+ * The _mode_ argument specifies the mode for the opened large object,
1911
+ * which is either +INV_READ+ or +INV_WRITE+.
1912
+ */
1913
+ static VALUE
1914
+ pglarge_open(argc, argv, obj)
1915
+ int argc;
1916
+ VALUE *argv;
1917
+ VALUE obj;
1918
+ {
1919
+ PGlarge *pglarge = get_pglarge(obj);
1920
+ VALUE nmode;
1921
+ int fd;
1922
+ int mode;
1923
+
1924
+ if (rb_scan_args(argc, argv, "01", &nmode) == 0) {
1925
+ mode = INV_READ;
1926
+ }
1927
+ else {
1928
+ mode = FIX2INT(nmode);
1929
+ }
1930
+
1931
+ if((fd = lo_open(pglarge->pgconn, pglarge->lo_oid, mode)) < 0) {
1932
+ rb_raise(rb_ePGError, "can't open large object");
1933
+ }
1934
+ pglarge->lo_fd = fd;
1935
+
1936
+ return INT2FIX(pglarge->lo_fd);
1937
+ }
1938
+
1939
+ /*
1940
+ * call-seq:
1941
+ * lrg.close()
1942
+ *
1943
+ * Closes a large object. Closed when they are garbage-collected.
1944
+ */
1945
+ static VALUE
1946
+ pglarge_close(obj)
1947
+ VALUE obj;
1948
+ {
1949
+ PGlarge *pglarge = get_pglarge(obj);
1950
+
1951
+ if((lo_close(pglarge->pgconn, pglarge->lo_fd)) < 0) {
1952
+ rb_raise(rb_ePGError, "can't closed large object");
1953
+ }
1954
+ DATA_PTR(obj) = 0;
1955
+
1956
+ return Qnil;
1957
+ }
1958
+
1959
+ /*
1960
+ * call-seq:
1961
+ * lrg.tell()
1962
+ *
1963
+ * Returns the current position of the large object pointer.
1964
+ */
1965
+ static VALUE
1966
+ pglarge_tell(obj)
1967
+ VALUE obj;
1968
+ {
1969
+ int start;
1970
+ PGlarge *pglarge = get_pglarge(obj);
1971
+
1972
+ if ((start = lo_tell(pglarge->pgconn,pglarge->lo_fd)) == -1) {
1973
+ rb_raise(rb_ePGError, "error while getting position");
1974
+ }
1975
+ return INT2NUM(start);
1976
+ }
1977
+
1978
+ static VALUE
1979
+ loread_all(obj)
1980
+ VALUE obj;
1981
+ {
1982
+ PGlarge *pglarge = get_pglarge(obj);
1983
+ VALUE str;
1984
+ long siz = BUFSIZ;
1985
+ long bytes = 0;
1986
+ int n;
1987
+
1988
+ str = rb_tainted_str_new(0,siz);
1989
+ for (;;) {
1990
+ n = lo_read(pglarge->pgconn, pglarge->lo_fd, RSTRING(str)->ptr + bytes,siz - bytes);
1991
+ if (n == 0 && bytes == 0) return Qnil;
1992
+ bytes += n;
1993
+ if (bytes < siz ) break;
1994
+ siz += BUFSIZ;
1995
+ rb_str_resize(str,siz);
1996
+ }
1997
+ if (bytes == 0) return rb_tainted_str_new(0,0);
1998
+ if (bytes != siz) rb_str_resize(str, bytes);
1999
+ return str;
2000
+ }
2001
+
2002
+ /*
2003
+ * call-seq:
2004
+ * lrg.read( [length] )
2005
+ *
2006
+ * Attempts to read _length_ bytes from large object.
2007
+ * If no _length_ is given, reads all data.
2008
+ */
2009
+ static VALUE
2010
+ pglarge_read(argc, argv, obj)
2011
+ int argc;
2012
+ VALUE *argv;
2013
+ VALUE obj;
2014
+ {
2015
+ int len;
2016
+ PGlarge *pglarge = get_pglarge(obj);
2017
+ VALUE str;
2018
+ VALUE length;
2019
+
2020
+ rb_scan_args(argc, argv, "01", &length);
2021
+ if (NIL_P(length)) {
2022
+ return loread_all(obj);
2023
+ }
2024
+
2025
+ len = NUM2INT(length);
2026
+ if (len < 0){
2027
+ rb_raise(rb_ePGError,"nagative length %d given", len);
2028
+ }
2029
+ str = rb_tainted_str_new(0,len);
2030
+
2031
+ if((len = lo_read(pglarge->pgconn, pglarge->lo_fd, StringValuePtr(str), len)) < 0) {
2032
+ rb_raise(rb_ePGError, "error while reading");
2033
+ }
2034
+ if (len == 0) return Qnil;
2035
+ RSTRING(str)->len = len;
2036
+ return str;
2037
+ }
2038
+
2039
+ /*
2040
+ * call-seq:
2041
+ * lrg.write( str )
2042
+ *
2043
+ * Writes the string _str_ to the large object.
2044
+ * Returns the number of bytes written.
2045
+ */
2046
+ static VALUE
2047
+ pglarge_write(obj, buffer)
2048
+ VALUE obj, buffer;
2049
+ {
2050
+ int n;
2051
+ PGlarge *pglarge = get_pglarge(obj);
2052
+
2053
+ Check_Type(buffer, T_STRING);
2054
+
2055
+ if( RSTRING(buffer)->len < 0) {
2056
+ rb_raise(rb_ePGError, "write buffer zero string");
2057
+ }
2058
+ if((n = lo_write(pglarge->pgconn, pglarge->lo_fd, StringValuePtr(buffer), RSTRING(buffer)->len)) == -1) {
2059
+ rb_raise(rb_ePGError, "buffer truncated during write");
2060
+ }
2061
+
2062
+ return INT2FIX(n);
2063
+ }
2064
+
2065
+ /*
2066
+ * call-seq:
2067
+ * lrg.seek( offset, whence )
2068
+ *
2069
+ * Move the large object pointer to the _offset_.
2070
+ * Valid values for _whence_ are +SEEK_SET+, +SEEK_CUR+, and +SEEK_END+.
2071
+ * (Or 0, 1, or 2.)
2072
+ */
2073
+ static VALUE
2074
+ pglarge_seek(obj, offset, whence)
2075
+ VALUE obj, offset, whence;
2076
+ {
2077
+ PGlarge *pglarge = get_pglarge(obj);
2078
+ int ret;
2079
+
2080
+ if((ret = lo_lseek(pglarge->pgconn, pglarge->lo_fd, NUM2INT(offset), NUM2INT(whence))) == -1) {
2081
+ rb_raise(rb_ePGError, "error while moving cursor");
2082
+ }
2083
+
2084
+ return INT2NUM(ret);
2085
+ }
2086
+
2087
+ /*
2088
+ * call-seq:
2089
+ * lrg.size()
2090
+ *
2091
+ * Returns the size of the large object.
2092
+ */
2093
+ static VALUE
2094
+ pglarge_size(obj)
2095
+ VALUE obj;
2096
+ {
2097
+ PGlarge *pglarge = get_pglarge(obj);
2098
+ int start, end;
2099
+
2100
+ if ((start = lo_tell(pglarge->pgconn,pglarge->lo_fd)) == -1) {
2101
+ rb_raise(rb_ePGError, "error while getting position");
2102
+ }
2103
+
2104
+ if ((end = lo_lseek(pglarge->pgconn, pglarge->lo_fd, 0, SEEK_END)) == -1) {
2105
+ rb_raise(rb_ePGError, "error while moving cursor");
2106
+ }
2107
+
2108
+ if ((start = lo_lseek(pglarge->pgconn, pglarge->lo_fd,start, SEEK_SET)) == -1) {
2109
+ rb_raise(rb_ePGError, "error while moving back to posiion");
2110
+ }
2111
+
2112
+ return INT2NUM(end);
2113
+ }
2114
+
2115
+ /*
2116
+ * call-seq:
2117
+ * lrg.export( file )
2118
+ *
2119
+ * Saves the large object to a file.
2120
+ */
2121
+ static VALUE
2122
+ pglarge_export(obj, filename)
2123
+ VALUE obj, filename;
2124
+ {
2125
+ PGlarge *pglarge = get_pglarge(obj);
2126
+
2127
+ Check_Type(filename, T_STRING);
2128
+
2129
+ if (!lo_export(pglarge->pgconn, pglarge->lo_oid, StringValuePtr(filename))){
2130
+ rb_raise(rb_ePGError, PQerrorMessage(pglarge->pgconn));
2131
+ }
2132
+
2133
+ return Qnil;
2134
+ }
2135
+
2136
+ /*
2137
+ * call-seq:
2138
+ * lrg.unlink()
2139
+ *
2140
+ * Deletes the large object.
2141
+ */
2142
+ static VALUE
2143
+ pglarge_unlink(obj)
2144
+ VALUE obj;
2145
+ {
2146
+ PGlarge *pglarge = get_pglarge(obj);
2147
+
2148
+ if (!lo_unlink(pglarge->pgconn,pglarge->lo_oid)) {
2149
+ rb_raise(rb_ePGError, PQerrorMessage(pglarge->pgconn));
2150
+ }
2151
+ DATA_PTR(obj) = 0;
2152
+
2153
+ return Qnil;
2154
+ }
2155
+
2156
+ static VALUE
2157
+ pgrow_init(self, keys)
2158
+ VALUE self, keys;
2159
+ {
2160
+ VALUE args[1] = { LONG2NUM(RARRAY(keys)->len) };
2161
+ rb_call_super(1, args);
2162
+ rb_iv_set(self, "@keys", keys);
2163
+ return self;
2164
+ }
2165
+
2166
+ static VALUE
2167
+ pgrow_keys(self)
2168
+ VALUE self;
2169
+ {
2170
+ return rb_iv_get(self, "@keys");
2171
+ }
2172
+
2173
+ static VALUE
2174
+ pgrow_values(self)
2175
+ VALUE self;
2176
+ {
2177
+ return self;
2178
+ }
2179
+
2180
+ static VALUE
2181
+ pgrow_aref(argc, argv, self)
2182
+ int argc;
2183
+ VALUE * argv;
2184
+ VALUE self;
2185
+ {
2186
+ if (TYPE(argv[0]) == T_STRING) {
2187
+ VALUE keys = pgrow_keys(self);
2188
+ int index = NUM2INT(rb_funcall(keys, rb_intern("index"), 1, argv[0]));
2189
+ return rb_ary_entry(self, index);
2190
+ }
2191
+ else {
2192
+ return rb_call_super(argc, argv);
2193
+ }
2194
+ }
2195
+
2196
+ static VALUE
2197
+ pgrow_each_value(self)
2198
+ VALUE self;
2199
+ {
2200
+ rb_ary_each(self);
2201
+ }
2202
+
2203
+ static VALUE
2204
+ pgrow_each_pair(self)
2205
+ VALUE self;
2206
+ {
2207
+ VALUE keys = pgrow_keys(self);
2208
+ int i;
2209
+ for (i = 0; i < RARRAY(keys)->len; ++i) {
2210
+ rb_yield(rb_assoc_new(rb_ary_entry(keys, i), rb_ary_entry(self, i)));
2211
+ }
2212
+ return self;
2213
+ }
2214
+
2215
+ static VALUE
2216
+ pgrow_each(self)
2217
+ VALUE self;
2218
+ {
2219
+ int arity = NUM2INT(rb_funcall(rb_block_proc(), rb_intern("arity"), 0));
2220
+ if (arity == 2) {
2221
+ pgrow_each_pair(self);
2222
+ }
2223
+ else {
2224
+ pgrow_each_value(self);
2225
+ }
2226
+ return self;
2227
+ }
2228
+
2229
+ static VALUE
2230
+ pgrow_each_key(self)
2231
+ VALUE self;
2232
+ {
2233
+ rb_ary_each(pgrow_keys(self));
2234
+ }
2235
+
2236
+ static VALUE
2237
+ pgrow_to_hash(self)
2238
+ VALUE self;
2239
+ {
2240
+ VALUE result = rb_hash_new();
2241
+ VALUE keys = pgrow_keys(self);
2242
+ int i;
2243
+ for (i = 0; i < RARRAY(self)->len; ++i) {
2244
+ rb_hash_aset(result, rb_ary_entry(keys, i), rb_ary_entry(self, i));
2245
+ }
2246
+ return result;
2247
+ }
2248
+
2249
+ /* Large Object support */
2250
+
2251
+ /********************************************************************
2252
+ *
2253
+ * Document-class: PGconn
2254
+ *
2255
+ * The class to access PostgreSQL database.
2256
+ * All other functionality of libpq save the large object to a file.
2257
+ *
2258
+ * For example, to send query to the database on the localhost:
2259
+ * require "postgres"
2260
+ * conn = PGconn.connect("localhost", 5432, "", "", "test1")
2261
+ * res = conn.exec("select * from a;")
2262
+ *
2263
+ * See the PGresult class for information on working with the results of a query.
2264
+ */
2265
+
2266
+
2267
+ /********************************************************************
2268
+ *
2269
+ * Document-class: PGresult
2270
+ *
2271
+ * The class to represent the query result tuples (rows).
2272
+ * An instance of this class is created as the result of every query.
2273
+ * You may need to invoke the #clear method of the instance when finished with
2274
+ * the result for better memory performance.
2275
+ */
2276
+
2277
+
2278
+
2279
+ /********************************************************************
2280
+ *
2281
+ * Document-class: PGlarge
2282
+ *
2283
+ * The class to access large objects.
2284
+ * An instance of this class is created as the result of
2285
+ * PGconn#lo_import, PGconn#lo_create, and PGconn#lo_open.
2286
+ */
2287
+
2288
+ void
2289
+ Init_postgres()
2290
+ {
2291
+ pg_gsub_bang_id = rb_intern("gsub!");
2292
+ pg_escape_regex = rb_reg_new("([\\t\\n\\\\])", 10, 0);
2293
+ rb_global_variable(&pg_escape_regex);
2294
+ pg_escape_str = rb_str_new("\\\\\\1", 4);
2295
+ rb_global_variable(&pg_escape_str);
2296
+
2297
+ rb_require("bigdecimal");
2298
+ rb_require("date");
2299
+ rb_require("time");
2300
+ rb_cDate = RUBY_CLASS("Date");
2301
+ rb_cDateTime = RUBY_CLASS("DateTime");
2302
+
2303
+ rb_ePGError = rb_define_class("PGError", rb_eStandardError);
2304
+
2305
+ rb_cPGconn = rb_define_class("PGconn", rb_cObject);
2306
+ #ifdef HAVE_RB_DEFINE_ALLOC_FUNC
2307
+ rb_define_alloc_func(rb_cPGconn, pgconn_alloc);
2308
+ #else
2309
+ rb_define_singleton_method(rb_cPGconn, "new", pgconn_s_new, -1);
2310
+ #endif
2311
+ rb_define_singleton_method(rb_cPGconn, "connect", pgconn_s_connect, -1);
2312
+ rb_define_singleton_method(rb_cPGconn, "open", pgconn_s_connect, -1);
2313
+ rb_define_singleton_method(rb_cPGconn, "setdb", pgconn_s_connect, -1);
2314
+ rb_define_singleton_method(rb_cPGconn, "setdblogin", pgconn_s_connect, -1);
2315
+ rb_define_singleton_method(rb_cPGconn, "escape", pgconn_s_escape, 1);
2316
+ rb_define_singleton_method(rb_cPGconn, "quote", pgconn_s_quote, 1);
2317
+ rb_define_singleton_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1);
2318
+ rb_define_singleton_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1);
2319
+
2320
+ rb_define_const(rb_cPGconn, "CONNECTION_OK", INT2FIX(CONNECTION_OK));
2321
+ rb_define_const(rb_cPGconn, "CONNECTION_BAD", INT2FIX(CONNECTION_BAD));
2322
+
2323
+ rb_define_method(rb_cPGconn, "initialize", pgconn_init, -1);
2324
+ rb_define_method(rb_cPGconn, "db", pgconn_db, 0);
2325
+ rb_define_method(rb_cPGconn, "host", pgconn_host, 0);
2326
+ rb_define_method(rb_cPGconn, "options", pgconn_options, 0);
2327
+ rb_define_method(rb_cPGconn, "port", pgconn_port, 0);
2328
+ rb_define_method(rb_cPGconn, "tty", pgconn_tty, 0);
2329
+ rb_define_method(rb_cPGconn, "status", pgconn_status, 0);
2330
+ rb_define_method(rb_cPGconn, "error", pgconn_error, 0);
2331
+ rb_define_method(rb_cPGconn, "close", pgconn_close, 0);
2332
+ rb_define_alias(rb_cPGconn, "finish", "close");
2333
+ rb_define_method(rb_cPGconn, "reset", pgconn_reset, 0);
2334
+ rb_define_method(rb_cPGconn, "user", pgconn_user, 0);
2335
+ rb_define_method(rb_cPGconn, "trace", pgconn_trace, 1);
2336
+ rb_define_method(rb_cPGconn, "untrace", pgconn_untrace, 0);
2337
+ rb_define_method(rb_cPGconn, "exec", pgconn_exec, -1);
2338
+ rb_define_method(rb_cPGconn, "query", pgconn_query, -1);
2339
+ rb_define_method(rb_cPGconn, "async_exec", pgconn_async_exec, 1);
2340
+ rb_define_method(rb_cPGconn, "async_query", pgconn_async_query, 1);
2341
+ rb_define_method(rb_cPGconn, "get_notify", pgconn_get_notify, 0);
2342
+ rb_define_method(rb_cPGconn, "insert_table", pgconn_insert_table, 2);
2343
+ rb_define_method(rb_cPGconn, "putline", pgconn_putline, 1);
2344
+ rb_define_method(rb_cPGconn, "getline", pgconn_getline, 0);
2345
+ rb_define_method(rb_cPGconn, "endcopy", pgconn_endcopy, 0);
2346
+ rb_define_method(rb_cPGconn, "on_notice", pgconn_on_notice, 0);
2347
+ rb_define_method(rb_cPGconn, "transaction_status", pgconn_transaction_status, 0);
2348
+ rb_define_method(rb_cPGconn, "protocol_version", pgconn_protocol_version, 0);
2349
+ rb_define_method(rb_cPGconn, "server_version", pgconn_server_version, 0);
2350
+ rb_define_method(rb_cPGconn, "lastval", pgconn_lastval, 0);
2351
+
2352
+ #ifdef HAVE_PQSETCLIENTENCODING
2353
+ rb_define_method(rb_cPGconn, "client_encoding", pgconn_client_encoding, 0);
2354
+ rb_define_method(rb_cPGconn, "set_client_encoding", pgconn_set_client_encoding, 1);
2355
+ #endif
2356
+
2357
+ /* Large Object support */
2358
+ rb_define_method(rb_cPGconn, "lo_import", pgconn_loimport, 1);
2359
+ rb_define_alias(rb_cPGconn, "loimport", "lo_import");
2360
+ rb_define_method(rb_cPGconn, "lo_create", pgconn_locreate, -1);
2361
+ rb_define_alias(rb_cPGconn, "locreate", "lo_create");
2362
+ rb_define_method(rb_cPGconn, "lo_open", pgconn_loopen, -1);
2363
+ rb_define_alias(rb_cPGconn, "loopen", "lo_open");
2364
+ rb_define_method(rb_cPGconn, "lo_export", pgconn_loexport, 2);
2365
+ rb_define_alias(rb_cPGconn, "loexport", "lo_export");
2366
+ rb_define_method(rb_cPGconn, "lo_unlink", pgconn_lounlink, 1);
2367
+ rb_define_alias(rb_cPGconn, "lounlink", "lo_unlink");
2368
+
2369
+ rb_cPGlarge = rb_define_class("PGlarge", rb_cObject);
2370
+ rb_define_method(rb_cPGlarge, "oid",pglarge_oid, 0);
2371
+ rb_define_method(rb_cPGlarge, "open",pglarge_open, -1);
2372
+ rb_define_method(rb_cPGlarge, "close",pglarge_close, 0);
2373
+ rb_define_method(rb_cPGlarge, "read",pglarge_read, -1);
2374
+ rb_define_method(rb_cPGlarge, "write",pglarge_write, 1);
2375
+ rb_define_method(rb_cPGlarge, "seek",pglarge_seek, 2);
2376
+ rb_define_method(rb_cPGlarge, "tell",pglarge_tell, 0);
2377
+ rb_define_method(rb_cPGlarge, "size",pglarge_size, 0);
2378
+ rb_define_method(rb_cPGlarge, "export",pglarge_export, 1);
2379
+ rb_define_method(rb_cPGlarge, "unlink",pglarge_unlink, 0);
2380
+
2381
+ rb_define_const(rb_cPGlarge, "INV_WRITE", INT2FIX(INV_WRITE));
2382
+ rb_define_const(rb_cPGlarge, "INV_READ", INT2FIX(INV_READ));
2383
+ rb_define_const(rb_cPGlarge, "SEEK_SET", INT2FIX(SEEK_SET));
2384
+ rb_define_const(rb_cPGlarge, "SEEK_CUR", INT2FIX(SEEK_CUR));
2385
+ rb_define_const(rb_cPGlarge, "SEEK_END", INT2FIX(SEEK_END));
2386
+ /* Large Object support */
2387
+
2388
+ rb_cPGresult = rb_define_class("PGresult", rb_cObject);
2389
+ rb_include_module(rb_cPGresult, rb_mEnumerable);
2390
+
2391
+ rb_define_const(rb_cPGresult, "EMPTY_QUERY", INT2FIX(PGRES_EMPTY_QUERY));
2392
+ rb_define_const(rb_cPGresult, "COMMAND_OK", INT2FIX(PGRES_COMMAND_OK));
2393
+ rb_define_const(rb_cPGresult, "TUPLES_OK", INT2FIX(PGRES_TUPLES_OK));
2394
+ rb_define_const(rb_cPGresult, "COPY_OUT", INT2FIX(PGRES_COPY_OUT));
2395
+ rb_define_const(rb_cPGresult, "COPY_IN", INT2FIX(PGRES_COPY_IN));
2396
+ rb_define_const(rb_cPGresult, "BAD_RESPONSE", INT2FIX(PGRES_BAD_RESPONSE));
2397
+ rb_define_const(rb_cPGresult, "NONFATAL_ERROR",INT2FIX(PGRES_NONFATAL_ERROR));
2398
+ rb_define_const(rb_cPGresult, "FATAL_ERROR", INT2FIX(PGRES_FATAL_ERROR));
2399
+
2400
+ rb_define_method(rb_cPGresult, "status", pgresult_status, 0);
2401
+ rb_define_alias(rb_cPGresult, "result", "entries");
2402
+ rb_define_alias(rb_cPGresult, "rows", "entries");
2403
+ rb_define_method(rb_cPGresult, "each", pgresult_each, 0);
2404
+ rb_define_method(rb_cPGresult, "[]", pgresult_aref, -1);
2405
+ rb_define_method(rb_cPGresult, "fields", pgresult_fields, 0);
2406
+ rb_define_method(rb_cPGresult, "num_tuples", pgresult_num_tuples, 0);
2407
+ rb_define_method(rb_cPGresult, "num_fields", pgresult_num_fields, 0);
2408
+ rb_define_method(rb_cPGresult, "fieldname", pgresult_fieldname, 1);
2409
+ rb_define_method(rb_cPGresult, "fieldnum", pgresult_fieldnum, 1);
2410
+ rb_define_method(rb_cPGresult, "type", pgresult_type, 1);
2411
+ rb_define_method(rb_cPGresult, "size", pgresult_size, 1);
2412
+ rb_define_method(rb_cPGresult, "getvalue", pgresult_getvalue, 2);
2413
+ rb_define_method(rb_cPGresult, "getvalue_byname", pgresult_getvalue_byname, 2);
2414
+ rb_define_method(rb_cPGresult, "getlength", pgresult_getlength, 2);
2415
+ rb_define_method(rb_cPGresult, "getisnull", pgresult_getisnull, 2);
2416
+ rb_define_method(rb_cPGresult, "cmdtuples", pgresult_cmdtuples, 0);
2417
+ rb_define_method(rb_cPGresult, "cmdstatus", pgresult_cmdstatus, 0);
2418
+ rb_define_method(rb_cPGresult, "oid", pgresult_oid, 0);
2419
+ rb_define_method(rb_cPGresult, "print", pgresult_print, 2);
2420
+ rb_define_method(rb_cPGresult, "clear", pgresult_clear, 0);
2421
+ rb_define_alias(rb_cPGresult, "close", "clear");
2422
+
2423
+ rb_cPGrow = rb_define_class("PGrow", rb_cArray);
2424
+ rb_define_method(rb_cPGrow, "initialize", pgrow_init, 1);
2425
+ rb_define_method(rb_cPGrow, "[]", pgrow_aref, -1);
2426
+ rb_define_method(rb_cPGrow, "keys", pgrow_keys, 0);
2427
+ rb_define_method(rb_cPGrow, "values", pgrow_values, 0);
2428
+ rb_define_method(rb_cPGrow, "each", pgrow_each, 0);
2429
+ rb_define_method(rb_cPGrow, "each_pair", pgrow_each_pair, 0);
2430
+ rb_define_method(rb_cPGrow, "each_key", pgrow_each_key, 0);
2431
+ rb_define_method(rb_cPGrow, "each_value", pgrow_each_value, 0);
2432
+ rb_define_method(rb_cPGrow, "to_hash", pgrow_to_hash, 0);
2433
+ }