File: pgsql_mod.cpp

package info (click to toggle)
falconpl 0.9.6.9-git20120606-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 46,176 kB
  • sloc: cpp: 181,389; ansic: 109,025; yacc: 2,310; xml: 1,218; sh: 403; objc: 245; makefile: 82; sql: 20
file content (737 lines) | stat: -rw-r--r-- 17,624 bytes parent folder | download | duplicates (2)
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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
439
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
506
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
/*
 * FALCON - The Falcon Programming Language.
 * FILE: pgsql_mod.cpp
 *
 * PgSQL Falcon service/driver
 * -------------------------------------------------------------------
 * Author: Jeremy Cowgar, Stanislas Marquis
 * Begin: Sun Dec 23 21:54:42 2007
 *
 * -------------------------------------------------------------------
 * (C) Copyright 2007: the FALCON developers (see list in AUTHORS file)
 *
 * See LICENSE file for licensing details.
 */

#include <string.h>
#include <stdio.h>

#include <falcon/engine.h>
#include "pgsql_mod.h"

/* Oid - see catalog/pg_type.h */
#define PG_TYPE_BOOL                    16
#define PG_TYPE_BYTEA                   17
#define PG_TYPE_CHAR                    18
#define PG_TYPE_NAME                    19
#define PG_TYPE_INT8                    20
#define PG_TYPE_INT2                    21
#define PG_TYPE_INT2VECTOR              22
#define PG_TYPE_INT4                    23
#define PG_TYPE_REGPROC                 24
#define PG_TYPE_TEXT                    25
#define PG_TYPE_OID                     26
#define PG_TYPE_TID                     27
#define PG_TYPE_XID                     28
#define PG_TYPE_CID                     29
#define PG_TYPE_OIDVECTOR               30
#define PG_TYPE_SET                     32
#define PG_TYPE_CHAR2                   409
#define PG_TYPE_CHAR4                   410
#define PG_TYPE_CHAR8                   411
#define PG_TYPE_POINT                   600
#define PG_TYPE_LSEG                    601
#define PG_TYPE_PATH                    602
#define PG_TYPE_BOX                     603
#define PG_TYPE_POLYGON                 604
#define PG_TYPE_FILENAME                605
#define PG_TYPE_FLOAT4                  700
#define PG_TYPE_FLOAT8                  701
#define PG_TYPE_ABSTIME                 702
#define PG_TYPE_RELTIME                 703
#define PG_TYPE_TINTERVAL               704
#define PG_TYPE_UNKNOWN                 705
#define PG_TYPE_MONEY                   790
#define PG_TYPE_OIDINT2                 810
#define PG_TYPE_OIDINT4                 910
#define PG_TYPE_OIDNAME                 911
#define PG_TYPE_BPCHAR                  1042
#define PG_TYPE_VARCHAR                 1043
#define PG_TYPE_DATE                    1082
#define PG_TYPE_TIME                    1083  /* w/o timezone */
#define PG_TYPE_TIMETZ                  1266  /* with timezone */
#define PG_TYPE_TIMESTAMP               1114  /* w/o timezone */
#define PG_TYPE_TIMESTAMPTZ             1184  /* with timezone */
#define PG_TYPE_NUMERIC                 1700


