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
//
// 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/libpq-fe.h>
#import "PGTSFoundationObjects.h"
#import "PGTSConnection.h"
#import "PGTSConnectionPrivate.h"
#import "PGTSTypeDescription.h"
#import "PGTSTableDescription.h"
#import "PGTSColumnDescription.h"
#import "PGTSDatabaseDescription.h"
#import "PGTSResultSet.h"
#import "NSString+PGTSAdditions.h"
#import "BXLogger.h"
#import "BXEnumerate.h"



@implementation NSObject (PGTSFoundationObjects)
+ (id) copyForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) type columnIndex: (int) columnIndex
{
	return [self copyForPGTSResultSet: set withCharacters: value type: type];
}

+ (id) copyForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) typeInfo
{
    BXLogWarning (@"Returning nil from NSObject's implementation for type %@ (%p).", [typeInfo name], typeInfo);
    return nil;
}

- (id) PGTSParameter: (PGTSConnection *) connection
{
	return self;
}

- (const char *) PGTSParameterLength: (size_t *) length connection: (PGTSConnection *) connection
{
    BXLogWarning (@"Returning NULL from NSObject's implementation for %@.", [self class]);
	if (length)
		*length = 0;
	return NULL;
}

- (BOOL) PGTSIsBinaryParameter
{
    return NO;
}

- (BOOL) PGTSIsCollection
{
	return NO;
}

- (id) PGTSExpressionOfType: (NSAttributeType) attrType connection: (PGTSConnection *) connection
{
	NSString *retval = nil;
	size_t length = 0;
	id param = [self PGTSParameter: connection];
	
	if ([param PGTSIsBinaryParameter])
	{
		size_t resultLength = 0;
		unsigned char *escapedValue = NULL;
		const unsigned char *value = (const unsigned char *) [param PGTSParameterLength: &length connection: connection];
		escapedValue = PQescapeByteaConn ([connection pgConnection], value, length, &resultLength);
		retval = [NSString stringWithFormat: @"'%s'", escapedValue];
		PQfreemem (escapedValue);
	}
	else
	{
		char *escapedValue = NULL;
		const char *value = [param PGTSParameterLength: &length connection: connection];
		escapedValue = PGTSCopyEscapedString (connection, value);
		retval = [NSString stringWithFormat: @"'%s'", escapedValue];
		free (escapedValue);
	}
	
	[param self]; // For GC.
	return retval;
}
@end


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


@implementation NSString (PGTSFoundationObjects)
+ (id) copyForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) typeInfo
{
	NSString *string = [[NSString alloc] initWithUTF8String: value];
	NSString *retval = [[string decomposedStringWithCanonicalMapping] retain];
	[string release];
	return retval;
}

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


@implementation NSData (PGTSFoundationObjects)
+ (id) copyForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) value type: (PGTSTypeDescription *) typeInfo
{
	//All columns are currently fetched in text format but according to the manual only bytea is escaped.
	//Bit and varbit seem to return bit strings as their name indicates, rather than octet strings.

	NSData* retval = nil;
	
	NSString* name = [typeInfo name];
	if ([@"bytea" isEqualToString: name])
	{
		size_t resultLength = 0;
		unsigned char *unescaped = PQunescapeBytea ((const unsigned char *) value, &resultLength);
		if (unescaped)
		{
			retval = [[self alloc] initWithBytes: unescaped length: resultLength];
			PQfreemem (unescaped);
		}
		else
		{
			BXLogWarning (@"PQunescapeBytea failed for characters: %s.", value);
		}		
	}
	else
	{
		retval = [[self alloc] initWithBytes: value length: strlen (value)];
	}
	return retval;
}

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

- (BOOL) PGTSIsBinaryParameter
{
    return YES;
}
@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) copyForPGTSResultSet: (PGTSResultSet *) set withCharacters: (const char *) current type: (PGTSTypeDescription *) typeInfo
{
    id retval = [[NSMutableArray alloc] init];
    //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 [] = {[elementType delimiter], '\0', '\0'};
        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 copyForPGTSResultSet: set withCharacters: elementData type: elementType] autorelease];
                    free (elementData);
                }
                [retval addObject: object];
                
                element = NULL;
                escaped = NULL;
                //Are we at the end?
                if (*current != endings [0])
                    break;
            }
            
