Class: Swift::DB::Postgres

Inherits:
Object
  • Object
show all
Defined in:
ext/swift/db/postgres/adapter.c

Defined Under Namespace

Classes: Result, Statement

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Object



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
# File 'ext/swift/db/postgres/adapter.c', line 63

VALUE db_postgres_adapter_initialize(VALUE self, VALUE options) {
    char *connection_info;
    VALUE db, user, pass, host, port, ssl;
    Adapter *a = db_postgres_adapter_handle(self);

    if (TYPE(options) != T_HASH)
        rb_raise(eSwiftArgumentError, "options needs to be a hash");

    db   = rb_hash_aref(options, ID2SYM(rb_intern("db")));
    user = rb_hash_aref(options, ID2SYM(rb_intern("user")));
    pass = rb_hash_aref(options, ID2SYM(rb_intern("password")));
    host = rb_hash_aref(options, ID2SYM(rb_intern("host")));
    port = rb_hash_aref(options, ID2SYM(rb_intern("port")));
    ssl  = rb_hash_aref(options, ID2SYM(rb_intern("ssl")));

    if (NIL_P(db))
        rb_raise(eSwiftConnectionError, "Invalid db name");
    if (NIL_P(host))
        host = rb_str_new2("127.0.0.1");
    if (NIL_P(port))
        port = rb_str_new2("5432");
    if (NIL_P(user))
        user = sUser;

    if (!NIL_P(ssl) && TYPE(ssl) != T_HASH)
            rb_raise(eSwiftArgumentError, "ssl options needs to be a hash");

    connection_info = (char *)malloc(4096);
    snprintf(connection_info, 4096, "dbname='%s' user='%s' password='%s' host='%s' port='%s'",
        CSTRING(db), CSTRING(user), CSTRING(pass), CSTRING(host), CSTRING(port));

    if (!NIL_P(ssl)) {
        append_ssl_option(connection_info, 4096, ssl, "sslmode",      "allow");
        append_ssl_option(connection_info, 4096, ssl, "sslcert",      0);
        append_ssl_option(connection_info, 4096, ssl, "sslkey",       0);
        append_ssl_option(connection_info, 4096, ssl, "sslrootcert",  0);
        append_ssl_option(connection_info, 4096, ssl, "sslcrl",       0);
    }

    a->connection = PQconnectdb(connection_info);
    free(connection_info);

    if (!a->connection)
        rb_raise(eSwiftRuntimeError, "unable to allocate database handle");
    if (PQstatus(a->connection) == CONNECTION_BAD)
        rb_raise(eSwiftConnectionError, PQerrorMessage(a->connection));

    PQsetNoticeProcessor(a->connection, (PQnoticeProcessor)db_postgres_adapter_notice, (void*)self);
    PQsetClientEncoding(a->connection, "utf8");
    return self;
}

Instance Method Details

#begin(*args) ⇒ Object



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
# File 'ext/swift/db/postgres/adapter.c', line 185

VALUE db_postgres_adapter_begin(int argc, VALUE *argv, VALUE self) {
    char command[256];
    VALUE savepoint;
    PGresult *result;

    Adapter *a = db_postgres_adapter_handle_safe(self);
    rb_scan_args(argc, argv, "01", &savepoint);

    if (a->t_nesting == 0) {
        result = PQexec(a->connection, "begin");
        db_postgres_check_result(result);
        PQclear(result);
        a->t_nesting++;
        if (NIL_P(savepoint))
            return Qtrue;
    }

    if (NIL_P(savepoint))
        savepoint = rb_uuid_string();

    snprintf(command, 256, "savepoint %s", CSTRING(savepoint));
    result = PQexec(a->connection, command);
    db_postgres_check_result(result);
    PQclear(result);

    a->t_nesting++;
    return savepoint;
}

#closeObject



309
310
311
312
313
314
315
316
317
# File 'ext/swift/db/postgres/adapter.c', line 309

VALUE db_postgres_adapter_close(VALUE self) {
    Adapter *a = db_postgres_adapter_handle(self);
    if (a->connection) {
        PQfinish(a->connection);
        a->connection = 0;
        return Qtrue;
    }
    return Qfalse;
}

#closed?Boolean

Returns:

  • (Boolean)


