baseten / Sources / PGTSConnection-old.m

   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
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//
// PGTSConnection.m
// BaseTen
//
// Copyright (C) 2006 Marko Karppinen & Co. LLC.
//
// Before using this software, please review the available licensing options
// by visiting http://www.karppinen.fi/baseten/licensing/ or by contacting
// us at sales@karppinen.fi. Without an additional license, this software
// may be distributed only in compliance with the GNU General Public License.
//
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 2.0,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
// $Id$
//

#import <PGTS/postgresql/libpq-fe.h> 

#ifdef USE_SSL
#import <openssl/ssl.h>
#endif

#import "TSRunloopMessenger.h"

#import "PGTSConnectionPrivate.h"
#import "PGTSConnection.h"
#import "PGTSResultSetPrivate.h"
#import "PGTSResultSet.h"
#import "PGTSAdditions.h"
#import "PGTSConnectionPool.h"
#import "PGTSConstants.h"
#import "PGTSConnectionDelegate.h"
#import "PGTSFunctions.h"
#import "PGTSDatabaseInfo.h"
#import "PGTSCertificateVerificationDelegate.h"
#import <MKCCollections/MKCCollections.h>
#import <Log4Cocoa/Log4Cocoa.h>


/** \cond */

#define BlockWhileConnecting( CONNECTION_CALL ) { \
    messageDelegateAfterConnecting = NO; \
    if (YES == CONNECTION_CALL) \
	{ \
        [asyncConnectionLock lockWhenCondition: 1]; \
		[asyncConnectionLock unlockWithCondition: 0]; \
	} \
    messageDelegateAfterConnecting = YES; \
    [self finishConnecting]; \
}


#define AssociateSelector( SEL, EXCEPTBIT ) { selector: SEL, exceptBit: EXCEPTBIT }


struct exceptionAssociation
{
    SEL selector;
    int exceptBit;
};

/** \endcond */


static id <PGTSCertificateVerificationDelegate> defaultCertDelegate = nil;

/**
 * Return the result of the given accessor as an NSString
 * Handles returned NULL values safely
 */
static inline NSString*
SafeStatusAccessor (char* (*function)(const PGconn*), PGconn* connection)
{
    char* value = function (connection);
    NSString* rval = nil;
    if (NULL != value)
        rval = [NSString stringWithUTF8String: value];
    return rval;
}

/**
 * Raise an exception if the delegate is invalid
 * Checks from a cache whether the delegate responds to a given selector
 * and raises and exception if needed
 */
static void
CheckExceptionTable (PGTSConnection* sender, int bitMask, BOOL doCheck)
{
    if (doCheck && sender->exceptionTable & bitMask)
    {
        id delegate = [sender delegate];
        NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
            sender, kPGTSConnectionKey, delegate, kPGTSConnectionDelegateKey, nil];
        NSString* reason = NSLocalizedString (@"Asynchronous connecting not allowed for delegate %p; missing methods", @"Exception reason");
        NSException* e = [NSException exceptionWithName: NSInternalInconsistencyException 
                                                 reason: [NSString stringWithFormat: reason, delegate]
                                               userInfo: userInfo];
        [e raise];
    }
}

/** Database connection */
@implementation PGTSConnection

/** Returns an autoreleased connection object */
+ (PGTSConnection *) connection
{
	return [[[[self class] alloc] init] autorelease];
}