namespace Falcon
{


int32 dbi_pgsqlQuestionMarksToDollars( const String& input, String& output )
{
    output.reserve( input.size() + 32 );
    output.size( 0 );

    uint32 pos0 = 0;
    uint32 pos1 = input.find( "?" );
    int32 i = 0;

    while ( pos1 != String::npos )
    {
        output += input.subString( pos0, pos1 );
        output.A( "$" ).N( ++i );
        pos0 = pos1 + 1;
        pos1 = input.find( "?", pos0 );
    }

    output += input.subString( pos0 );
    return i;
}


/******************************************************************************
 * Recordset class
 *****************************************************************************/

DBIRecordsetPgSQL::DBIRecordsetPgSQL( DBIHandlePgSQL* dbh, PGresult* res )
    :
    DBIRecordset( dbh ),
    m_row( -1 ),
    m_res( res ),
    m_pConn( dbh->getConnRef() )
{
    m_rowCount = PQntuples( res );
    m_columnCount = PQnfields( res );
    m_pConn->incref();
}


DBIRecordsetPgSQL::~DBIRecordsetPgSQL()
{
   if ( m_res != NULL )
      close();
}


bool DBIRecordsetPgSQL::fetchRow()
{
    return ++m_row < m_rowCount ? true : false;
}


bool DBIRecordsetPgSQL::discard( int64 ncount )
{
    for ( int64 i=0; i < ncount; ++i )
    {
        if ( !fetchRow() )
            return false;
    }
    return true;
}


int64 DBIRecordsetPgSQL::getRowIndex()
{
    return m_row;
}


int64 DBIRecordsetPgSQL::getRowCount()
{
    return m_rowCount;
}


int DBIRecordsetPgSQL::getColumnCount()
{
   return m_columnCount;
}


bool DBIRecordsetPgSQL::getColumnName( int nCol, String& name )
{
    if ( nCol < 0 || nCol >= m_columnCount )
        return false;

    name.bufferize( PQfname( m_res, nCol ) );
    return true;
}


bool DBIRecordsetPgSQL::getColumnValue( int nCol, Item& value )
{
    if ( nCol < 0 || nCol >= m_columnCount )
        return false;

    const char* v = PQgetvalue( m_res, m_row, nCol );
    if ( *v == '\0'
        && PQgetisnull( m_res, m_row, nCol ) )
    {
        value.setNil();
        return true;
    }
    else
    if ( m_dbh->options()->m_bFetchStrings )
    {
        String s( v );
        s.bufferize();
        value = s;
        return true;
    }

    switch ( PQftype( m_res, nCol ) )
    {
    case PG_TYPE_BOOL:
        value.setBoolean( *v == 't' ? true : false );
        break;

    case PG_TYPE_INT2:
    case PG_TYPE_INT4:
    case PG_TYPE_INT8:
        value.setInteger( atol( v ) );
        break;

    case PG_TYPE_FLOAT4:
    case PG_TYPE_FLOAT8:
    case PG_TYPE_NUMERIC:
        value.setNumeric( atof( v ) );
        break;

    case PG_TYPE_DATE:
        {
            VMachine* vm = VMachine::getCurrent();
            if ( vm == 0 )
                return false;

            String tv( v );
            int64 year, month, day;
            tv.subString( 0, 4 ).parseInt( year );
            tv.subString( 5, 7 ).parseInt( month );
            tv.subString( 8, 10 ).parseInt( day );
            TimeStamp* ts = new TimeStamp( year, month, day );

            CoreObject* ots = vm->findWKI( "TimeStamp" )->asClass()->createInstance();
            ots->setUserData( ts );
            value = ots;
            break;
        }

    case PG_TYPE_TIME:
    case PG_TYPE_TIMETZ: // todo: handle tz
        {
            VMachine* vm = VMachine::getCurrent();
            if ( vm == 0 )
                return false;

            String tv( v );
            int64 hour, minute, second;
            tv.subString( 0, 2 ).parseInt( hour );
            tv.subString( 3, 5 ).parseInt( minute );
            tv.subString( 6, 8 ).parseInt( second );
            TimeStamp* ts = new TimeStamp( 0, 0, 0, hour, minute, second );

            CoreObject* ots = vm->findWKI( "TimeStamp" )->asClass()->createInstance();
            ots->setUserData( ts );
            value = ots;
            break;
        }

    case PG_TYPE_TIMESTAMP:
    case PG_TYPE_TIMESTAMPTZ: // todo: handle tz
        {
            VMachine* vm = VMachine::getCurrent();
            if ( vm == 0 )
                return false;

            String tv( v );
            int64 year, month, day, hour, minute, second;
            tv.subString(  0,  4 ).parseInt( year );
            tv.subString(  5,  7 ).parseInt( month );
            tv.subString(  8, 10 ).parseInt( day );
            tv.subString( 11, 13 ).parseInt( hour );
            tv.subString( 14, 16 ).parseInt( minute );
            tv.subString( 17, 19 ).parseInt( second );
            TimeStamp* ts = new TimeStamp( year, month, day, hour, minute, second );

            CoreObject* ots = vm->findWKI( "TimeStamp" )->asClass()->createInstance();
            ots->setUserData( ts );
            value = ots;
            break;
        }

    case PG_TYPE_CHAR2:
    case PG_TYPE_CHAR4:
    case PG_TYPE_CHAR8:
    case PG_TYPE_TEXT:
    case PG_TYPE_VARCHAR:
    default:
        {
            String s( v );
            s.bufferize();
            value = s;
            break;
        }
    }
    return true;
}


void DBIRecordsetPgSQL::close()
{
    if ( m_res != NULL )
    {
        PQclear( m_res );
        m_pConn->decref();
        m_res = NULL;
    }
}

/*
    DBIStatementPgSQL class
 */

DBIStatementPgSQL::DBIStatementPgSQL( DBIHandlePgSQL* dbh )
    :
    DBIStatement( dbh ),
    m_pConn( dbh->getConnRef() )
{
    m_pConn->incref();
}

void DBIStatementPgSQL::init( const String& query, const String& name )
{
    fassert( name.length() );
    m_name = name;

    String temp;
    m_nParams = dbi_pgsqlQuestionMarksToDollars( query, temp );

    AutoCString zQuery( temp );
    AutoCString zName( name );
    PGresult* res = PQprepare( m_pConn->handle(), zName.c_str(), zQuery.c_str(), m_nParams, NULL );

    if ( res == NULL
        || PQresultStatus( res ) != PGRES_COMMAND_OK )
    {
        DBIHandlePgSQL::throwError( __FILE__, __LINE__, res );
    }

    PQclear( res );

    getExecString( m_nParams, name );
}


DBIStatementPgSQL::~DBIStatementPgSQL()
{
    close();
}


void DBIStatementPgSQL::getExecString( uint32 nParams, const String& name )
{
    fassert( name.length() );

    m_execString.reserve( 11 + name.length() + ( nParams * 2 ) );
    m_execString.size( 0 );
    m_execString = "EXECUTE " + name + "(";
    if ( nParams > 0 )
    {
        m_execString.append( "?" );
        for ( uint32 i=1; i < nParams; ++i )
            m_execString.append( ",?" );
    }
    m_execString.append( ");" );
}


DBIRecordset* DBIStatementPgSQL::execute( ItemArray* params )
{
    String output;
    if ( (params == 0 && m_nParams != 0) ||
          (params != 0 && (params->length() != m_nParams
        || !dbi_sqlExpand( m_execString, output, *params ) ) ) )
    {
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_BIND_SIZE, __LINE__ ) );
    }
    AutoCString zQuery( output );

    PGresult* res = PQexec( ((DBIHandlePgSQL*)m_dbh)->getConn(), zQuery.c_str() );

    if ( res == 0 )
        DBIHandlePgSQL::throwError( __FILE__, __LINE__, res );

    ExecStatusType st = PQresultStatus( res );

    // have we a resultset?
    if ( st == PGRES_TUPLES_OK  )
    {
       return new DBIRecordsetPgSQL( static_cast<DBIHandlePgSQL*>(m_dbh), res );
    }
    else
    if ( st != PGRES_COMMAND_OK )
    {
        DBIHandlePgSQL::throwError( __FILE__, __LINE__, res );
    }

    // no result
    PQclear( res );
    return 0;
}


