Source

baseten / Sources / PGTSConnection.mm

Full commit
  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
//
// PGTSConnection.mm
// BaseTen
//
// Copyright (C) 2008 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 <CoreFoundation/CoreFoundation.h>
#import <BaseTen/postgresql/libpq-fe.h>

#import "PGTSConnection.h"
#import "PGTSConnectionPrivate.h"
#import "PGTSConnector.h"
#import "PGTSSynchronousConnector.h"
#import "PGTSAsynchronousConnector.h"
#import "PGTSConstants.h"
#import "PGTSQuery.h"
#import "PGTSQueryDescription.h"
#import "PGTSAdditions.h"
#import "PGTSResultSet.h"
#import "PGTSDatabaseDescription.h"
#import "PGTSNotification.h"
#import "PGTSProbes.h"
#import "PGTSMetadataStorage.h"
#import "PGTSMetadataContainer.h"

#import "PGTSInvocationRecorder.h"
#import "BXLogger.h"
#import "BXEnumerate.h"
#import "BXArraySize.h"
#import "BXConstants.h"
#import "BXSocketDescriptor.h"
#import "BXConnectionMonitor.h"

#import "NSString+PGTSAdditions.h"



@interface PGTSConnection (PGTSConnectorDelegate) <PGTSConnectorDelegate>
@end



@interface PGTSConnection (BXSocketDescriptorDelegate) <BXSocketDescriptorDelegate>
@end



static void
NoticeReceiver (void *connectionPtr, PGresult const *notice)
{
	PGTSConnection *connection = (PGTSConnection *) connectionPtr;
	NSError *error = [PGTSResultSet errorForPGresult: notice];
	[[connection delegate] PGTSConnection: connection receivedNotice: error];
}



/**
 * \internal
 * \brief A connection class for Postgresql.
 * \note Instances of this class may be used from multiple threads after a connection has been made.
 */
@implementation PGTSConnection
+ (void) initialize
{
	static BOOL tooLate = NO;
	if (! tooLate)
	{
		tooLate = YES;
				
		{
            NSMutableArray *keys = [[[NSMutableArray alloc] init] autorelease];
			CFRetain (keys);
            PQconninfoOption *options = PQconndefaults ();
            char* keyword = NULL;
            while ((keyword = options->keyword))
            {
                NSString *key = [NSString stringWithUTF8String: keyword];
                [keys addObject: key];
                options++;
            }
			kPGTSConnectionDictionaryKeys = [keys copy];
		}
		
		[[PGTSMetadataStorage defaultStorage] setContainerClass: [PGTSEFMetadataContainer class]];
	}
}


- (id) init
{
	if ((self = [super init]))
	{
		mQueue = [[NSMutableArray alloc] init];
		mCertificateVerificationDelegate = [PGTSCertificateVerificationDelegate defaultCertificateVerificationDelegate];
	}
	return self;
}


- (void) dealloc
{
    [self disconnect];
	[self _setConnector: nil];
	
	[mQueue release];
    [mMetadataContainer release];
	[mPGTypes release];
	[super dealloc];
}


- (BOOL) connectUsingClass: (Class) connectorClass connectionDictionary: (NSDictionary *) connectionDictionary
{
	// FIXME: thread safety?

	PGTSConnector* connector = [[[connectorClass alloc] init] autorelease];
	[self _setConnector: connector];
	
	[connector setConnection: mConnection]; //For resetting.
	[connector setTraceFile: [mDelegate PGTSConnectionTraceFile: self]];
	[[BXConnectionMonitor sharedInstance] clientDidStartConnectionAttempt: self];
	BXLogDebug (@"Making %@ connect.", [connector class]);
	return [connector connect: connectionDictionary];
}


- (void) connectAsync: (NSDictionary *) connectionDictionary
{
	[self connectUsingClass: [PGTSAsynchronousConnector class] connectionDictionary: connectionDictionary];
}


- (BOOL) connectSync: (NSDictionary *) connectionDictionary
{
	return [self connectUsingClass: [PGTSSynchronousConnector class] connectionDictionary: connectionDictionary];
}


- (void) resetAsync
{
	[self connectUsingClass: [PGTSAsynchronousReconnector class] connectionDictionary: nil];
}