+ (void) initialize
{
	static BOOL tooLate = NO;
	if (!tooLate)
	{
		tooLate = YES;
        
        kPGTSSentQuerySelector                  = @selector (PGTSConnection:sentQuery:);
        kPGTSFailedToSendQuerySelector          = @selector (PGTSConnection:failedToSendQuery:);
        kPGTSAcceptCopyingDataSelector          = @selector (PGTSConnection:acceptCopyingData:errorMessage:);
        kPGTSReceivedDataSelector               = @selector (PGTSConnection:receivedData:);
        kPGTSReceivedResultSetSelector          = @selector (PGTSConnection:receivedResultSet:);
        kPGTSReceivedErrorSelector              = @selector (PGTSConnection:receivedError:);
        kPGTSReceivedNoticeSelector             = @selector (PGTSConnection:receivedNotice:);
        
        kPGTSConnectionFailedSelector           = @selector (PGTSConnectionFailed:);
        kPGTSConnectionEstablishedSelector      = @selector (PGTSConnectionEstablished:);
        kPGTSStartedReconnectingSelector        = @selector (PGTSConnectionStartedReconnecting:);
        kPGTSDidReconnectSelector               = @selector (PGTSConnectionDidReconnect:);
        
        {
            NSMutableArray* keys = [NSMutableArray array];
            kPGTSDefaultConnectionDictionary = [[NSMutableDictionary alloc] init];
            
            PQconninfoOption *option = PQconndefaults ();
            char* keyword = NULL;
            while ((keyword = option->keyword))
            {
                NSString* key = [NSString stringWithUTF8String: keyword];
                [keys addObject: key];
                char* value = option->val;
                if (NULL == value)
                    value = getenv ([key UTF8String]);
                if (NULL == value)
                    value = option->compiled;
                if (NULL != value)
                {
                    [(NSMutableDictionary *) kPGTSDefaultConnectionDictionary setObject: 
                                          [NSString stringWithUTF8String: value] forKey: key];
                }
                option++;
            }
            kPGTSConnectionDictionaryKeys = [keys copy];
			
			//sslmode is disabled by default??
			[(NSMutableDictionary *) kPGTSDefaultConnectionDictionary setObject: @"prefer" forKey: @"sslmode"];
        }		
        defaultCertDelegate = [[PGTSCertificateVerificationDelegate alloc] init];
	}
}

- (id) init
{    
    if ((self = [super init]))
    {
        connection = NULL;
        connectionLock = [[NSLock alloc] init];
        connectionStatus = CONNECTION_BAD;
        messageDelegateAfterConnecting = YES;
        //socket is managed by the worker thread
        cancelRequest = NULL;
        timeout.tv_sec = 10;
        timeout.tv_usec = 0;
        
        workerThreadLock = [[NSLock alloc] init];
        asyncConnectionLock = [[NSConditionLock alloc] initWithCondition: 0];
        
        postgresNotificationCenter = [[NSNotificationCenter PGTSNotificationCenter] retain];
        notificationCounts = [[NSCountedSet alloc] init];
        notificationAssociations = [[NSMutableDictionary alloc] init];
        
        [self setConnectionDictionary: kPGTSDefaultConnectionDictionary];
        
        resultSetClass = [PGTSResultSet class];
        
        parameterCounts = [MKCDictionary copyDictionaryWithKeyType: kMKCCollectionTypeObject 
                                                         valueType: kMKCCollectionTypeInteger];
        delegateProcessesNotices = NO;
        overlooksFailedQueries = YES;
        connectsAutomatically = NO;
        reconnectsAutomatically = NO;
        logsQueries = NO;
        failedToSendQuery = NO;
        initialCommands = nil;
        //databaseInfo is set after the connection has been made
		certificateVerificationDelegate = defaultCertDelegate;
        
        exceptionTable = 0;
        [self setDelegate: nil];        

        id messenger = [TSRunloopMessenger runLoopMessengerForCurrentRunLoop];
        mainProxy          = [[messenger target: self withResult: NO]  retain];
        returningMainProxy = [[messenger target: self withResult: YES] retain];
        NSConditionLock* threadStartLock = [[NSConditionLock alloc] initWithCondition: 0];

        //Wait for the worker thread to start
        [NSThread detachNewThreadSelector: @selector (workerThreadMain:) toTarget: self withObject: threadStartLock];
        [threadStartLock lockWhenCondition: 1];
        [threadStartLock unlock];
        [threadStartLock release];        
    }
	return self;
}