void DBIStatementPgSQL::reset()
{
}


void DBIStatementPgSQL::close()
{
    // deallocate the stored procedure
    String query = "DEALLOCATE ";
    query += m_name;
    AutoCString zQuery( query );
    PGresult* res = PQexec( ((DBIHandlePgSQL*)m_dbh)->getConn(), zQuery.c_str() );
    if ( res != 0 )
        PQclear( res );

    if( m_pConn != 0 )
    {
        m_pConn->decref();
        m_pConn = 0;
    }
}


/******************************************************************************
 * DB Handler class
 *****************************************************************************/


DBIHandlePgSQL::DBIHandlePgSQL( PGconn *conn )
    :
    m_conn( conn ),
    m_bInTrans( false ),
    m_pConn( new PgSQLHandlerRef(conn) )
{}


DBIHandlePgSQL::~DBIHandlePgSQL()
{
    close();
}


void DBIHandlePgSQL::close()
{
    if ( m_conn != 0 )
    {
        if ( m_bInTrans )
        {
            PGresult* res = PQexec( m_conn, "COMMIT" );
            m_bInTrans = false;
            if ( res != 0 )
                PQclear( res );
        }
        m_pConn->decref();
        m_conn = 0;
    }
}


void DBIHandlePgSQL::options( const String& params )
{
    if ( !m_settings.parse( params ) )
    {
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_OPTPARAMS, __LINE__ )
            .extra( params ) );
    }
}