319
320
321
322
# File 'ext/swift/db/postgres/adapter.c', line 319

VALUE db_postgres_adapter_closed_q(VALUE self) {
    Adapter *a = db_postgres_adapter_handle(self);
    return a->connection ? Qfalse : Qtrue;
}

#commit(*args) ⇒ Object



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
# File 'ext/swift/db/postgres/adapter.c', line 214

VALUE db_postgres_adapter_commit(int argc, VALUE *argv, VALUE self) {
    VALUE savepoint;
    char command[256];
    PGresult *result;

    Adapter *a = db_postgres_adapter_handle_safe(self);
    rb_scan_args(argc, argv, "01", &savepoint);

    if (a->t_nesting == 0)
        return Qfalse;

    if (NIL_P(savepoint)) {
        result = PQexec(a->connection, "commit");
        db_postgres_check_result(result);
        PQclear(result);
        a->t_nesting--;
    }
    else {
        snprintf(command, 256, "release savepoint %s", CSTRING(savepoint));
        result = PQexec(a->connection, command);
        db_postgres_check_result(result);
        PQclear(result);
        a->t_nesting--;
    }
    return Qtrue;
}

#escape(fragment) ⇒ Object



333
334
335
336
337
338
339
340
341
342
343
344
# File 'ext/swift/db/postgres/adapter.c', line 333

VALUE db_postgres_adapter_escape(VALUE self, VALUE fragment) {
    int error;
    VALUE text = TO_S(fragment);
    char pg_escaped[RSTRING_LEN(text) * 2 + 1];
    Adapter *a = db_postgres_adapter_handle_safe(self);
    PQescapeStringConn(a->connection, pg_escaped, RSTRING_PTR(text), RSTRING_LEN(text), &error);

    if (error)
        rb_raise(eSwiftArgumentError, "invalid escape string: %s\n", PQerrorMessage(a->connection));

    return rb_str_new2(pg_escaped);
}

#execute(*args) ⇒ Object



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
# File 'ext/swift/db/postgres/adapter.c', line 125

VALUE db_postgres_adapter_execute(int argc, VALUE *argv, VALUE self) {
    char **bind_args_data = 0;
    int n, *bind_args_size = 0, *bind_args_fmt = 0;
    PGresult *pg_result;
    VALUE sql, bind, data;
    Adapter *a = db_postgres_adapter_handle_safe(self);

    rb_scan_args(argc, argv, "10*", &sql, &bind);
    if (!a->native)
        sql = db_postgres_normalized_sql(sql);

    if (RARRAY_LEN(bind) > 0) {
        bind_args_size = (int   *) malloc(sizeof(int)    * RARRAY_LEN(bind));
        bind_args_fmt  = (int   *) malloc(sizeof(int)    * RARRAY_LEN(bind));
        bind_args_data = (char **) malloc(sizeof(char *) * RARRAY_LEN(bind));

        rb_gc_register_address(&bind);
        for (n = 0; n < RARRAY_LEN(bind); n++) {
            data = rb_ary_entry(bind, n);
            if (NIL_P(data)) {
                bind_args_size[n] = 0;
                bind_args_data[n] = 0;
                bind_args_fmt[n]  = 0;
            }
            else {
                if (rb_obj_is_kind_of(data, rb_cIO) || rb_obj_is_kind_of(data, cStringIO))
                    bind_args_fmt[n] = 1;
                else
                    bind_args_fmt[n] = 0;

                data = typecast_to_string(data);
                bind_args_size[n] = RSTRING_LEN(data);
                bind_args_data[n] = RSTRING_PTR(data);
            }
        }

        Query q = {
            .connection = a->connection,
            .command    = CSTRING(sql),
            .n_args     = RARRAY_LEN(bind),
            .data       = bind_args_data,
            .size       = bind_args_size,
            .format     = bind_args_fmt
        };

        pg_result = (PGresult *)rb_thread_blocking_region(nogvl_pq_exec_params, &q, RUBY_UBF_IO, 0);
        rb_gc_unregister_address(&bind);
        free(bind_args_size);
        free(bind_args_data);
        free(bind_args_fmt);
    }
    else {
        Query q = {.connection = a->connection, .command = CSTRING(sql)};
        pg_result = (PGresult *)rb_thread_blocking_region(nogvl_pq_exec, &q, RUBY_UBF_IO, 0);
    }

    db_postgres_check_result(pg_result);
    return db_postgres_result_load(db_postgres_result_allocate(cDPR), pg_result);
}