/**
 * Construct a similiar connection object without actually connecting to the database.
 */
- (id) disconnectedCopy
{
    PGTSConnection* anObject = [[[self class] alloc] init];
    anObject->timeout = timeout;
    [anObject setConnectionString: connectionString];
    [anObject setDeserializationDictionary: deserializationDictionary];
    anObject->connectsAutomatically = connectsAutomatically;
    anObject->reconnectsAutomatically = reconnectsAutomatically;
    anObject->overlooksFailedQueries = overlooksFailedQueries;
    [anObject setInitialCommands: initialCommands];
    anObject->resultSetClass = resultSetClass;
    [anObject setDelegate: delegate];
    anObject->logsQueries = logsQueries;
    
    return anObject;
}

- (void) dealloc
{
    [self disconnect];
    //Wait for the other thread to end
    [self endWorkerThread];
    
	[postgresNotificationCenter release];
    [notificationCounts release];
    [notificationAssociations release];
	
    [connectionLock release];
    [asyncConnectionLock release];
    [workerThreadLock release];
        
    [connectionString release];
    [parameterCounts release];
	[deserializationDictionary release];
    [initialCommands release];
	[errorMessage release];
    
    log4Debug (@"Deallocating db connection: %p", self);
    [super dealloc];
}

/**
 * Connect or reconnect asynchronously.
 * The delegate is required to respond to some related messages
 */
//@{
- (BOOL) connectAsync
{
    BOOL rval = NO;
    CheckExceptionTable (self, kPGTSRaiseForConnectAsync, messageDelegateAfterConnecting);

	if (NO == connecting)
	{
		connecting = YES;
		connectingAsync = YES;
	}
	
	[connectionLock lock];
	if (NULL != connection)
	{
		PQfinish (connection);
		connection = NULL;
	}
	[connectionLock unlock];
	
	const char* conninfo = [connectionString UTF8String];
	if ((connection = PQconnectStart (conninfo)))
	{
		rval = YES;
		[workerProxy workerPollConnectionResetting: NO];
	}
	else
	{
		connecting = NO;
	}
	
    return rval;
}

- (BOOL) reconnectAsync
{
    BOOL rval = NO;
    CheckExceptionTable (self, kPGTSRaiseForReconnectAsync, messageDelegateAfterConnecting);
    if (NULL != connection && 1 == PQresetStart (connection))
    {
        rval = YES;
        [workerProxy workerPollConnectionResetting: YES];
    }    
    return rval;
}
//@}

/**
 * Connect or reconnect synchronously
 */
//@{
- (ConnStatusType) connect
{
	connecting = YES;
    BlockWhileConnecting ([self connectAsync]);
	connecting = NO;
    return connectionStatus;
}

- (ConnStatusType) reconnect
{
    if (CONNECTION_OK != connectionStatus)
        BlockWhileConnecting ([self reconnectAsync]);
    return connectionStatus;
}
//@}

/**
 * End the worker thread
 */
- (void) endWorkerThread
{
	if (YES == shouldContinueThread)
	{
		messageDelegateAfterConnecting = NO;
		[asyncConnectionLock lock];
		[asyncConnectionLock unlock];
		[workerProxy workerEnd];
		[workerThreadLock lock];
		[workerThreadLock unlock];
		
		[mainProxy release];
		[returningMainProxy release];
		mainProxy = nil;
		returningMainProxy = nil;
	}
}


/**
 * Disconnect from the database
 */
- (void) disconnect
{
   if (NULL != connection)
   {
       [asyncConnectionLock lock];
       [asyncConnectionLock unlock];
       NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
       [nc postNotificationName: kPGTSWillDisconnectNotification object: self];
       [[PGTSConnectionPool sharedInstance] removeConnection: self];
       
	   [returningWorkerProxy workerCleanUpDisconnecting: YES];	   
       [nc postNotificationName: kPGTSDidDisconnectNotification object: self];
   }
}