- (BOOL) resetSync
{
	return [self connectUsingClass: [PGTSSynchronousReconnector class] connectionDictionary: nil];
}


- (void) disconnect
{
	@synchronized (self)
	{
	    BXLogInfo (@"Disconnecting.");
		[[BXConnectionMonitor sharedInstance] clientWillDisconnect: self];

	    [mConnector cancel];
		[self _setConnector: nil];
	
	    if (mConnection)
	    {        
			PQfinish (mConnection);
	        mConnection = NULL;
		}
	}
	
	[self _setSocketDescriptor: nil];
}


- (PGconn *) pgConnection
{
	PGconn *retval = NULL;
	@synchronized (self)
	{
    	retval = mConnection;
	}
	return retval;
}


- (void) setDelegate: (id <PGTSConnectionDelegate>) anObject
{
	@synchronized (self)
	{
	    mDelegate = anObject;
	}
}


- (void) reloadDatabaseDescription
{
	BOOL shouldReload = YES;
	@synchronized (self)
	{
		if (! mMetadataContainer)
			shouldReload = NO;
	}
	
	[self databaseDescription];
	if (shouldReload)
		[mMetadataContainer reloadUsingConnection: self];
}


- (PGTSDatabaseDescription *) databaseDescription
{
	@synchronized (self)
	{
		if (! mMetadataContainer)
		{
			NSString* keyFormat = [NSString stringWithFormat: @"//%s@%s:%s/%s",
								   PQuser (mConnection), PQhost (mConnection), PQport (mConnection), PQdb (mConnection)];
			NSURL* metadataKey = [NSURL URLWithString: keyFormat];
			
			mMetadataContainer = [[[PGTSMetadataStorage defaultStorage] metadataContainerForURI: metadataKey] retain];
		}
	}
	[mMetadataContainer prepareForConnection: self];
    return [mMetadataContainer databaseDescription];
}


- (id) deserializationDictionary
{
	@synchronized (self)
	{
		if (! mPGTypes)
		{
			NSBundle* bundle = [NSBundle bundleForClass: [PGTSConnection class]];
			NSString* path = [[bundle resourcePath] stringByAppendingString: @"/datatypeassociations.plist"];
			NSData* plist = [NSData dataWithContentsOfFile: path];
			BXAssertValueReturn (plist, nil, @"datatypeassociations.plist was not found (looked from %@).", path);
			
			NSString* error = nil;
			NSMutableDictionary *PGTypes = [[[NSPropertyListSerialization propertyListFromData: plist 
																			  mutabilityOption: NSPropertyListImmutable
																						format: NULL 
																			  errorDescription: &error] mutableCopy] autorelease];
			BXAssertValueReturn (PGTypes, nil, @"Error creating PGTSDeserializationDictionary: %@ (file: %@)", error, path);
			
			NSArray* keys = [PGTypes allKeys];
			BXEnumerate (key, e, [keys objectEnumerator])
			{
				Class typeClass = NSClassFromString ([PGTypes objectForKey: key]);
				if (Nil == typeClass)
					[PGTypes removeObjectForKey: key];
				else
					[PGTypes setObject: typeClass forKey: key];
			}
			
			mPGTypes = [PGTypes copy];
		}
	}
    return mPGTypes;
}


- (NSString *) errorString
{
	NSString *message = nil;
	@synchronized (self)
	{
		message = [NSString stringWithUTF8String: PQerrorMessage (mConnection)];
	}
	message = PGTSReformatErrorMessage (message);
	return message;
}


- (NSError *) connectionError
{
	// FIXME: thread safety?
	return [mConnector connectionError];
}


- (id <PGTSCertificateVerificationDelegate>) certificateVerificationDelegate
{
	id <PGTSCertificateVerificationDelegate> retval = nil;
	@synchronized (self)
	{
		retval = [[mCertificateVerificationDelegate retain] autorelease];
	}
	return retval;
}


- (void) setCertificateVerificationDelegate: (id <PGTSCertificateVerificationDelegate>) anObject
{
	@synchronized (self)
	{
		mCertificateVerificationDelegate = anObject;
		if (! mCertificateVerificationDelegate)
			mCertificateVerificationDelegate = [PGTSCertificateVerificationDelegate defaultCertificateVerificationDelegate];
	}
}


