Source

baseten / Framework / Sources / PGTSAdditions.m

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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//
// PGTSAdditions.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 <stdlib.h>
#import <limits.h>
#import <PGTS/postgresql/libpq-fe.h> 
#import "PGTSAdditions.h"
#import "PGTSConnection.h"
#import "PGTSConstants.h"
#import "PGTSFunctions.h"
#import "PGTSTypeInfo.h"
#import "PGTSFieldInfo.h"
#import "PGTSDatabaseInfo.h"
#import "PGTSACLItem.h"
#import <Log4Cocoa/Log4Cocoa.h>


//A workaround for libpq versions earlier than 8.0.8 and 8.1.4
//#define PQescapeStringConn( conn, to, from, length, error ) PQescapeString( to, from, length )



//Same as with strtoull
long long
strtoll (const char * restrict nptr, char ** restrict endptr, int base);

//This really might not exist in 10.2.8
float
strtof (const char * restrict nptr, char ** restrict endptr);


@interface NSDictionary (PGTSAdditionsPrivate)
- (NSArray *) PGTSParameters1: (NSMutableArray *) parameters connection: (PGTSConnection *) connection qualified: (BOOL) qualified;
@end


@implementation NSObject (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    return nil;
}

- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
	if (NULL != length)
		*length = 0;
	return NULL;
}

- (NSString *) PGTSEscapedObjectParameter: (PGTSConnection *) connection
{
	NSString* rval = nil;
	int length = 0;
	char* charParameter = [self PGTSParameterLength: &length connection: connection];
	if (NULL != charParameter)
	{
		PGconn* pgConn = [connection pgConnection];
		char* escapedParameter = calloc (1 + 2 * length, sizeof (char));
		PQescapeStringConn (pgConn, escapedParameter, charParameter, length, NULL);
		const char* clientEncoding = PQparameterStatus (pgConn, "client_encoding");
		NSCAssert1 (0 == strcmp ("UNICODE", clientEncoding), @"Expected client_encoding to be UNICODE (was: %s).", clientEncoding);
		rval = [[[NSString alloc] initWithBytesNoCopy: escapedParameter length: strlen (escapedParameter)
											 encoding: NSUTF8StringEncoding freeWhenDone: YES] autorelease];
	}
	return rval;
}

- (NSString *) PGTSEscapedName: (PGTSConnection *) connection
{
	return [NSString stringWithFormat: @"\"%@\"", [[self description] PGTSEscapedString: connection]];
}

- (NSString *) PGTSQualifiedName: (PGTSConnection *) connection
{
	return [self PGTSEscapedName: connection];
}
@end


@implementation NSDictionary (PGTSAdditions)
/**
 * Read the bundled deserialization dictionary if needed.
 */
+ (id) PGTSDeserializationDictionary
{
    static BOOL initialized = NO;
    static NSMutableDictionary* dict = nil;
    if (NO == initialized)
    {
        NSString* path = [[[NSBundle bundleForClass: [PGTSConnection class]] resourcePath] 
            stringByAppendingString: @"/datatypeassociations.plist"];
        NSData* plist = [NSData dataWithContentsOfFile: path];
        log4AssertValueReturn (nil != plist, nil, @"datatypeassociations.plist was not found (looked from %@).", path);
        
        NSString* error = nil;
        dict = [[NSPropertyListSerialization propertyListFromData: plist mutabilityOption: NSPropertyListMutableContainers 
                                                           format: NULL errorDescription: &error] retain];
        log4AssertValueReturn (nil != dict, nil, @"Error creating PGTSDeserializationDictionary: %@ (file: %@)", error, path);
            
        NSArray* keys = [dict allKeys];
        TSEnumerate (key, e, [keys objectEnumerator])
        {
            Class class = NSClassFromString ([dict objectForKey: key]);
            if (Nil == class)
                [dict removeObjectForKey: key];
            else
                [dict setObject: class forKey: key];
        }

        initialized = YES;
    }
    return dict;
}

/**
 * Use the keys and values to form a connection string.
 */