#filenoObject



346
347
348
349
# File 'ext/swift/db/postgres/adapter.c', line 346

VALUE db_postgres_adapter_fileno(VALUE self) {
    Adapter *a = db_postgres_adapter_handle_safe(self);
    return INT2NUM(PQsocket(a->connection));
}

#native_bind_formatObject



365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'ext/swift/db/postgres/adapter.c', line 365

VALUE db_postgres_adapter_native(VALUE self) {
    int status, native;
    VALUE result;
    Adapter *a = db_postgres_adapter_handle_safe(self);

    native    = a->native;
    a->native = 1;
    result = rb_protect(rb_yield, Qnil, &status);
    a->native = native;
    if (status)
        rb_jump_tag(status);
    return result;
}

#native_bind_format=(flag) ⇒ Object



379
380
381
382
383
# File 'ext/swift/db/postgres/adapter.c', line 379

VALUE db_postgres_adapter_native_set(VALUE self, VALUE flag) {
    Adapter *a = db_postgres_adapter_handle_safe(self);
    a->native = Qtrue == flag ? 1 : 0;
    return flag;
}

#pingObject



324
325
326
327
# File 'ext/swift/db/postgres/adapter.c', line 324

VALUE db_postgres_adapter_ping(VALUE self) {
    Adapter *a = db_postgres_adapter_handle(self);
    return a->connection && PQstatus(a->connection) == CONNECTION_OK ? Qtrue : Qfalse;
}

#prepare(sql) ⇒ Object



329
330
331
# File 'ext/swift/db/postgres/adapter.c', line 329

VALUE db_postgres_adapter_prepare(VALUE self, VALUE sql) {
    return db_postgres_statement_initialize(db_postgres_statement_allocate(cDPS), self, sql);
}

#query(*args) ⇒ Object



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'ext/swift/db/postgres/adapter.c', line 385

VALUE db_postgres_adapter_query(int argc, VALUE *argv, VALUE self) {
    VALUE sql, bind, data;
    char **bind_args_data = 0;
    int n, ok = 1, *bind_args_size = 0, *bind_args_fmt = 0;
    Adapter *a = db_postgres_adapter_handle_safe(self);

    rb_scan_args(argc, argv, "10*", &sql, &bind);
    if (!a->native)
        sql = db_postgres_normalized_sql(sql);

    if (RARRAY_LEN(bind) > 0) {
        bind_args_size = (int   *) malloc(sizeof(int)    * RARRAY_LEN(bind));
        bind_args_fmt  = (int   *) malloc(sizeof(int)    * RARRAY_LEN(bind));
        bind_args_data = (char **) malloc(sizeof(char *) * RARRAY_LEN(bind));

        for (n = 0; n < RARRAY_LEN(bind); n++) {
            data = rb_ary_entry(bind, n);
            if (NIL_P(data)) {
                bind_args_size[n] = 0;
                bind_args_data[n] = 0;
                bind_args_fmt[n]  = 0;
            }
            else {
                if (rb_obj_is_kind_of(data, rb_cIO) || rb_obj_is_kind_of(data, cStringIO))
                    bind_args_fmt[n] = 1;
                else
                    bind_args_fmt[n] = 0;

                data = typecast_to_string(data);
                bind_args_size[n] = RSTRING_LEN(data);
                bind_args_data[n] = RSTRING_PTR(data);
            }
        }

        ok = PQsendQueryParams(a->connection, RSTRING_PTR(sql), RARRAY_LEN(bind), 0,
            (const char* const *)bind_args_data, bind_args_size, bind_args_fmt, 0);

        free(bind_args_size);
        free(bind_args_data);
        free(bind_args_fmt);
    }
    else
        ok = PQsendQuery(a->connection, RSTRING_PTR(sql));

    if (!ok)
        rb_raise(eSwiftRuntimeError, "%s", PQerrorMessage(a->connection));

    if (rb_block_given_p()) {
        rb_thread_wait_fd(PQsocket(a->connection));
        return db_postgres_result_each(db_postgres_adapter_result(self));
    }
    else
        return Qtrue;
}

