Source

baseten / Sources / PGTSFoundationObjects.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
//
// PGTSFoundationObjects.m
// 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 <BaseTen/postgresql/libpq-fe.h>
#import "PGTSFoundationObjects.h"
#import "PGTSConnection.h"
#import "PGTSConnectionPrivate.h"
#import "PGTSTypeDescription.h"
#import "PGTSDatabaseDescription.h"
#import "PGTSAdditions.h"
#import "PGTSResultSet.h"
#import "BXLogger.h"
#import "BXEnumerate.h"


@implementation NSObject (PGTSFoundationObjects)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) typeInfo
{
    BXLogWarning (@"Returning a nil from NSObject's implementation.");
    return nil;
}

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

- (BOOL) PGTSIsBinaryParameter
{
    return NO;
}

- (BOOL) PGTSIsCollection
{
	return NO;
}

- (id) PGTSExpressionOfType: (NSAttributeType) attrType
{
	return nil;
}
@end


@implementation NSExpression (PGTSFoundationObjects)
- (BOOL) PGTSIsCollection
{
	BOOL retval = NO;
	if ([self expressionType] == NSConstantValueExpressionType)
		retval = [[self constantValue] PGTSIsCollection];
	return retval;
}
@end


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

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

- (id) PGTSExpressionOfType: (NSAttributeType) attrType
{
	NSMutableString* retval = [NSMutableString stringWithString: self];
	[retval replaceOccurrencesOfString: @"'" withString: @"\\'" options: 0 range: NSMakeRange (0, [retval length])];
	[retval insertString: @"'" atIndex: 0];
	[retval appendString: @"'"];
	return retval;
}
@end


@implementation NSData (PGTSFoundationObjects)
//FIXME: Should we use htonl?
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) typeInfo
{
	size_t resultLength = 0;
	unsigned char *unescaped = PQunescapeBytea ((unsigned char*) value, &resultLength);
	
	//FIXME: Handle the error?
	BXAssertValueReturn (unescaped, nil, @"PQunescapeBytea failed for characters: %s", value);
	
    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;
}

- (BOOL) PGTSIsBinaryParameter
{
    return YES;
}
@end


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


@implementation NSArray (PGTSFoundationObjects)
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 type: (PGTSTypeDescription *) typeInfo
{
    id retval = [NSMutableArray array];
    //Used with type: argument later
	PGTSConnection* connection = [set connection];
    PGTSTypeDescription* elementType = [[connection databaseDescription] typeWithOid: [typeInfo elementOid]];
    if (nil != elementType)
    {
        NSDictionary* deserializationDictionary = [connection deserializationDictionary];
        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 type: 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;
}

static inline void
AppendBytes (IMP impl, NSMutableData* target, const void* bytes, unsigned int length)
{
    (void (*)(id, SEL, const void*, unsigned int)) impl (target, @selector (appendBytes:length:), bytes, length);
}

static inline void
EscapeAndAppendByte (IMP appendImpl, NSMutableData* target, const char* src)
{
    switch (*src)
    {
        case '\\':
        case '"':
            AppendBytes (appendImpl, target, "\\", 1);
            //Fall through.
        default:
            AppendBytes (appendImpl, target, src, 1);
    }
}

- (char *) PGTSParameterLength: (int *) outLength connection: (PGTSConnection *) connection
{
    //We make use of UTF-8's ASCII-compatibility feature.
    char* retval = NULL;
    if (0 == [self count])
    {
        retval = "{}";
        if (outLength)
            *outLength = 2;
    }
    else
    {
        //Optimize a bit because we append each byte individually.
        NSMutableData* contents = [NSMutableData data];
        IMP impl = [contents methodForSelector: @selector (appendBytes:length:)];
        AppendBytes (impl, contents, "{", 1);
        BXEnumerate (currentObject, e, [self objectEnumerator])
        {
            if ([NSNull null] == currentObject)
			{
				const char* bytes = "null,";
                [contents appendBytes: bytes length: strlen (bytes)];
			}
            else
            {
                int length = -1;
                char* value = [currentObject PGTSParameterLength: &length connection: connection];
                
                //Arrays can't have quotes around them.
                if ([currentObject isKindOfClass: [NSArray class]])
                {
                    AppendBytes (impl, contents, value, length);
                    AppendBytes (impl, contents, ",", 1);
                }
                else
                {
                    //If the length isn't known, wait for a NUL byte.
                    AppendBytes (impl, contents, "\"", 1);
                    if (-1 == length)
                    {
                        while ('\0' != *value)
                        {
                            EscapeAndAppendByte (impl, contents, value);
                            value++;
                        }
                    }
                    else
                    {
                        char* end = value + length;
                        while (value < end)
                        {
                            EscapeAndAppendByte (impl, contents, value);
                            value++;
                        }
                    }
                    AppendBytes (impl, contents, "\"", 1);
                }
                AppendBytes (impl, contents, ",", 1);
            }
        }
		[contents replaceBytesInRange: NSMakeRange ([contents length] - 1, 1) withBytes: "}\0" length: 2]; 
		retval = (char *) [contents bytes];
		if (outLength)
			*outLength = [contents length];
		
    }
    return retval;
}

- (BOOL) PGTSIsCollection
{
	return YES;
}
@end


@implementation NSDate (PGTSFoundationObjects)
- (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 type: (PGTSTypeDescription *) typeInfo
{
	BXLogDebug (@"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];
    BXAssertLog (nil != rval, @"Failed to match string to date format");
#ifndef L4_BLOCK_ASSERTIONS
	double integralPart = 0.0;
	BXAssertLog (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;
}

- (id) PGTSExpressionOfType: (NSAttributeType) attrType
{
	return [NSString stringWithFormat: @"timestamp with time zone 'epoch' + interval '%f seconds'", [self timeIntervalSince1970]];
}
@end


@implementation NSCalendarDate (PGTSFoundationObjects)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) 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;
        }
    }
    
    BXAssertLog (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 (PGTSFoundationObjects)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) typeInfo
{
    NSDecimal decimal;
    NSString* stringValue = [NSString stringWithUTF8String: value];
    NSScanner* scanner = [NSScanner scannerWithString: stringValue];
    [scanner scanDecimal: &decimal];
    return [NSDecimalNumber decimalNumberWithDecimal: decimal];
}
@end


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

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

- (id) PGTSExpressionOfType: (NSAttributeType) attrType
{
	id retval = self;
	if (NSBooleanAttributeType == attrType)
		retval = ([self boolValue] ? @"true" : @"false");
	return retval;
}
@end


@implementation NSSet (PGTSFoundationObjects)
- (BOOL) PGTSIsCollection
{
	return YES;
}

//FIXME: should we allow set parameters?
- (char *) PGTSParameterLength: (int *) length connection: (PGTSConnection *) connection
{
	[self doesNotRecognizeSelector: _cmd];
	return NULL;
}
@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 type: (PGTSTypeDescription *) typeInfo
{
    return [NSNumber numberWithFloat: strtof (value, NULL)];
}
@end


@implementation PGTSDouble
@end


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


@implementation PGTSBool
@end


@implementation PGTSBool (PGTSAdditions)
+ (id) newForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) 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 type: (PGTSTypeDescription *) 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
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.