- (NSString *) PGTSConnectionString
{
	NSMutableString* connectionString = [NSMutableString string];
	NSEnumerator* e = [self keyEnumerator];
	NSString* currentKey;
	NSString* format = @"%@ = '%@' ";
	while ((currentKey = [e nextObject]))
        if ([kPGTSConnectionDictionaryKeys containsObject: currentKey])
            [connectionString appendFormat: format, currentKey, [self objectForKey: currentKey]];
	return connectionString;
}

/**
 * Sort the fields by table.
 * \return An NSDictionary with PGTSTableInfo objects as keys. The values are also NSDictionaries
 *         which have PGTSFieldInfo objects as keys and their values as objects.
 */
- (NSDictionary *) PGTSFieldsSortedByTable
{
    NSMutableDictionary* tables = [NSMutableDictionary dictionary];
    TSEnumerate (field, e, [self keyEnumerator])
    {
        PGTSTableInfo* table = [field table];
        NSMutableDictionary* fields = [tables objectForKey: table];
        if (nil == fields)
        {
            fields = [NSMutableDictionary dictionary];
            [tables setObject: fields forKey: table];
        }
        [fields setObject: [self objectForKey: field] forKey: field];
    }
    return tables;
}

/**
 * Use the keys and values to form a SET clause and append the values to an array.
 * \param parameters the value array
 */
- (NSString *) PGTSSetClauseParameters: (NSMutableArray *) parameters connection: (PGTSConnection *) connection;
{
    return [[self PGTSParameters1: parameters connection: connection qualified: NO] componentsJoinedByString: @", "];
}


/**
 * Use the keys and values to form a WHERE clause and append the values to an array.
 * \param parameters the value array
 */
- (NSString *) PGTSWhereClauseParameters: (NSMutableArray *) parameters connection: (PGTSConnection *) connection;
{
    return [[self PGTSParameters1: parameters connection: connection qualified: YES] componentsJoinedByString: @" AND "];
}

@end


@implementation NSMutableDictionary (PGTSAdditions)
- (void) PGTSSetRow: (int) row resultSet: (PGTSResultSet *) res
{
    [res setValuesFromRow: row target: self nullPlaceholder: [NSNull null]];
}
@end


@implementation NSDictionary (PGTSAdditionsPrivate)
/**
 * Make a key-value-pair of each item in the dictionary.
 * Keys and values are presented as follows: "key" = $n, where n ranges from 1 to number of items
 */
- (NSArray *) PGTSParameters1: (NSMutableArray *) parameters connection: (PGTSConnection *) connection qualified: (BOOL) qualified
{
    NSMutableArray* fields = [NSMutableArray arrayWithCapacity: [self count]];
    //Postgres's indexing is one-based
    unsigned int i = [parameters count] + 1;
    TSEnumerate (field, e, [self keyEnumerator])
    {
        [parameters addObject: [self objectForKey: field]];
		NSString* name = nil;
		if (qualified)
			name = [field PGTSQualifiedName: connection];
		else
			name = [field PGTSEscapedName: connection];
        [fields addObject: [NSString stringWithFormat: @"%@ = $%u", name, i]];
        i++;
    }
    return fields;
}
@end


@implementation NSNotificationCenter (PGTSAdditions)
/**
 * Return the shared notification center that delivers notifications from the database.
 */
+ (NSNotificationCenter *) PGTSNotificationCenter
{
    static id sharedInstance = nil;
    if (!sharedInstance)
        sharedInstance = [[[self class] alloc] init];
    return sharedInstance;
}
@end


@implementation NSString (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    return [NSString stringWithUTF8String: value];
}

- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
    if (nil == connection)
        log4Warn (@"Connection pointer was nil.");
    else
    {
        const char* clientEncoding = PQparameterStatus ([connection pgConnection], "client_encoding");
        NSCAssert1 (0 == strcmp ("UNICODE", clientEncoding), @"Expected client_encoding to be UNICODE (was: %s).", clientEncoding);
    }
    const char* rval = [self UTF8String];
    if (NULL != length)
        *length = strlen (rval);
    return (char *) rval;
}