#read(*args) ⇒ Object



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'ext/swift/db/postgres/adapter.c', line 507

VALUE db_postgres_adapter_read(int argc, VALUE *argv, VALUE self) {
    int n, done = 0;
    char *sql, *data;
    PGresult *result;
    VALUE table, fields, io;
    Adapter *a = db_postgres_adapter_handle_safe(self);

    if (argc > 3)
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 0..3)", argc);

    table = fields = io = Qnil;
    switch (argc) {
        case 0:
            if (!rb_block_given_p())
                rb_raise(eSwiftArgumentError, "#read needs an IO object to write to or a block to call");
            break;
        case 1:
            if (rb_respond_to(argv[0], rb_intern("write")))
                io = argv[0];
            else
                table = argv[0];
            break;
        case 2:
            table = argv[0];
            io    = argv[1];
            if (!rb_respond_to(io, rb_intern("write")))
                rb_raise(eSwiftArgumentError, "#read needs an IO object that responds to #write");
            break;
        case 3:
            table  = argv[0];
            fields = argv[1];
            io     = argv[2];
            if (!rb_respond_to(io, rb_intern("write")))
                rb_raise(eSwiftArgumentError, "#read needs an IO object that responds to #write");
            if (TYPE(fields) != T_ARRAY)
                rb_raise(eSwiftArgumentError, "fields needs to be an array");
            if (RARRAY_LEN(fields) < 1)
                fields = Qnil;
    }


    if (!NIL_P(table)) {
        sql = (char *)malloc(4096);
        if (NIL_P(fields))
            snprintf(sql, 4096, "copy %s to stdout", CSTRING(table));
        else
            snprintf(sql, 4096, "copy %s(%s) to stdout", CSTRING(table), CSTRING(rb_ary_join(fields, rb_str_new2(", "))));

        result = PQexec(a->connection, sql);
        free(sql);

        db_postgres_check_result(result);
        PQclear(result);
    }

    while (!done) {
        switch ((n = PQgetCopyData(a->connection, &data, 0))) {
            case -1: done = 1; break;
            case -2: rb_raise(eSwiftRuntimeError, "%s", PQerrorMessage(a->connection));
            default:
                if (n > 0) {
                    if (NIL_P(io))
                        rb_yield(rb_str_new(data, n));
                    else
                        rb_funcall(io, rb_intern("write"), 1, rb_str_new(data, n));
                    PQfreemem(data);
                }
        }
    }

    result = PQgetResult(a->connection);
    db_postgres_check_result(result);
    if (!result)
        rb_raise(eSwiftRuntimeError, "invalid result at the end of COPY command");
    return db_postgres_result_load(db_postgres_result_allocate(cDPR), result);
}

#resultObject



351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'ext/swift/db/postgres/adapter.c', line 351

VALUE db_postgres_adapter_result(VALUE self) {
    PGresult *result, *rest;
    Adapter *a = db_postgres_adapter_handle_safe(self);
    while (1) {
        PQconsumeInput(a->connection);
        if (!PQisBusy(a->connection))
            break;
    }
    result = PQgetResult(a->connection);
    while ((rest = PQgetResult(a->connection))) PQclear(rest);
    db_postgres_check_result(result);
    return db_postgres_result_load(db_postgres_result_allocate(cDPR), result);
}

#rollback(*args) ⇒ Object



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
# File 'ext/swift/db/postgres/adapter.c', line 241

VALUE db_postgres_adapter_rollback(int argc, VALUE *argv, VALUE self) {
    VALUE savepoint;
    char command[256];
    PGresult *result;

    Adapter *a = db_postgres_adapter_handle_safe(self);
    rb_scan_args(argc, argv, "01", &savepoint);

    if (a->t_nesting == 0)
        return Qfalse;

    if (NIL_P(savepoint)) {
        result = PQexec(a->connection, "rollback");
        db_postgres_check_result(result);
        PQclear(result);
        a->t_nesting--;
    }
    else {
        snprintf(command, 256, "rollback to savepoint %s", CSTRING(savepoint));
        result = PQexec(a->connection, command);
        db_postgres_check_result(result);
        PQclear(result);
        a->t_nesting--;
    }
    return Qtrue;
}