- (ConnStatusType) connectionStatus
{
	ConnStatusType retval = CONNECTION_OK;
	@synchronized (self)
	{
		retval = PQstatus (mConnection);
	}
	return retval;
}


- (PGTransactionStatusType) transactionStatus
{
	PGTransactionStatusType retval = PQTRANS_IDLE;
	@synchronized (self)
	{
		retval = PQtransactionStatus (mConnection);
	}
	return retval;
}


- (int) backendPID
{
	int retval = 0;
	@synchronized (self)
	{
		retval = PQbackendPID (mConnection);
	}
	return retval;
}


- (int) socket
{
	int retval = 0;
	@synchronized (self)
	{
		retval = PQsocket (mConnection);
	}
	return retval;
}


- (BXSocketDescriptor *) socketDescriptor
{
	id retval = nil;
	@synchronized (self)
	{
		retval = [[mSocketDescriptor retain] autorelease];
	}
	return retval;
}


- (PGresult *) execQuery: (const char *) query
{
	PGresult *res = NULL;

	@synchronized (self)
	{
		Expect (! mSocketDescriptor || [mSocketDescriptor isLocked]);

		if ([self canSend])
		{
			res = PQexec (mConnection, query);
			if (BASETEN_POSTGRESQL_SEND_QUERY_ENABLED ())
			{
				char *query_s = strdup (query);
				BASETEN_POSTGRESQL_SEND_QUERY (self, 1, query_s, NULL);
				free (query_s);
			}
		}
	}
	
	if (res && mLogsQueries)
		[mDelegate PGTSConnection: self sentQueryString: query];
	
	return res;
}


- (id <PGTSConnectionDelegate>) delegate
{
	id <PGTSConnectionDelegate> retval = nil;
	@synchronized (self)
	{
		retval = [[mDelegate retain] autorelease];
	}
	return retval;
}


- (BOOL) logsQueries
{
	BOOL retval = NO;
	@synchronized (self)
	{
		retval = mLogsQueries;
	}
	return retval;
}


- (void) setLogsQueries: (BOOL) flag
{
	@synchronized (self)
	{
		mLogsQueries = flag;
	}
}


- (void) logQueryIfNeeded: (PGTSQuery *) query
{
	if (mLogsQueries)
		[mDelegate PGTSConnection: self sentQuery: query];
}


- (void) logResultIfNeeded: (PGTSResultSet *) res
{
	if (mLogsQueries)
		[mDelegate PGTSConnection: self receivedResultSet: res];
}


- (SSL *) SSLStruct
{
	SSL *retval = NULL;
	@synchronized (self)
	{
		retval = (SSL *) PQgetssl (mConnection);
	}
	return retval;
}


- (BOOL) canSend
{
	//FIXME: rewrite
	return YES;
}


- (BOOL) usedPassword
{
	BOOL retval = NO;
	@synchronized (self)
	{
		retval = (PQconnectionUsedPassword (mConnection) ? YES : NO);
	}
	return retval;
}
@end



@implementation PGTSConnection (PGTSConnectionPrivate)
- (void) _setConnector: (PGTSConnector *) anObject
{
	@synchronized (self)
	{
		if (mConnector != anObject)
		{
			[mConnector cancel];
			[mConnector setDelegate: nil];
			[mConnector release];
			
			mConnector = [anObject retain];
			[mConnector setDelegate: self];
		}
	}
}


- (void) _setSocketDescriptor: (BXSocketDescriptor *) desc
{
	BXSocketDescriptor *oldDesc = nil;
	@synchronized (self)
	{
		oldDesc = mSocketDescriptor;
		
		mSocketDescriptor = [desc retain];
		[mSocketDescriptor setDelegate: self];
		[mSocketDescriptor install];
	}
	
	[oldDesc invalidate];
	[oldDesc setDelegate: nil];
	[oldDesc release];
}