+ (NSString *) PGTSFieldAliases: (unsigned int) count
{
    return [self PGTSFieldAliases: count start: 1];
}

+ (NSString *) PGTSFieldAliases: (unsigned int) count start: (unsigned int) start
{
    NSString* rval = nil;
    if (0 >= count)
        rval = @"";
    else
    {
        rval = [NSMutableString stringWithCapacity: 3 * (count % 10) + 4 * ((count / 10) % 10)];
        for (unsigned int i = start; i <= count; i++)
            [(NSMutableString *) rval appendFormat: @"$%u,", i];
        [(NSMutableString *) rval deleteCharactersInRange: NSMakeRange ([rval length] - 1, 1)];
    }
    return rval;
}

/**
 * Escape the string for the SQL interpreter.
 */
- (NSString *) PGTSEscapedString: (PGTSConnection *) connection
{
    const char* from = [self UTF8String];
    size_t length = strlen (from);
    char* to = calloc (1 + 2 * length, sizeof (char));
    PQescapeStringConn ([connection pgConnection], to, from, length, NULL);
    NSString* rval = [NSString stringWithUTF8String: to];
    free (to);
    return rval;
}

/**
 * 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.
 */
- (int) PGTSParameterCount
{
    NSScanner* scanner = [NSScanner scannerWithString: self];
    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;
}

//FIXME: do we really need to escape field names?
- (NSString *) PGTSQuotedString
{
    return [NSString stringWithFormat: @"\"%@\"", self];
}

@end


@implementation NSData (PGTSAdditions)
//TODO: -PGTSParameterLength:
//Should we use htonl?
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
	size_t resultLength = 0;
	unsigned char *unescaped = PQunescapeBytea ((unsigned char*) value, &resultLength);
	
	if (NULL == unescaped)
	{
		log4Error (@"PQunescapeBytea failed for characters: %s", value); //FIXME: Handle error?
		return nil;
	}
	
    NSData *data = [[self class] dataWithBytes: unescaped length: resultLength];
	PQfreemem (unescaped);
	return data;
}

- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
    const char* rval = [self bytes];
    if (NULL != length)
        *length = [self length];
    return (char *) rval;
}

@end


@interface NSArray (PGTSPrivateAdditions)
- (NSString *) PGTSParameter2: (PGTSConnection *) connection;
@end

@implementation NSArray (PGTSAdditions)
static inline size_t
UnescapePGArray (char* dst, const char* const src_, size_t length)
{
    const char* const end = src_ + length;
    const char* src = src_;
    char c = '\0';
    while (src < end)
    {
        c = *src;
        switch (c)
        {
            case '\\':
                src++;
                c = *src;
                length--;
                //Fall through.
            default:
                *dst = c;
                src++;
                dst++;
        }
    }
    return length;
}