#transaction(*args) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'ext/swift/db/postgres/adapter.c', line 268

VALUE db_postgres_adapter_transaction(int argc, VALUE *argv, VALUE self) {
    int status;
    VALUE savepoint, block, block_result;

    Adapter *a = db_postgres_adapter_handle_safe(self);
    rb_scan_args(argc, argv, "01&", &savepoint, &block);

    if (NIL_P(block))
        rb_raise(eSwiftRuntimeError, "postgres transaction requires a block");

    if (a->t_nesting == 0) {
        db_postgres_adapter_begin(1, &savepoint, self);
        block_result = rb_protect(rb_yield, self, &status);
        if (!status) {
            db_postgres_adapter_commit(1, &savepoint, self);
            if (!NIL_P(savepoint))
                db_postgres_adapter_commit(0, 0, self);
        }
        else {
            db_postgres_adapter_rollback(1, &savepoint, self);
            if (!NIL_P(savepoint))
                db_postgres_adapter_rollback(0, 0, self);
            rb_jump_tag(status);
        }
    }
    else {
        if (NIL_P(savepoint))
            savepoint = rb_uuid_string();
        db_postgres_adapter_begin(1, &savepoint, self);
        block_result = rb_protect(rb_yield, self, &status);
        if (!status)
            db_postgres_adapter_commit(1, &savepoint, self);
        else {
            db_postgres_adapter_rollback(1, &savepoint, self);
            rb_jump_tag(status);
        }
    }

    return block_result;
}

#write(*args) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'ext/swift/db/postgres/adapter.c', line 440

VALUE db_postgres_adapter_write(int argc, VALUE *argv, VALUE self) {
    char *sql;
    VALUE table, fields, io, data;
    PGresult *result;
    Adapter *a = db_postgres_adapter_handle_safe(self);

    if (argc < 1 || argc > 3)
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1..3)", argc);

    table = io = fields = Qnil;
    switch (argc) {
        case 1:
            io = argv[0];
            break;
        case 2:
            table = argv[0];
            io    = argv[1];
            break;
        case 3:
            table  = argv[0];
            fields = argv[1];
            io     = argv[2];

            if (TYPE(fields) != T_ARRAY)
                rb_raise(eSwiftArgumentError, "fields needs to be an array");
            if (RARRAY_LEN(fields) < 1)
                fields = Qnil;
    }

    if (argc > 1) {
        sql = (char *)malloc(4096);
        if (NIL_P(fields))
            snprintf(sql, 4096, "copy %s from stdin", CSTRING(table));
        else
            snprintf(sql, 4096, "copy %s(%s) from stdin", CSTRING(table), CSTRING(rb_ary_join(fields, rb_str_new2(", "))));

        result = PQexec(a->connection, sql);
        free(sql);

        db_postgres_check_result(result);
        PQclear(result);
    }

    if (rb_respond_to(io, rb_intern("read"))) {
        while (!NIL_P((data = rb_funcall(io, rb_intern("read"), 1, INT2NUM(4096))))) {
            data = TO_S(data);
            if (PQputCopyData(a->connection, RSTRING_PTR(data), RSTRING_LEN(data)) != 1)
                rb_raise(eSwiftRuntimeError, "%s", PQerrorMessage(a->connection));
        }
        if (PQputCopyEnd(a->connection, 0) != 1)
            rb_raise(eSwiftRuntimeError, "%s", PQerrorMessage(a->connection));
    }
    else {
        io = TO_S(io);
        if (PQputCopyData(a->connection, RSTRING_PTR(io), RSTRING_LEN(io)) != 1)
            rb_raise(eSwiftRuntimeError, "%s", PQerrorMessage(a->connection));
        if (PQputCopyEnd(a->connection, 0) != 1)
            rb_raise(eSwiftRuntimeError, "%s", PQerrorMessage(a->connection));
    }

    result = PQgetResult(a->connection);
    db_postgres_check_result(result);
    if (!result)
        rb_raise(eSwiftRuntimeError, "invalid result at the end of COPY command");
    return db_postgres_result_load(db_postgres_result_allocate(cDPR), result);
}