- (NSNotificationCenter *) postgresNotificationCenter
{
    return postgresNotificationCenter;
}

/**
 * Send a LISTEN query and register an object to receive notifications from this connection
 * \param anObject The observer
 * \param aSelector The method to be called upon notification. It should take one parameter the type of which is NSNotification
 */
- (void) startListening: (id) anObject forNotification: (NSString *) notificationName selector: (SEL) aSelector
{    
    [self startListening: anObject forNotification: notificationName 
                selector: aSelector sendQuery: YES];
}

- (void) startListening: (id) anObject forNotification: (NSString *) notificationName 
               selector: (SEL) aSelector sendQuery: (BOOL) sendQuery
{
    //Keep track of listeners although this should probably be done in the NotificationCenter
    NSValue* objectIdentifier = [NSValue valueWithPointer: anObject];
    NSMutableSet* objectNotifications = [notificationAssociations objectForKey: objectIdentifier];
    if (nil == objectNotifications)
    {
        objectNotifications = [NSMutableSet set];
        [notificationAssociations setObject: objectNotifications forKey: objectIdentifier];
    }
    else if ([objectNotifications containsObject: notificationName])
        return; //We already were listening
    
    [postgresNotificationCenter addObserver: anObject 
                                   selector: aSelector
                                       name: notificationName 
                                     object: self];    
    if (sendQuery && ![notificationCounts containsObject: notificationName])
    {
        [self executeQuery: [NSString stringWithFormat: @"LISTEN \"%@\"", notificationName]];
    }
    
    [objectNotifications addObject: notificationName];
    [notificationCounts addObject: notificationName];
}

/**
 * Remove an object as the observer of notifications with the given name
 * An UNLISTEN query is also sent if the object is the only observer for the given notification
 */
- (void) stopListening: (id) anObject forNotification: (NSString *) notificationName
{
    NSValue* objectIdentifier = [NSValue valueWithPointer: anObject];
    NSMutableSet* objectNotifications = [notificationAssociations objectForKey: objectIdentifier];
    if ([objectNotifications containsObject: notificationName])
    {
        [objectNotifications removeObject: notificationName];
        [notificationCounts removeObject: notificationName];
        if (![notificationCounts containsObject: notificationName])
        {
            [self executeQuery: [@"UNLISTEN " stringByAppendingString: notificationName]];
        }
        
        [postgresNotificationCenter removeObserver: anObject 
                                              name: notificationName 
                                            object: self];
    }
}

/**
 * Remove an object as the observer of any notifications
 */
- (void) stopListening: (id) anObject
{
    NSValue* objectIdentifier = [NSValue valueWithPointer: anObject];
    NSEnumerator* e = [[notificationAssociations objectForKey: objectIdentifier] objectEnumerator];
    NSString* notificationName;

    [notificationAssociations removeObjectForKey: objectIdentifier];
    [postgresNotificationCenter removeObserver: anObject];
	
    while ((notificationName = [e nextObject]))
    {
        [notificationCounts removeObject: notificationName];
        if (![notificationCounts containsObject: notificationName])
			[self executeQuery: [@"UNLISTEN " stringByAppendingString: notificationName]];
    }
}

@end


/** Miscellaneous accessors */
@implementation PGTSConnection (MiscAccessors)

/** Returns YES if OpenSSL was linked at compile time */
+ (BOOL) hasSSLCapability
{
#ifdef USE_SSL
    return YES;
#else
    return NO;
#endif
}

/** Connection status */
- (ConnStatusType) status
{
    return connectionStatus;
}

/** The connection object from libpq */
- (PGconn *) pgConnection
{
    return connection;
}

/**
 * Connection variables.
 */