const DBISettingParams* DBIHandlePgSQL::options() const
{
    return &m_settings;
}


void DBIHandlePgSQL::throwError( const char* file, int line, PGresult* res )
{
    fassert( res );

    int code = (int) PQresultStatus( res );
    const char* err = PQresultErrorMessage( res );

    if ( err != NULL && err[0] != '\0' )
    {
        String desc = err;
        desc.remove( desc.length() - 1, 1 ); // Get rid of newline
        desc.bufferize();

        PQclear( res );

        throw new DBIError( ErrorParam( code, line )
            .extra( desc )
            .module( file ) );
    }
    else
    {
        PQclear( res );

        throw new DBIError( ErrorParam( code, line )
            .module( file ) );
    }
}


void DBIHandlePgSQL::begin()
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    if ( m_bInTrans )
        return;

    PGresult* res = PQexec( m_conn, "BEGIN" );
    if ( res == 0
        || PQresultStatus( res ) != PGRES_COMMAND_OK )
    {
        throwError( __FILE__, __LINE__, res );
    }

    m_bInTrans = true;
    PQclear( res );
}


void DBIHandlePgSQL::commit()
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    if ( !m_bInTrans )
        return;

    PGresult* res = PQexec( m_conn, "COMMIT" );
    if ( res == 0
        || PQresultStatus( res ) != PGRES_COMMAND_OK )
    {
        throwError( __FILE__, __LINE__, res );
    }

    m_bInTrans = false;
    PQclear( res );
}


void DBIHandlePgSQL::rollback()
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    if ( !m_bInTrans )
        return;

    PGresult* res = PQexec( m_conn, "ROLLBACK" );
    if ( res == 0
        || PQresultStatus( res ) != PGRES_COMMAND_OK )
    {
        throwError( __FILE__, __LINE__, res );
    }

    m_bInTrans = false;
    PQclear( res );
}


PGresult* DBIHandlePgSQL::internal_exec( const String& sql, int64& affectedRows )
{
    fassert( m_conn );

    AutoCString cStr( sql );
    PGresult* res = PQexec( m_conn, cStr.c_str() );

    if ( res == NULL )
        throwError( __FILE__, __LINE__, res );

    ExecStatusType st = PQresultStatus( res );
    if ( st != PGRES_TUPLES_OK
        && st != PGRES_COMMAND_OK )
        throwError( __FILE__, __LINE__, res );

    const char* num = PQcmdTuples( res );
    if ( num && num[0] != '\0' )
        affectedRows = atoi( num );
    else
        affectedRows = -1;

    return res;
}