- (void) _processNotifications
{
	NSMutableArray *notifications = nil;
	
	@synchronized (self)
	{
		PGnotify* pgNotification = NULL;
		while ((pgNotification = PQnotifies (mConnection)))
		{
			if (! notifications)
				notifications = [[NSMutableArray alloc] init];
			
			NSString* name = [NSString stringWithUTF8String: pgNotification->relname];
			PGTSNotification* notification = [[PGTSNotification alloc] init];
			[notification setBackendPID: pgNotification->be_pid];
			[notification setNotificationName: name];
			BASETEN_POSTGRESQL_RECEIVED_NOTIFICATION (self, pgNotification->be_pid, pgNotification->relname, pgNotification->extra);		
			PQfreeNotify (pgNotification);
			
			[notifications addObject: notification];
			[notification release];
		}    
	}

	if ([notifications count])
	{
		BXLogInfo (@"Received %lu notifications.", [notifications count]);
		id <PGTSConnectionDelegate> delegate = [self delegate];
		for (PGTSNotification *notification in notifications)
			[delegate PGTSConnection: self gotNotification: notification];
	}
	
	[notifications release];
}


- (void) _sendNextQuery
{
	ExpectV ([mSocketDescriptor isLocked]);

	@synchronized (self)
	{
		if ([mQueue count])
		{
			PGTSQueryDescription* desc = [mQueue objectAtIndex: 0];
			if (nil != desc)
			{
				BXAssertVoidReturn (! [desc sent], @"Expected %@ not to have been sent.", desc);	
				
				[desc sendForConnection: self];
				[self _checkConnectionStatus];
			}
		}
	}
}


- (void) _sendOrEnqueueQuery: (PGTSQueryDescription *) query
{	
	@synchronized (self)
	{
		[mQueue addObject: query];
		if (1 == [mQueue count] && mConnection)
		{
			NSInvocation *invocation = nil;
			[[PGTSInvocationRecorder recordWithTarget: self outInvocation: &invocation] _sendNextQuery];
			[mSocketDescriptor lock: invocation];
		}
	}
}


- (void) _checkConnectionStatus
{
	@synchronized (self)
	{
		if (CONNECTION_BAD == PQstatus (mConnection))
			[mDelegate PGTSConnectionLost: self error: nil]; //FIXME: set the error.
		//FIXME: also indicate that a reset will be sufficient instead of reconnecting.
	}
}


- (PGTSResultSet *) _executeQuery: (NSString *) queryString parameterArray: (NSArray *) parameters
{
	PGTSResultSet *retval = nil;
	@synchronized (self)
	{
		//First empty the query queue.
		{
			PGTSResultSet* res = nil;
			PGTSQueryDescription* desc = nil;
			while (0 < [mQueue count] && (desc = [mQueue objectAtIndex: 0])) 
			{
				res = [desc finishForConnection: self];
				if ([mQueue count]) //Patch by Jianhua Meng 2008-11-12
					[mQueue removeObjectAtIndex: 0];		
			}
		}
		
		// Send the actual query.
		PGTSQueryDescription* desc = [PGTSQueryDescription queryDescriptionFor: queryString 
																	  delegate: nil
																	  callback: NULL 
																parameterArray: parameters
																	  userInfo: nil];
		retval = [desc finishForConnection: self];
	}
	return retval;
}
@end