//@{
- (BOOL) setConnectionURL: (NSURL *) url
{
    log4Debug (@"Connection URL: %@", url);
	BOOL rval = NO;
	NSDictionary* connectionDict = [url PGTSConnectionDictionary];
	if (nil != connectionDict)
	{
		[self setConnectionDictionary: connectionDict];
		rval = YES;
	}	
    return rval;
}

/** \sa PGTSConstants.h for keys */
- (void) setConnectionDictionary: (NSDictionary *) userDict
{
    NSMutableDictionary* connectionDict = [[kPGTSDefaultConnectionDictionary mutableCopy] autorelease];
    [connectionDict addEntriesFromDictionary: userDict];
	
	if (nil == [connectionDict objectForKey: kPGTSConnectTimeoutKey])
	{
		int seconds = [self timeout].tv_sec;
		[connectionDict setObject: [NSNumber numberWithInt: seconds] forKey: kPGTSConnectTimeoutKey];
	}
	
    [self setConnectionString: [connectionDict PGTSConnectionString]];
}

/** Set the connection string directly */
- (void) setConnectionString: (NSString *) aString
{
    if (connectionString != aString)
    {
        [connectionString release];
        connectionString = [aString retain];
    }
}
//@}

/** Return the connection string set using an NSDictionary or NSString */
- (NSString *) connectionString
{
    return connectionString;
}

/**
 * The delegate
 */
//@{
- (id <PGTSConnectionDelegate>) delegate
{
    return delegate;
}

- (void) setDelegate: (id <PGTSConnectionDelegate>) anObject
{    
    delegate = anObject;
    
    delegateProcessesNotices = NO;
    if ([anObject respondsToSelector: kPGTSReceivedNoticeSelector])
        delegateProcessesNotices = YES;
    
    struct exceptionAssociation associations [] =
    {
        //AssociateSelector (kPGTSSentQuerySelector, kPGTSRaiseForCompletelyAsync),
        AssociateSelector (kPGTSFailedToSendQuerySelector, kPGTSRaiseForCompletelyAsync),
        AssociateSelector (kPGTSAcceptCopyingDataSelector, kPGTSRaiseForSendCopyData),
        AssociateSelector (kPGTSReceivedDataSelector, kPGTSRaiseForReceiveCopyData),
        AssociateSelector (kPGTSReceivedResultSetSelector, kPGTSRaiseForAsync),
        //AssociateSelector (kPGTSReceivedErrorSelector, kPGTSRaiseForAsync),
        
        AssociateSelector (kPGTSConnectionFailedSelector, kPGTSRaiseForConnectAsync),
        AssociateSelector (kPGTSConnectionEstablishedSelector, kPGTSRaiseForConnectAsync),
        AssociateSelector (kPGTSConnectionFailedSelector, kPGTSRaiseForReconnectAsync),
        AssociateSelector (kPGTSDidReconnectSelector, kPGTSRaiseForReconnectAsync),

        AssociateSelector (NULL, 0)
    };
    
    for (int i = 0; NULL != associations [i].selector; i++)
    {
        //Cancel only the exceptions the delegate is responsible for
        exceptionTable &= ~associations [i].exceptBit;
    }

    for (int i = 0; NULL != associations [i].selector; i++)
    {
        if (NO == [anObject respondsToSelector: associations [i].selector])
            exceptionTable |= associations [i].exceptBit;
    }    
}
//@}

- (BOOL) overlooksFailedQueries
{
    return overlooksFailedQueries;
}

/**
 * Set the framework to call PGTSConnection:receivedResultSet: instead of PGTSConnection:receivedError:
 */
- (void) setOverlooksFailedQueries: (BOOL) aBool
{
    overlooksFailedQueries = aBool;
}

/**
 * Connect automatically after awakeFromNib
 */
//@{
- (BOOL) connectsAutomatically
{
    return connectsAutomatically;
}

- (void) setConnectsAutomatically: (BOOL) aBool
{
    connectsAutomatically = aBool;
}
//@}