+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) current typeInfo: (PGTSTypeInfo *) typeInfo
{
    id retval = [NSMutableArray array];
    //Used with typeInfo: argument later
    PGTSTypeInfo* elementType = [[typeInfo database] typeInfoForTypeWithOid: [typeInfo elementOid]];
    if (nil != elementType)
    {
        NSDictionary* deserializationDictionary = [[elementType connection] deserializationDictionary];
        if (nil == deserializationDictionary)
            deserializationDictionary = [NSDictionary PGTSDeserializationDictionary];
        Class elementClass = [deserializationDictionary objectForKey: [elementType name]];
        if (Nil == elementClass)
            elementClass = [NSData class];
        
        //First check if the array starts with a range decoration. 
        //We don't do anything with them, at least yet, so we skip it.
        if ('[' == *current)
        {
            while ('\0' != current)
            {
                current++;
                if (']' == *current && '=' == *(current + 1))
                {
                    current += 2;
                    break;
                }
            }
        }
        
        //Check if the array is enclosed in curly braces. If this is the case, remove them.
        //Arrays should always have this decoration but possibly (?) sometimes don't.
        char* endings = NULL;
        asprintf (&endings, "%c\0\0", [elementType delimiter]);
        if ('{' == *current)
        {
            current++;
            endings [1] = '}';
        }
        
        const char* element = NULL;
        const char* escaped = NULL;
        while (1)
        {
            //Mark the element beginning.
            if (NULL == element)
                element = current;
            
            //Remember the last escape character.
            if ('\\' == *current && current - 1 != escaped)
                escaped = current;
                        
            if (strchr (endings, *current) && current != escaped)
            {
                const char* end = current;
                //Check for "value" -style element.
                if ('"' == *element)
                {
                    end--;
                    //Check for escaped quote before delimiter: "value1\","
                    //Also check for ending-in-element: "}"
                    if (element == end || end - 1 == escaped || '"' != *end)
                        goto continue_iteration;
                    
                    element++;
                }
                
                //Since we really are at the end of an element, create an object.
                id object = nil;
                if (element >= end)
                    object = [NSNull null];
                else
                {
                    //Make a copy and remove double-escapes.
                    //FIXME: hopefully malloc copes with requests for more than 0xffff bytes.
                    size_t last = end - element;
                    char* elementData = malloc (1 + last);
                    last = UnescapePGArray (elementData, element, last);

                    //Add a terminating NUL so we get a C-string.
                    elementData [last] = '\0';

                    //Create the object.
                    object = [elementClass newForPGTSResultSet: set withCharacters: elementData typeInfo: elementType];
                    free (elementData);
                }
                [retval addObject: object];
                
                element = NULL;
                escaped = NULL;
                //Are we at the end?
                if (*current != endings [0])
                    break;
            }
            
continue_iteration:
            current++;
        }
        free (endings);
    }
    return retval;
}

- (NSString *) PGTSFieldnames: (PGTSConnection *) connection
{
    NSMutableArray* names = [NSMutableArray arrayWithCapacity: [self count]];
    TSEnumerate (currentName, e, [self objectEnumerator])
    {
        [names addObject: [NSString stringWithFormat: @"\"%@\"", [currentName PGTSEscapedString: connection]]];
    }
    return [names componentsJoinedByString: @","];
}

- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
    return [[self PGTSParameter2: connection] PGTSParameterLength: length connection: connection];
}

- (NSString *) PGTSParameter2: (PGTSConnection *) connection
{
    //PostgreSQL array (hopefully) cannot contain other kinds of elements,
    //which is good, since the input syntax is not easy to produce using recursion
    NSString* rval = nil;
    if (0 == [self count])
        rval = @"{}";
    else if ([[self objectAtIndex: 0] isKindOfClass: [NSArray class]])
        rval = [[self valueForKey: @"PGTSParameter2"] componentsJoinedByString: @", "];
    else
    {
        NSMutableArray* components = [NSMutableArray arrayWithCapacity: [self count]];
        TSEnumerate (currentObject, e, [self objectEnumerator])
        {
            int length = 0;
            char* parameter = [currentObject PGTSParameterLength: &length connection: connection];
            char* escapedParameter = calloc (2 * length + 1, sizeof (char));
            PQescapeStringConn ([connection pgConnection], escapedParameter, parameter, length, NULL);
            [components addObject: [NSString stringWithUTF8String: escapedParameter]];
        }
        rval = [NSString stringWithFormat: @"{\"%@\"}", [components componentsJoinedByString: @"\", \""]];
    }
    return rval;
}
@end


@implementation NSDate (PGTSAdditions)
- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
    NSMutableString* rval = [NSMutableString stringWithString: 
        [self descriptionWithCalendarFormat: @"%Y-%m-%d %H:%M:%S"
                                   timeZone: [NSTimeZone localTimeZone]
                                     locale: nil]];
    double integralPart = 0.0;
    double subseconds = modf ([self timeIntervalSinceReferenceDate], &integralPart);
    
    char* fractionalPart = NULL;
    asprintf (&fractionalPart, "%-.6f", fabs (subseconds));
    [rval appendFormat: @"%s", &fractionalPart [1]];
    free (fractionalPart);
    
    return [rval PGTSParameterLength: length connection: connection];
}