@implementation PGTSConnection (PGTSConnectorDelegate)
- (void) connector: (PGTSConnector*) connector gotConnection: (PGconn *) connection
{
	mConnection = connection;
	
	//Rather than call PQsendquery etc. multiple times, monitor the socket state.
	PQsetnonblocking (connection, 0); 
	//Use UTF-8.
	PQsetClientEncoding (connection, "UNICODE"); 
	
	BOOL shouldContinue = YES;
	char const * const queries [] = {
		"SET standard_conforming_strings TO true",
		"SET datestyle TO 'ISO, YMD'",
		"SET timezone TO 'UTC'",
		"SET transaction_isolation TO 'read committed'"
	};
	for (int i = 0, count = BXArraySize (queries); i < count; i++)
	{
		PGresult* res = [self execQuery: queries [i]];
		if (PGRES_COMMAND_OK != PQresultStatus (res))
		{
			shouldContinue = NO;
			BXLogError (@"Expected setting run-time parameters for connection to succeed. Error:\n%s",
						PQresultErrorMessage (res) ?: "<no error message>");
			
			PGTSResultSet* result = [[[PGTSResultSet alloc] initWithPGResult: res connection: self] autorelease];
			NSError* error = [result error];
			[mConnector setConnectionError: error];
		}
	}
	
	int const serverVersion = PQserverVersion (connection);
	if (serverVersion < 90000)
	{
		PGresult* res = [self execQuery: "SET regex_flavor TO 'advanced'"];
		if (PGRES_COMMAND_OK != PQresultStatus (res))
		{
			shouldContinue = NO;
			BXLogError (@"Expected setting run-time parameters for connection to succeed. Error:\n%s",
						PQresultErrorMessage (res) ?: "<no error message>");
			
			PGTSResultSet* result = [[[PGTSResultSet alloc] initWithPGResult: res connection: self] autorelease];
			NSError* error = [result error];
			[mConnector setConnectionError: error];
		}
	}

	if (shouldContinue)
	{
		PQsetNoticeReceiver (connection, &NoticeReceiver, (void *) self);
		
		BXSocketDescriptor *desc = [BXSocketDescriptor copyDescriptorWithSocket: PQsocket (mConnection)];
		[self _setSocketDescriptor: desc];
		[desc release];
		
		[[BXConnectionMonitor sharedInstance] clientDidConnect: self];
		
		if (0 < [mQueue count])
		{
			NSInvocation *invocation = nil;
			[[PGTSInvocationRecorder recordWithTarget: self outInvocation: &invocation] _sendNextQuery];
			[mSocketDescriptor lock: invocation];
		}
		
		[mDelegate PGTSConnectionEstablished: self];
		[self _setConnector: nil];
	}
	else
	{
		[[BXConnectionMonitor sharedInstance] clientDidFailConnectionAttempt: self];
        [mDelegate PGTSConnectionFailed: self];
	}
}


- (void) connectorFailed: (PGTSConnector*) connector
{
	[[BXConnectionMonitor sharedInstance] clientDidFailConnectionAttempt: self];
	[mDelegate PGTSConnectionFailed: self];
	//Retain the connector for error handling.
}


- (BOOL) allowSSLForConnector: (PGTSConnector *) connector context: (void *) x509_ctx preverifyStatus: (int) preverifyStatus
{
	return [mCertificateVerificationDelegate PGTSAllowSSLForConnection: self context: x509_ctx preverifyStatus: preverifyStatus];
}
@end



@implementation PGTSConnection (BXSocketDescriptorDelegate)
- (void) socketDescriptor: (BXSocketDescriptor *) desc readyForReading: (int) fd estimatedSize: (unsigned long) size
{
	@synchronized (self)
	{
		ExpectV ([desc isLocked]);

		//When the socket is ready for read, send any available notifications and read results until 
		//the socket blocks. If all results for the current query have been read, send the next query.
		PQconsumeInput (mConnection);
		
		[self _processNotifications];
		
		if (0 < [mQueue count])
		{
			PGTSQueryDescription* queryDescription = [[[mQueue objectAtIndex: 0] retain] autorelease];
			while (! PQisBusy (mConnection))
			{
				[queryDescription receiveForConnection: self];
				if ([queryDescription finished])
					break;
			}
			
			if ([queryDescription finished])
			{
				NSUInteger count = [mQueue count];
				if (count)
				{
					if ([mQueue objectAtIndex: 0] == queryDescription)
					{
						[mQueue removeObjectAtIndex: 0];
						count--;
					}
					
					if (count)
						[self _sendNextQuery];
				}            
			}
		}
	}
}


- (void) socketDescriptor: (BXSocketDescriptor *) desc lockedSocket: (int) fd userInfo: (id) userInfo
{
	ExpectV ([userInfo isKindOfClass: [NSInvocation class]]);
	[userInfo invoke];
}
@end



@implementation PGTSConnection (Queries)
#define StdargToNSArray( ARRAY_VAR, COUNT, LAST ) \
    { va_list ap; va_start (ap, LAST); ARRAY_VAR = StdargToNSArray2 (ap, COUNT, LAST); va_end (ap); }


static NSArray*
StdargToNSArray2 (va_list arguments, int argCount, id lastArg)
{
    NSMutableArray* retval = [NSMutableArray arrayWithCapacity: argCount];
	if (0 < argCount)
	{
		[retval addObject: lastArg ?: [NSNull null]];

	    for (int i = 1; i < argCount; i++)
    	{
        	id argument = va_arg (arguments, id);
	        [retval addObject: argument ?: [NSNull null]];
    	}
	}
    return retval;
}