/**
 * Reset connection automatically
 */
//@{
- (BOOL) reconnectsAutomatically
{
    return reconnectsAutomatically;
}

- (void) setReconnectsAutomatically: (BOOL) aBool
{
    reconnectsAutomatically = aBool;
}
//@}

/**
 * Initial commands after making the connecting
 * \sa sendFinishedConnectingMessage:reconnect:
 */
//@{
- (NSString *) initialCommands
{
    return initialCommands;
}

- (void) setInitialCommands: (NSString *) aString
{
    if (aString != initialCommands)
    {
        [initialCommands release];
        initialCommands = [aString retain];
    }
}
//@}

/**
 * Information object related to the connected database
 */
//@{
/** \return the PGTSDatabaseInfo object, or nil if disconnected */
- (PGTSDatabaseInfo *) databaseInfo
{
    return databaseInfo;
}
/** Make a weak reference to the given object */
- (void) setDatabaseInfo: (PGTSDatabaseInfo *) anObject
{
    databaseInfo = anObject;
}
//@}

/**
 * The deserialization dictionary for result sets returned by this connection
 */
//@{
- (NSMutableDictionary *) deserializationDictionary
{
    return deserializationDictionary;
}

- (void) setDeserializationDictionary: (NSMutableDictionary *) aDictionary
{
    if (deserializationDictionary != aDictionary)
    {
        [deserializationDictionary release];
        deserializationDictionary = [aDictionary retain];
    }
}
//@}

/**
 * Connection timeout
 */
//@{
- (struct timeval) timeout
{
    return timeout;
}

- (void) setTimeout: (struct timeval) value
{
    timeout = value;
}
//@}

- (void) setLogsQueries: (BOOL) aBool
{
    logsQueries = aBool;
}

- (BOOL) logsQueries
{
    return logsQueries;
}

- (id <PGTSCertificateVerificationDelegate>) certificateVerificationDelegate
{
	return certificateVerificationDelegate;
}

- (void) setCertificateVerificationDelegate: (id <PGTSCertificateVerificationDelegate>) anObject
{
	certificateVerificationDelegate = anObject;
	if (nil == certificateVerificationDelegate)
		certificateVerificationDelegate = defaultCertDelegate;
}

- (BOOL) connectingAsync
{
	return (connecting && connectingAsync);
}
@end


/** 
 * Convenience methods for transaction handling
 * \return a BOOL indicating whether the query was successful
 */
@implementation PGTSConnection (TransactionHandling)
- (BOOL) beginTransaction
{
    return ((nil != [self executeQuery: @"BEGIN"]));
}

- (BOOL) commitTransaction
{
    return ((nil != [self executeQuery: @"COMMIT"]));
}

- (BOOL) rollbackTransaction
{
    return ((nil != [self executeQuery: @"ROLLBACK"]));
}

- (BOOL) rollbackToSavepointNamed: (NSString *) aName
{
    return ((nil != [self executeQuery: [NSString stringWithFormat: @"ROLLBACK TO SAVEPOINT %@", aName]]));
}

- (BOOL) savepointNamed: (NSString *) aName
{
    return ((nil != [self executeQuery: [NSString stringWithFormat: @"SAVEPOINT %@", aName]]));
}
@end


/** 
 * Connection status 
 */
@implementation PGTSConnection (StatusMethods)

- (BOOL) connected
{
	ConnStatusType status = [self connectionStatus];
    return (NULL != connection && CONNECTION_OK == status);
}

- (NSString *) databaseName
{
    return SafeStatusAccessor (&PQdb, connection);
}

- (NSString *) user
{
    return SafeStatusAccessor (&PQuser, connection);
}

- (NSString *) password
{
    return SafeStatusAccessor (&PQpass, connection);
}

- (NSString *) host
{
    return SafeStatusAccessor (&PQhost, connection);
}