continue_iteration:
                current++;
        }
    }
    return retval;
}

static inline void
AppendBytes (IMP impl, NSMutableData* target, const void* bytes, NSUInteger length)
{
	(void)(void (*)(id, SEL, const void*, NSUInteger)) 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);
    }
}

- (id) PGTSParameter: (PGTSConnection *) connection
{
    //We make use of UTF-8's ASCII-compatibility feature.
	id retval = nil;
    if (0 == [self count])
    {
		const char* emptyArray = "{}";
		retval = [NSData dataWithBytes: &emptyArray length: strlen (emptyArray)];
    }
    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
            {
                size_t length = SIZE_T_MAX;
                const char* value = [[currentObject PGTSParameter: connection] 
									 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 ([currentObject PGTSIsBinaryParameter] && SIZE_T_MAX != length)
                    {
                        const char* end = value + length;
                        while (value < end)
                        {
                            EscapeAndAppendByte (impl, contents, value);
                            value++;
                        }
                    }
                    else
					{
                        while ('\0' != *value)
                        {
                            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 = contents;
    }
    return retval;
}

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


@implementation NSDecimalNumber (PGTSFoundationObjects)
+ (id) copyForPGTSResultSet: (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 alloc] initWithDecimal: decimal];
}
@end


@implementation NSNumber (PGTSFoundationObjects)
- (id) PGTSParameter: (PGTSConnection *) connection
{
	return [self description];
}

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

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


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

//FIXME: should we allow set parameters?
- (id) PGTSParameter: (PGTSConnection *) connection
{
	[self doesNotRecognizeSelector: _cmd];
	return nil;
}

- (const char *) PGTSParameterLength: (size_t *) length connection: (PGTSConnection *) connection
{
	[self doesNotRecognizeSelector: _cmd];
	return NULL;
}
@end


@implementation NSXMLDocument (PGTSFoundationObjects)
+ (id) copyForPGTSResultSet: (PGTSResultSet *) result withCharacters: (const char *) value type: (PGTSTypeDescription *) type columnIndex: (int) columnIndex
{
	BOOL shouldReturnDocument = NO;
	NSData* xmlData = [[NSData alloc] initWithBytes: value length: strlen (value)];
	id retval = xmlData;
	PGresult* res = [result PGresult];
	Oid relid = PQftable (res, columnIndex);
	int attnum = PQftablecol (res, columnIndex);
	
	if (InvalidOid != relid)
	{
		PGTSDatabaseDescription* db = [[result connection] databaseDescription];
		PGTSTableDescription* rel = [db tableWithOid: relid];
		PGTSColumnDescription* column = [rel columnAtIndex: attnum];
		if ([column requiresDocuments])
			shouldReturnDocument = YES;
	}
	
	if (shouldReturnDocument)
	{
		NSError* error = nil;
		retval = nil;
		NSXMLDocument* document = [[NSXMLDocument alloc] initWithData: xmlData options: 0 error: &error];
		[xmlData release];
		
		if (document)
			retval = document;
		else
			BXLogError (@"Unable to create XML document even though I was supposed to have received one. Error: %@.", error);
	}
	
	return retval;
}

- (id) PGTSParameter: (PGTSConnection *) connection
{
	return [self XMLStringWithOptions: NSXMLNodeCompactEmptyElement | NSXMLNodeUseDoubleQuotes];
}
@end


@implementation NSValue (PGTSFoundationObjects)
- (id) PGTSParameter: (PGTSConnection *) connection
{
	id retval = nil;
	if (0 == strcmp (@encode (NSPoint), [self objCType]))
	{
		NSPoint point = [self pointValue];
		retval = [NSString stringWithFormat: @"(%lf,%lf)", point.x, point.y];
	}
	else
	{
		retval = [super PGTSParameter: connection];
	}
	return retval;
}
@end


@implementation NSNull (PGTSFoundationObjects)
- (const char *) PGTSParameterLength: (size_t *) length connection: (PGTSConnection *) connection
{
	if (length)
		*length = 0;
	return NULL;
}
@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.