/**
 * \internal
 * \brief The number of parameters in a string.
 *
 * Parameters are marked as follows: $n. The number of parameters is equal to the highest value of n.
 */
static int
ParameterCount (NSString* query)
{
    NSScanner* scanner = [NSScanner scannerWithString: query];
    int paramCount = 0;
    while (NO == [scanner isAtEnd])
    {
        int foundCount = 0;
        [scanner scanUpToString: @"$" intoString: NULL];
        [scanner scanString: @"$" intoString: NULL];
        //The largest found number specifies the number of parameters
        if ([scanner scanInt: &foundCount])
            paramCount = MAX (foundCount, paramCount);
    }
    return paramCount;
}


- (PGTSResultSet *) executeQuery: (NSString *) queryString
{
	return [self executeQuery: queryString parameterArray: nil];
}


- (PGTSResultSet *) executeQuery: (NSString *) queryString parameters: (id) p1, ...
{
	NSArray* parameters = nil;
	StdargToNSArray (parameters, ParameterCount (queryString), p1);
	return [self executeQuery: queryString parameterArray: parameters];
}


- (PGTSResultSet *) executeQuery: (NSString *) queryString parameterArray: (NSArray *) parameters
{
	NSInvocation *invocation = nil;
	PGTSResultSet *retval = nil;
	
	[[PGTSInvocationRecorder recordWithTarget: self outInvocation: &invocation] 
	 _executeQuery: queryString parameterArray: parameters];
	
	// Remember not to call -lockAndWait: while @synchronized. Otherwise we'll deadlock.
	[mSocketDescriptor lockAndWait: invocation];
	[invocation getReturnValue: &retval];
	
	return retval;
}


- (int) sendQuery: (NSString *) queryString delegate: (id) delegate callback: (SEL) callback
{
	return [self sendQuery: queryString delegate: delegate callback: callback parameterArray: nil];
}


- (int) sendQuery: (NSString *) queryString delegate: (id) delegate callback: (SEL) callback
	   parameters: (id) p1, ...
{
	NSArray* parameters = nil;
	StdargToNSArray (parameters, ParameterCount (queryString), p1);
	return [self sendQuery: queryString delegate: delegate callback: callback parameterArray: parameters];
}


- (int) sendQuery: (NSString *) queryString delegate: (id) delegate callback: (SEL) callback 
   parameterArray: (NSArray *) parameters
{
	return [self sendQuery: queryString delegate: delegate callback: callback 
			parameterArray: parameters userInfo: nil];
}


- (int) sendQuery: (NSString *) queryString delegate: (id) delegate callback: (SEL) callback 
   parameterArray: (NSArray *) parameters userInfo: (id) userInfo
{
	PGTSQueryDescription* desc = [PGTSQueryDescription queryDescriptionFor: queryString 
																  delegate: delegate 
																  callback: callback
															parameterArray: parameters
																  userInfo: userInfo];
	int retval = [desc identifier];
	[self _sendOrEnqueueQuery: desc];
	return retval;
}
@end



@implementation PGTSConnection (BXConnectionMonitorClient)
- (int) socketForConnectionMonitor: (BXConnectionMonitor *) monitor
{
	return [self socket];
}


- (void) connectionMonitorProcessWillExit: (BXConnectionMonitor *) monitor
{
    [self disconnect];
}


- (void) connectionMonitorSystemWillSleep: (BXConnectionMonitor *) monitor
{
 	[self disconnect];
	mDidDisconnectOnSleep = YES;
}


- (void) connectionMonitorSystemDidWake: (BXConnectionMonitor *) monitor
{
	if (mDidDisconnectOnSleep)
	{
		mDidDisconnectOnSleep = NO;
		[mDelegate PGTSConnectionLost: self error: nil]; //FIXME: set the error.
	}
}


- (void) connectionMonitor: (BXConnectionMonitor *) monitor
	  networkStatusChanged: (SCNetworkConnectionFlags) flags
{
	[mDelegate PGTSConnection: self networkStatusChanged: flags];
}
@end