- (long) port
{
    long rval = 0;
    char* portString = PQport (connection);
    if (NULL != portString)
        rval = strtol (portString, NULL, 10);
    return rval;
}

- (NSString *) commandLineOptions
{
    return SafeStatusAccessor (&PQoptions, connection);
}

- (ConnStatusType) connectionStatus
{
    return PQstatus (connection);
}

- (PGTransactionStatusType) transactionStatus
{
    return PQtransactionStatus (connection);
}

- (NSString *) statusOfParameter: (NSString *) parameterName
{
    NSString* rval = nil;
    if (nil != parameterName)
    {
        const char* value = PQparameterStatus (connection, 
                                               [parameterName UTF8String]);
        if (NULL != value)
            rval = [NSString stringWithUTF8String: value];
    }
    return rval;
}

- (int) protocolVersion
{
    return PQprotocolVersion (connection);
}

- (int) serverVersion
{
    return PQserverVersion (connection);
}

/**
 * The last error message.
 */
- (NSString *) errorMessage
{
    NSString* rval = nil;
    char* message = PQerrorMessage (connection);
    if (0 != strlen (message))
        rval = [NSString stringWithUTF8String: message];
	else
		rval = errorMessage;
	return rval;
}

- (int) backendPID
{
	return PQbackendPID (connection);
}

- (void *) sslStruct
{
#ifdef USE_SSL
	return PQgetssl (connection);
#else
    return NULL;
#endif
}

- (PGConnectionErrorCode) errorCode
{
	return PQerrorCode (connection);
}

@end


/** NSCoding implementation */
@implementation PGTSConnection (NSCoding)

- (id) initWithCoder: (NSCoder *) decoder
{
    if ((self = [super init]))
    {
        unsigned int returnedLength = 0;
        {
            //exceptionTable is set in setDelegate:
            
            connection = NULL;
            connectionLock = [[NSLock alloc] init];
            {
                timeout.tv_sec  = *[decoder decodeBytesForKey: @"timeout.tv_sec"  returnedLength: &returnedLength];
                if (sizeof (timeout.tv_sec) != returnedLength)
                    [[NSException exceptionWithName: NSInternalInconsistencyException reason: nil userInfo: nil] raise];
                timeout.tv_usec = *[decoder decodeBytesForKey: @"timeout.tv_usec" returnedLength: &returnedLength];
                if (sizeof (timeout.tv_usec) != returnedLength)
                    [[NSException exceptionWithName: NSInternalInconsistencyException reason: nil userInfo: nil] raise];
            }
            connectionString = [[decoder decodeObjectForKey: @"connectionString"] retain];
            connectionStatus = CONNECTION_BAD;
            messageDelegateAfterConnecting = YES;
            
            //socket               is set in workerThreadMain:
            asyncConnectionLock  = [[NSConditionLock alloc] initWithCondition: 0];
            workerThreadLock     = [[NSLock alloc] init];
            //shouldContinueThread is set in workerThreadMain:
            //threadRunning        is set in workerThreadMain:
            {
                id messenger       = [TSRunloopMessenger runLoopMessengerForCurrentRunLoop];            
                mainProxy          = [[messenger target: self withResult: NO]  retain];
                returningMainProxy = [[messenger target: self withResult: YES] retain];
            }
            //workerProxy          is set in workerThreadMain:
            //returningWorkerProxy is set in workerThreadMain:
            
            postgresNotificationCenter = [[NSNotificationCenter PGTSNotificationCenter] retain];
            notificationCounts = [[NSCountedSet alloc] init];
            notificationAssociations = [[NSMutableDictionary alloc] init];

            cancelRequest = NULL;
            //databaseInfo is set after the connection has been made
            parameterCounts = [MKCDictionary copyDictionaryWithKeyType: kMKCCollectionTypeObject
                                                             valueType: kMKCCollectionTypeInteger];
            deserializationDictionary = [decoder decodeObjectForKey: @"deserializationDictionary"];
            connectsAutomatically =  [decoder decodeBoolForKey: @"connectsAutomatically"];
            reconnectsAutomatically =  [decoder decodeBoolForKey: @"reconnectsAutomatically"];
            overlooksFailedQueries = [decoder decodeBoolForKey: @"overlooksFailedQueries"];
            delegateProcessesNotices = NO; //sic
            logsQueries = [decoder decodeBoolForKey: @"logQueries"];
            initialCommands = [[decoder decodeObjectForKey: @"initialCommands"] retain];
            {
                resultSetClass = NSClassFromString ([decoder decodeObjectForKey: @"resultSetClass"]);
                if (Nil == resultSetClass)
                    [[NSException exceptionWithName: NSInternalInconsistencyException reason: nil userInfo: nil] raise];
            }
            [self setDelegate: [decoder decodeObjectForKey: @"delegate"]];
        }
                
        {
            //Wait for the worker thread to start
            NSLock* threadStartLock = [[NSLock alloc] init];
            [threadStartLock lock];
            [NSThread detachNewThreadSelector: @selector (workerThreadMain:) toTarget: self withObject: threadStartLock];
            [threadStartLock lock];
            [threadStartLock unlock];
            [threadStartLock release];
            
            [[PGTSConnectionPool sharedInstance] addConnection: self];
        }
            
        if (connectsAutomatically)
            [self connect];
    }
    return self;
}