+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
	log4Debug (@"Given value: %s", value);
	
	size_t length = strlen (value) + 1;
    char* datetime = alloca (length);
	strlcpy (datetime, value, length);
	
    double interval = 0.0;
	char* subseconds = NULL;
	
    if ('.' == datetime [19])
    {
        datetime [19] = '\0';
        length = strlen (&datetime [20]) + 1;
        subseconds = alloca (2 + length);
        strlcpy (&subseconds [2], &datetime [20], length);
        subseconds [0] = '0';
        subseconds [1] = '.';
        interval = strtod (subseconds, NULL);
    }
    
    NSMutableString* dateString = [NSString stringWithUTF8String: datetime];
    id rval = [NSCalendarDate dateWithString: dateString
                              calendarFormat: @"%Y-%m-%d %H:%M:%S"];
    rval = [NSDate dateWithTimeIntervalSinceReferenceDate: [rval timeIntervalSinceReferenceDate] + interval];
    log4AssertLog (nil != rval, @"Failed to match string to date format");
#ifndef L4_BLOCK_ASSERTIONS
	double integralPart = 0.0;
	log4AssertLog (NULL == subseconds || 0.0 < modf ([rval timeIntervalSince1970], &integralPart),
				   @"Expected date to have a fractional part (timestamp: %f, subseconds: %s)",
				   [rval timeIntervalSince1970], subseconds);
#endif
    return rval;
}
@end


@implementation NSCalendarDate (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    id rval = nil;
	size_t length = strlen (value);
    if (10 == length)
    {
        NSString* dateString = [NSString stringWithUTF8String: value];
        rval = [[self class] dateWithString: dateString calendarFormat: @"%Y-%m-%d"];
    }
    else
    {
        BOOL shouldContinue = YES;
        char tzmarker = '\0';
        char* timezone = NULL;
        char* subseconds = NULL;
		length++;
		char* datetime = alloca (length);
		strlcpy (datetime, value, length);
        
        switch (datetime [19])
        {
            case '+':
            case '-':
                tzmarker = datetime [19];
                timezone = &datetime [20];
                break;
            case '.':
            {
                subseconds = &datetime [20];
                
                unsigned int i = 0;
                while (isdigit (subseconds [i]))
                    i++;
                
                tzmarker = subseconds [i];
                subseconds [i] = '\0';
                timezone = &subseconds [i + 1];
                break;
            }
            default:
                shouldContinue = NO;
                break;
        }
        datetime [19] = '\0';
        
        if (YES == shouldContinue)
        {
            NSString* dateString = [NSString stringWithUTF8String: datetime];
            NSCalendarDate* date = [[self class] dateWithString: dateString
                                                 calendarFormat: @"%Y-%m-%d %H:%M:%S"];
            
            double interval = 0.0;
            if (NULL != subseconds)
            {
                size_t length = strlen (subseconds) + 1;
                char* subseconds2 = alloca (2 + length);
                strlcpy (&subseconds2 [2], subseconds, length);
                subseconds2 [0] = '0';
                subseconds2 [1] = '.';
                interval = strtod (subseconds2, NULL);
                date = [date addTimeInterval: interval];
            }
            
            if (NULL != timezone)
            {
                int secondsFromGMT = 0;
                char* minutes = NULL;
                if (':' == timezone [2])
                {
                    timezone [2] = '\0';
                    minutes = &timezone [3];
                    secondsFromGMT += 60 * strtol (minutes, NULL, 10);
                }                
                secondsFromGMT += 60 * 60 * strtol (timezone, NULL, 10);
                
                if ('-' == tzmarker)
                    secondsFromGMT *= -1;
                
                [date setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: secondsFromGMT]];
            }
            
            rval = date;
        }
    }
    
    log4AssertLog (nil != rval, @"Failed matching string %s to date format.", value);
    return rval;
}

- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
    NSMutableString* rval = [NSMutableString stringWithString: [self descriptionWithCalendarFormat: @"%Y-%m-%d %H:%M:%S"]];
    double integralPart = 0.0;
    double subseconds = modf ([self timeIntervalSinceReferenceDate], &integralPart);
    
    char* fractionalPart = NULL;
    asprintf (&fractionalPart, "%-.6f", fabs (subseconds));
    [rval appendFormat: @"%s", &fractionalPart [1]];
    free (fractionalPart);
    
    int seconds = [[self timeZone] secondsFromGMT];
    [rval appendFormat: @"%+.2d:%.2d", seconds / (60 * 60), abs ((seconds % (60 * 60)) / 60)];
    return [rval PGTSParameterLength: length connection: connection];
}
@end


@implementation NSDecimalNumber (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    NSDecimal decimal;
    NSString* stringValue = [NSString stringWithUTF8String: value];
    NSScanner* scanner = [NSScanner scannerWithString: stringValue];
    [scanner scanDecimal: &decimal];
    return [NSDecimalNumber decimalNumberWithDecimal: decimal];
}
@end


@implementation NSNumber (PGTSAdditions)
- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
    return [[self description] PGTSParameterLength: length connection: connection];
}

+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    return [NSNumber numberWithLongLong: strtoll (value, NULL, 10)];
}

/**
 * Return the value as Oid.
 * \sa PGTSOidAsObject
 */
- (Oid) PGTSOidValue
{
    return [self unsignedIntValue];
}

- (id) PGTSConstantExpressionValue: (NSDictionary *) context
{
	id retval = self;
	if (0 == strcmp ("c", [self objCType]))
		retval = ([self boolValue] ? @"true" : @"false");
    return retval;
}
@end

@implementation PGTSAbstractClass
- (id) init
{
    NSString* reason = [NSString stringWithFormat: @"%@ is an abstract class", [self class]];
    [[NSException exceptionWithName: NSGenericException 
                             reason: reason
                           userInfo: nil] raise];
    return nil;
}
@end

@implementation PGTSFloat
@end

@implementation PGTSFloat (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    return [NSNumber numberWithFloat: strtof (value, NULL)];
}
@end

@implementation PGTSDouble
@end

@implementation PGTSDouble (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    return [NSNumber numberWithDouble: strtod (value, NULL)];
}
@end

@implementation PGTSBool
@end

@implementation PGTSBool (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    BOOL boolValue = (value [0] == 't' ? YES : NO);
    return [NSNumber numberWithBool: boolValue];
}
@end

@implementation PGTSPoint
@end

@implementation PGTSPoint (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    NSPoint retval = NSZeroPoint;
    NSString* pointString = [NSString stringWithUTF8String: value];
    NSScanner* pointScanner = [NSScanner scannerWithString: pointString];
    [pointScanner setScanLocation: 1];
	
#if CGFLOAT_IS_DOUBLE
    [pointScanner scanDouble: &(retval.x)];
#else
    [pointScanner scanFloat: &(retval.x)];
#endif
	
    [pointScanner setScanLocation: [pointScanner scanLocation] + 1];
	
#if CGFLOAT_IS_DOUBLE
    [pointScanner scanDouble: &(retval.y)];
#else
    [pointScanner scanFloat: &(retval.y)];
#endif
	
    return [NSValue valueWithPoint: retval];
}
@end

@implementation PGTSSize
@end