DBIRecordset* DBIHandlePgSQL::query( const String &sql, ItemArray* params )
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    PGresult* res = 0;
    if ( params != 0 && params->length() != 0 )
    {
        String output;
        if ( !dbi_sqlExpand( sql, output, *params ) )
        {
            throw new DBIError( ErrorParam( FALCON_DBI_ERROR_QUERY, __LINE__ ) );
        }
        res = internal_exec( output, m_nLastAffected );
    }
    else
    {
        res = internal_exec( sql, m_nLastAffected );
    }
    fassert( res != 0 );

    ExecStatusType st = PQresultStatus( res );

    // have we a resultset?
    if ( st == PGRES_TUPLES_OK  )
    {
       return new DBIRecordsetPgSQL( this, res );
    }

    // no result
    fassert( st == PGRES_COMMAND_OK );
    PQclear( res );
    return 0;
}


DBIStatement* DBIHandlePgSQL::prepare( const String &query )
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    DBIStatementPgSQL* stmt = new DBIStatementPgSQL( this );

    // the statement may throw
    try {
       stmt->init( query );
       return stmt;
    }
    catch( ... )
    {
       delete stmt;
       throw;
    }
}


DBIStatement* DBIHandlePgSQL::prepareNamed( const String &name, const String& query )
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    DBIStatementPgSQL* stmt = new DBIStatementPgSQL( this );

    // the statement may throw
    try {
       stmt->init( query, name );
       return stmt;
    }
    catch( ... )
    {
       delete stmt;
       throw;
    }
}


int64 DBIHandlePgSQL::getLastInsertedId( const String& name )
{
    if ( m_conn == 0 )
        throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CLOSED_DB, __LINE__ ) );

    /* so... PQoidValue does it but takes a PGresult.
    We can retrieve a PGresult in case of prepared statements only...
    */

    AutoCString nm( name );
    PGresult* res = PQdescribePrepared( m_conn, nm.c_str() );
    int oid = -1;

    if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
        goto finish;
    else
        oid = (int) PQoidValue( res );

  finish:
    PQclear( res );
    return oid;
}


void DBIHandlePgSQL::selectLimited( const String& query, int64 nBegin, int64 nCount, String& result )
{
    String sBegin, sCount;

    if( nCount > 0 )
        sCount.A( " LIMIT " ).N( nCount );

    if ( nBegin > 0 )
        sBegin.A( " OFFSET " ).N( nBegin );

    result = "SELECT " + query + sCount + sBegin;
}


/******************************************************************************
 * Main service class
 *****************************************************************************/

void DBIServicePgSQL::init()
{
}


DBIHandle *DBIServicePgSQL::connect( const String &parameters )
{
   AutoCString connParams( parameters );
   PGconn *conn = PQconnectdb( connParams.c_str () );
   if ( conn == NULL )
   {
      throw new DBIError( ErrorParam( FALCON_DBI_ERROR_NOMEM, __LINE__ ) );
   }

   if ( PQstatus( conn ) != CONNECTION_OK )
   {
      String errorMessage = PQerrorMessage( conn );
      errorMessage.remove( errorMessage.length() - 1, 1 ); // Get rid of newline
      errorMessage.bufferize();

      PQfinish( conn );

      throw new DBIError( ErrorParam( FALCON_DBI_ERROR_CONNECT, __LINE__ )
              .extra( errorMessage ) );
   }

   return new DBIHandlePgSQL( conn );
}


CoreObject *DBIServicePgSQL::makeInstance( VMachine *vm, DBIHandle *dbh )
{
   Item *cl = vm->findWKI( "PgSQL" );
   if ( cl == 0 || ! cl->isClass() || cl->asClass()->symbol()->name() != "PgSQL" )
   {
      throw new DBIError( ErrorParam( FALCON_DBI_ERROR_INVALID_DRIVER, __LINE__ ) );
   }

   CoreObject *obj = cl->asClass()->createInstance();
   obj->setUserData( dbh );

   return obj;
}

} /* namespace Falcon */