- (void) encodeWithCoder: (NSCoder *) encoder
{
    //Operate on a disconnected copy to make reconnecting possible
    PGTSConnection* c = [self disconnectedCopy];
    {
        //exceptionTable is set in setDelegate:
        
        //connection     is reinitialized
        //connectionLock is reinitialized
        {
            [encoder encodeBytes: (const uint8_t *) &c->timeout.tv_sec  length: sizeof (c->timeout.tv_sec)  forKey: @"timeout.tv_sec"];
            [encoder encodeBytes: (const uint8_t *) &c->timeout.tv_usec length: sizeof (c->timeout.tv_usec) forKey: @"timeout.tv_usec"];        
        }
        [encoder encodeObject: c->connectionString forKey: @"connectionString"];
        //connectionStatus is reinitialized
        //messageDelegateAfterConnecting is reinitialized
        
        //socket               is set in workerThreadMain:
        //asyncConnectionLock  is reinitialized
        //workerThreadLock     is reinitialized
        //shouldContinueThread is set in workerThreadMain:
        //threadRunning        is set in workerThreadMain:
        //mainProxy            is reinitialized
        //returningMainProxy   is reinitialized
        //workerProxy          is set in workerThreadMain:
        //returningWorkerProxy is set in workerThreadMain:
        
        //postgresNotificationCenter is reinitialized
        //notificationCounts         is reinitialized
        //notificationAssociations   is reinitialized
        
        //cancelRequest   is reinitialized
        //databaseInfo    is reinitialized
        //parameterCounts is reinitialized
        [encoder encodeObject: c->deserializationDictionary forKey: @"deserializationDictionary"];
        [encoder encodeBool: c->connectsAutomatically forKey: @"connectsAutomatically"];
        [encoder encodeBool: c->reconnectsAutomatically forKey: @"reconnectsAutomatically"];
        [encoder encodeBool: c->overlooksFailedQueries forKey: @"overlooksFailedQueries"];
        //delegateProcessesNotices is reinitialized (sic)
        [encoder encodeBool: c->logsQueries forKey: @"logQueries"];
        [encoder encodeObject: c->initialCommands forKey: @"initialCommands"];
        [encoder encodeObject: NSStringFromClass (c->resultSetClass) forKey: @"resultSetClass"];
        [encoder encodeConditionalObject: c->delegate forKey: @"delegate"];
    }
    [c release];
}


@end
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.