@implementation PGTSSize (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{
    NSPoint p = NSZeroPoint;
    [[PGTSPoint newForPGTSResultSet: set withCharacters: value typeInfo: typeInfo] getValue: &p];
    NSSize s;
    s.width = p.x;
    s.height = p.y;
    return [NSValue valueWithSize: s];
}
@end

@implementation PGTSACLItem (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) res withCharacters: (const char *) value typeInfo: (PGTSTypeInfo *) typeInfo
{        
    //Role and privileges are separated by an equals sign
    id rval = nil;
	size_t length = strlen (value) + 1;
    char* grantingRole = alloca (length);
	strlcpy (grantingRole, value, length);
    char* role = strsep (&grantingRole, "=");
    char* privileges = strsep (&grantingRole, "/");
    
    //Zero-length but not NULL
    log4AssertValueReturn (NULL != privileges && NULL != role && NULL != grantingRole, nil, @"Unable to parse privileges (%s).", value);
    
    //Role is zero-length if the privileges are for PUBLIC
    rval = [[[PGTSACLItem alloc] init] autorelease];
    if (0 != strlen (role))
    {
        PGTSDatabaseInfo* database = [[res connection] databaseInfo];
        
        //Remove "group " from beginning
        if (role == strstr (role, "group "))
            role = &role [6]; //6 == strlen ("group ");
        if (grantingRole == strstr (role, "group "))
            grantingRole = &grantingRole [6];
        
        [rval setRole: [database roleNamed: [NSString stringWithUTF8String: role]]];
        [rval setGrantingRole: [database roleNamed: [NSString stringWithUTF8String: grantingRole]]];
    }
    
    //Parse the privileges
    enum PGTSACLItemPrivilege userPrivileges = kPGTSPrivilegeNone;
    enum PGTSACLItemPrivilege grantOption = kPGTSPrivilegeNone;
    for (unsigned int i = 0, length = strlen (privileges); i < length; i++)
    {
        switch (privileges [i])
        {
            case 'r': //SELECT
                userPrivileges |= kPGTSPrivilegeSelect;
                grantOption = kPGTSPrivilegeSelectGrant;
                break;
            case 'w': //UPDATE
                userPrivileges |= kPGTSPrivilegeUpdate;
                grantOption = kPGTSPrivilegeUpdateGrant;
                break;
            case 'a': //INSERT
                userPrivileges |= kPGTSPrivilegeInsert;
                grantOption = kPGTSPrivilegeInsertGrant;
                break;
            case 'd': //DELETE
                userPrivileges |= kPGTSPrivilegeDelete;
                grantOption = kPGTSPrivilegeDeleteGrant;
                break;
            case 'x': //REFERENCES
                userPrivileges |= kPGTSPrivilegeReferences;
                grantOption = kPGTSPrivilegeReferencesGrant;
                break;
            case 't': //TRIGGER
                userPrivileges |= kPGTSPrivilegeTrigger;
                grantOption = kPGTSPrivilegeTriggerGrant;
                break;
            case 'X': //EXECUTE
                userPrivileges |= kPGTSPrivilegeExecute;
                grantOption = kPGTSPrivilegeExecuteGrant;
                break;
            case 'U': //USAGE
                userPrivileges |= kPGTSPrivilegeUsage;
                grantOption = kPGTSPrivilegeUsageGrant;
                break;
            case 'C': //CREATE
                userPrivileges |= kPGTSPrivilegeCreate;
                grantOption = kPGTSPrivilegeCreateGrant;
                break;
            case 'c': //CONNECT
                userPrivileges |= kPGTSPrivilegeConnect;
                grantOption = kPGTSPrivilegeConnectGrant;
                break;
            case 'T': //TEMPORARY
                userPrivileges |= kPGTSPrivilegeTemporary;
                grantOption = kPGTSPrivilegeTemporaryGrant;
                break;
            case '*': //Grant option
                userPrivileges |= grantOption;
                grantOption = kPGTSPrivilegeNone;
                break;
            default:
                break;
        }
    }
    [rval setPrivileges: userPrivileges];
    
    return rval;    
}
@end


@implementation NSURL (PGTSAdditions)
#define SetIf( VALUE, KEY ) if ((VALUE)) [connectionDict setObject: VALUE forKey: KEY];
- (NSMutableDictionary *) PGTSConnectionDictionary
{
	NSMutableDictionary* connectionDict = nil;
	if (0 == [@"pgsql" caseInsensitiveCompare: [self scheme]])
	{
		connectionDict = [NSMutableDictionary dictionary];    
		
		NSString* relativePath = [self relativePath];
		if (1 <= [relativePath length])
			SetIf ([relativePath substringFromIndex: 1], kPGTSDatabaseNameKey);
		
		SetIf ([self host], kPGTSHostKey);
		SetIf ([self user], kPGTSUserNameKey);
		SetIf ([self password], kPGTSPasswordKey);
		SetIf ([self port], kPGTSPortKey);
	}
	return connectionDict;
}
@end