Source

baseten / Sources / PGTSResultSet.mm

  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
//
// PGTSResultSet.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 <stdlib.h>
#import <limits.h>
#import <tr1/unordered_map>
#import <BaseTen/postgresql/libpq-fe.h>
#import "PGTSConnection.h"
#import "PGTSResultSet.h"
#import "PGTSConstants.h"
#import "PGTSDatabaseDescription.h"
#import "PGTSTableDescription.h"
#import "PGTSColumnDescription.h"
#import "PGTSTypeDescription.h"
#import "PGTSFoundationObjects.h"
#import "PGTSAdditions.h"
#import "PGTSScannedMemoryAllocator.h"
#import "PGTSCollections.h"
#import "BXLogger.h"


typedef std::tr1::unordered_map <NSString*, int, 
	PGTS::ObjectHash, 
	PGTS::ObjectCompare <NSString *>, 
	PGTS::scanned_memory_allocator <std::pair <NSString * const, int> > > 
	FieldIndexMap;
typedef std::tr1::unordered_map <int, Class, 
	std::tr1::hash <int>, 
	std::equal_to <int>, 
	PGTS::scanned_memory_allocator <std::pair <const int, Class> > > 
	FieldClassMap;


static NSString*
ErrorUserInfoKey (char fieldCode)
{
    NSString* retval = nil;
    switch (fieldCode)
    {
        case PG_DIAG_SEVERITY:
            retval = kPGTSErrorSeverity;
            break;
            
        case PG_DIAG_SQLSTATE:
            retval = kPGTSErrorSQLState;
            break;
            
        case PG_DIAG_MESSAGE_PRIMARY:
            retval = kPGTSErrorPrimaryMessage;
            break;
            
        case PG_DIAG_MESSAGE_DETAIL:
            retval = kPGTSErrorDetailMessage;
            break;
            
        case PG_DIAG_MESSAGE_HINT:
            retval = kPGTSErrorHint;
            break;
            
        case PG_DIAG_INTERNAL_QUERY:
            retval = kPGTSErrorInternalQuery;
            break;
            
        case PG_DIAG_CONTEXT:
            retval = kPGTSErrorContext;
            break;
            
        case PG_DIAG_SOURCE_FILE:
            retval = kPGTSErrorSourceFile;
            break;
            
        case PG_DIAG_SOURCE_FUNCTION:
            retval = kPGTSErrorSourceFunction;
            break;
            
        case PG_DIAG_STATEMENT_POSITION:
            retval = kPGTSErrorStatementPosition;
            break;
            
        case PG_DIAG_INTERNAL_POSITION:
            retval = kPGTSErrorInternalPosition;
            break;
            
        case PG_DIAG_SOURCE_LINE:
            retval = kPGTSErrorSourceLine;
            break;
            
        default:
            break;
    }
    return retval;
}



@interface PGTSResultError : NSError
{
}
@end



@interface PGTSConcreteResultSet : PGTSResultSet
{
    PGTSConnection* mConnection; //Weak
	PGresult* mResult;
	int mCurrentRow;
    int mFields;
    int mTuples;
    NSInteger mIdentifier;
    FieldIndexMap* mFieldIndices;
    FieldClassMap* mFieldClasses;
    Class mRowClass;
	id mUserInfo;
    
    BOOL mKnowsFieldClasses;
    BOOL mDeterminesFieldClassesFromDB;
}
+ (id) resultWithPGresult: (PGresult *) aResult connection: (PGTSConnection *) aConnection;
- (id) initWithPGResult: (PGresult *) aResult connection: (PGTSConnection *) aConnection;
@end



@implementation PGTSResultError
- (NSString *) description
{
	return [[self userInfo] objectForKey: kPGTSErrorMessage];
}
@end



/** 
 * \internal
 * \brief Result set for a query.
 *
 * A result set contains rows that may be iterated by the user.
 */
@implementation PGTSConcreteResultSet

- (PGTSConnection *) connection
{
    return mConnection;
}

- (void) dealloc
{
	PQclear (mResult);
    delete mFieldClasses;
    FieldIndexMap::const_iterator iterator = mFieldIndices->begin ();
    while (mFieldIndices->end () != iterator)
    {
		[iterator->first autorelease];
        iterator++;
    }
    delete mFieldIndices;
    [mConnection release];
    [super dealloc];
}

- (void) finalize
{
	PQclear (mResult);
    delete mFieldClasses;
    delete mFieldIndices;
    [super finalize];
}

- (NSString *) description
{
    return [NSString stringWithFormat: @"<%@ (%p) cr: %d t: %d f: %d kc: %d ok: %d>",
        [self class], self, mCurrentRow, mTuples, mFields, mKnowsFieldClasses, [self querySucceeded]];
}

- (ExecStatusType) status
{
	return PQresultStatus (mResult);
}

- (BOOL) querySucceeded
{
    ExecStatusType s = [self status];
    return (PGRES_FATAL_ERROR != s && PGRES_BAD_RESPONSE != s);
}

+ (id) resultWithPGresult: (PGresult *) aResult connection: (PGTSConnection *) aConnection
{
	return [[[self alloc] initWithPGResult: aResult connection: aConnection] autorelease];
}

- (id) initWithPGResult: (PGresult *) result connection: (PGTSConnection *) aConnection;
{
	if ((self = [super init]))
    {
        mConnection = [aConnection retain];
        
        mResult = result;
        mCurrentRow = -1;
        mTuples = PQntuples (result);
        mFields = PQnfields (result);
    
        mFieldIndices = new FieldIndexMap (mFields);
        mFieldClasses = new FieldClassMap (mFields);
        for (int i = 0; i < mFields; i++)
        {
            char* fname = PQfname (result, i);
            if (!fname)
            {
                mFields = i;
                break;
            }
			NSString* stringName = [NSString stringWithUTF8String: fname];
            (* mFieldIndices) [[stringName retain]] = i;
        }
        mDeterminesFieldClassesFromDB = YES;
    }        
	return self;
}

- (void) setDeterminesFieldClassesAutomatically: (BOOL) aBool
{
    mDeterminesFieldClassesFromDB = aBool;
}

- (void) fetchFieldDescriptions
{
	mKnowsFieldClasses = YES;
    
#if 0
	Oid* oidVector = (Oid *) calloc (mFields + 1, sizeof (Oid));
	for (int i = 0; i < mFields; i++)
		oidVector [i] = PQftype (mResult, i);
	oidVector [mFields] = InvalidOid;
#endif

	PGTSDatabaseDescription* db = [mConnection databaseDescription];
#if 0
	//Warm-up the cache.
	[db typesWithOids: oidVector];
	free (oidVector);
	oidVector = NULL;
#endif
	
    NSDictionary* deserializationDictionary = [mConnection deserializationDictionary];
    for (int i = 0; i < mFields; i++)
    {
        PGTSTypeDescription* type = [db typeWithOid: PQftype (mResult, i)];
        NSString* name = [type name];
		Class aClass = [deserializationDictionary objectForKey: name];
		
		if (! aClass)
		{
			//Check for arrays. Other types that satisfy the condition (like int2vector and oidvector) 
			//should have an entry in deserializationDictionary, if they are used.
			if (-1 == [type length] && InvalidOid != [type elementOid])
			{
				aClass = [NSArray class];
			}
			else
			{
				//Handle other types by kind.
				switch ([type kind]) 
				{
					case 'e':
						aClass = [NSString class];
						break;
						
					case 'c':
						//FIXME: handle composite types.
					case 'd':
						//FIXME: handle domains.
					case 'p':
						//FIXME: handle pseudo-types. (On the other hand, this shouldn't get reached.)
					case 'b':
					default:
						aClass = [NSData class];					
						break;
				}				
			}
		}
		
		[self setClass: aClass forFieldAtIndex: i];
	}
}

- (int) numberOfFields
{
	return mFields;
}

- (NSArray *) resultAsArray
{
	NSMutableArray* retval = [NSMutableArray arrayWithCapacity: [self count]];
	[self goBeforeFirstRow];
	while ([self advanceRow]) 
	{
		[retval addObject: [self currentRowAsDictionary]];
	}
	return retval;
}

- (NSInteger) identifier
{
    return mIdentifier;
}

- (void) setIdentifier: (NSInteger) anIdentifier
{
    mIdentifier = anIdentifier;
}

- (NSString *) errorString
{
	return [NSString stringWithUTF8String: PQresultErrorMessage (mResult)];
}

- (NSError *) error
{
	return [[self class] errorForPGresult: mResult];
}
	
- (PGresult *) PGresult
{
	return mResult;
}
@end


@implementation PGTSConcreteResultSet (RowAccessors)

- (BOOL) isAtEnd
{
    return (mCurrentRow == mTuples - 1);
}

- (int) currentRow
{
    return mCurrentRow;
}

- (id <PGTSResultRowProtocol>) currentRowAsObject
{
    id retval = [[[mRowClass alloc] init] autorelease];
	
    if (retval)
        [retval PGTSSetRow: mCurrentRow resultSet: self];
    
    //We are too simple to cache and reuse these.
    return retval;
}

- (void) setRowClass: (Class) aClass
{
    if ([aClass conformsToProtocol: @protocol (PGTSResultRowProtocol)])
        mRowClass = aClass;
    else
    {
        //FIXME: localize me.
        NSString* reason = @"Class %@ does not conform to protocol PGTSResultRowProtocol";
        [NSException raise: NSInvalidArgumentException 
                    format: reason, aClass];
    }
}

- (void) setValuesFromRow: (int) rowIndex target: (id) targetObject nullPlaceholder: (id) nullPlaceholder
{
    FieldIndexMap::const_iterator iterator = mFieldIndices->begin ();
    while (mFieldIndices->end () != iterator)
    {
        NSString* fieldname = iterator->first;
        id value = [self valueForKey: fieldname row: rowIndex];
        if (! value)
            value = nullPlaceholder;
        @try
        {
            [targetObject setValue: value forKey: fieldname];
        }
        @catch (id e)
        {
        }
        iterator++;
    }
}

/**
 * \brief Current row with field names as keys.
 *
 * NSNull is used in place of nil.
 */
- (NSDictionary *) currentRowAsDictionary
{
    NSMutableDictionary* retval = [NSMutableDictionary dictionaryWithCapacity: mFields];
    [self setValuesFromRow: mCurrentRow target: retval nullPlaceholder: [NSNull null]];
    return retval;
}

/** \brief Move to the beginning of the result set */
- (void) goBeforeFirstRow
{
    [self goToRow: -1];
}

- (BOOL) goToRow: (int) aRow
{
    BOOL retval = NO;
	if (-1 <= aRow && aRow < mTuples)
	{
		mCurrentRow = aRow;
		retval = YES;
	}
	return retval;
}

- (void) goBeforeFirstRowWithValue: (id) value forKey: (NSString *) columnName low: (const int) low high: (const int) high
{
	int mid = round (low / 2.0 + high / 2.0);
	if (mid == high)
		[self goToRow: low];
	else
	{
		//Tail recursion.
		id currentValue = [self valueForKey: columnName row: mid];
		switch ([currentValue compare: value])
		{
			case NSOrderedAscending:
				[self goBeforeFirstRowWithValue: value forKey: columnName low: mid high: high];
				break;
				
			case NSOrderedSame:
			case NSOrderedDescending:
				[self goBeforeFirstRowWithValue: value forKey: columnName low: low high: mid];
				break;
												
			default: 
				[NSException raise: NSInternalInconsistencyException format: nil];
				break;
		}
	}
}

- (void) goBeforeFirstRowWithValue: (id) value forKey: (NSString *) columnName
{
	if (! mKnowsFieldClasses && mDeterminesFieldClassesFromDB)
        [self fetchFieldDescriptions];

	//low is -1 because the first row might apply and -advanceRow will probably will be called after this method.
	//high is mTuples (instead of mTuples - 1) in case even the last row doesn't apply and we set it to current.
	[self goBeforeFirstRowWithValue: value forKey: columnName low: -1 high: mTuples];
	ExpectV (mCurrentRow == -1 || NSOrderedAscending == [[self valueForKey: columnName row: mCurrentRow] compare: value]);
	ExpectV (mCurrentRow == mTuples - 1 || NSOrderedAscending != [[self valueForKey: columnName row: mCurrentRow + 1] compare: value]);
}

- (int) count
{
	return mTuples;
}

- (unsigned long long) numberOfRowsAffectedByCommand
{
	return strtoull (PQcmdTuples (mResult), NULL, 10);
}

- (BOOL) advanceRow
{
    BOOL retval = NO;
    
    if (! mKnowsFieldClasses && mDeterminesFieldClassesFromDB)
        [self fetchFieldDescriptions];
    
    //Row numbering is zero-based.
    //The number is initially -1. 
	if (mCurrentRow < mTuples - 1)
	{
        mCurrentRow++;
		retval = YES;
	}
	return retval;
}

- (void) setUserInfo: (id) userInfo
{
	if (mUserInfo != userInfo)
	{
		[mUserInfo release];
		mUserInfo = [userInfo retain];
	}
}

- (id) userInfo
{
	return mUserInfo;
}
@end


@implementation PGTSConcreteResultSet (FieldAccessors)

/**
 * \brief Set the class that should be used with a specific field.
 * @{
 */
- (BOOL) setClass: (Class) aClass forKey: (NSString *) aName
{
    return [self setClass: aClass forFieldAtIndex: (* mFieldIndices) [aName]];
}

- (BOOL) setClass: (Class) aClass forFieldAtIndex: (int) fieldIndex
{
    BOOL retval = NO;
    if (fieldIndex < mFields)
    {
        (* mFieldClasses) [fieldIndex] = aClass;
        retval = YES;
    }
    return retval;
}
/** @} */

- (id) valueForFieldAtIndex: (int) columnIndex row: (int) rowIndex
{
    id retval = nil;
    if (! ((columnIndex < mFields) && (rowIndex < mTuples)))
    {
		[NSException raise: kPGTSFieldNotFoundException format: nil];
    }
    
    if (! PQgetisnull (mResult, rowIndex, columnIndex))
    {
        Class objectClass = (* mFieldClasses) [columnIndex];
        if (! objectClass)
            objectClass = [NSData class];
        char* value = PQgetvalue (mResult, rowIndex, columnIndex);
        PGTSTypeDescription* type = [[mConnection databaseDescription] typeWithOid: PQftype (mResult, columnIndex)];
        retval = [objectClass newForPGTSResultSet: self withCharacters: value type: type];
    }
    return retval;
}

- (id) valueForFieldAtIndex: (int) columnIndex
{
    return [self valueForFieldAtIndex: columnIndex row: mCurrentRow];
}

- (id) valueForKey: (NSString *) aName row: (int) rowIndex
{
    FieldIndexMap::const_iterator iter = mFieldIndices->find (aName);
    if (mFieldIndices->end () == iter)
    {
        @throw [NSException exceptionWithName: kPGTSFieldNotFoundException reason: nil 
                                     userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
                                         aName, kPGTSFieldnameKey,
                                         self,  kPGTSResultSetKey,
                                         nil]];
    }
    int columnIndex = iter->second;
    return [self valueForFieldAtIndex: columnIndex row: rowIndex];
}

- (id) valueForKey: (NSString *) aName
{
    return [self valueForKey: aName row: mCurrentRow];
}

@end


@implementation PGTSResultSet
+ (id) resultWithPGresult: (PGresult *) aResult connection: (PGTSConnection *) aConnection
{
    return [[[PGTSConcreteResultSet alloc] initWithPGResult: aResult connection: aConnection] autorelease];
}

+ (NSError *) errorForPGresult: (PGresult *) result
{
	NSError* retval = nil;
	ExecStatusType status = PQresultStatus (result);
	if (PGRES_FATAL_ERROR == status || PGRES_NONFATAL_ERROR == status)
	{
		char fields [] = {
			PG_DIAG_SEVERITY,
			PG_DIAG_SQLSTATE,
			PG_DIAG_MESSAGE_PRIMARY,
			PG_DIAG_MESSAGE_DETAIL,
			PG_DIAG_MESSAGE_HINT,
			PG_DIAG_STATEMENT_POSITION,
			PG_DIAG_INTERNAL_POSITION,
			PG_DIAG_INTERNAL_QUERY,
			PG_DIAG_CONTEXT,
			PG_DIAG_SOURCE_FILE,
			PG_DIAG_SOURCE_LINE,
			PG_DIAG_SOURCE_FUNCTION
		};
		
		NSMutableDictionary* userInfo = [NSMutableDictionary dictionaryWithCapacity: (sizeof (fields)) / sizeof (char)];
		
		for (int i = 0, count = sizeof (fields) / sizeof (* fields); i < count; i++)
		{
			char* value = PQresultErrorField (result, fields [i]);
			if (! value) continue;
			
			id objectValue = nil;
			switch (fields [i])
			{
				case PG_DIAG_SEVERITY: //FIXME: perhaps add the severity as a constant number?
				case PG_DIAG_SQLSTATE:
				case PG_DIAG_MESSAGE_PRIMARY:
				case PG_DIAG_MESSAGE_DETAIL:
				case PG_DIAG_MESSAGE_HINT:
				case PG_DIAG_INTERNAL_QUERY:
				case PG_DIAG_CONTEXT:
				case PG_DIAG_SOURCE_FILE:
				case PG_DIAG_SOURCE_FUNCTION:
				{
					objectValue = [NSString stringWithUTF8String: value];
					break;
				}
					
				case PG_DIAG_STATEMENT_POSITION:
				case PG_DIAG_INTERNAL_POSITION:
				case PG_DIAG_SOURCE_LINE:
				{
					long longValue = strtol (value, NULL, 10);
					objectValue = [NSNumber numberWithLong: longValue];
					break;
				}
					
				default:
					continue;
			}
			NSString* key = ErrorUserInfoKey (fields [i]);
			if (objectValue && key) [userInfo setObject: objectValue forKey: key];
		}
		
		{
			//Human-readable error message.
			NSString* message = [NSString stringWithUTF8String: PQresultErrorMessage (result)];
			[userInfo setObject: message forKey: kPGTSErrorMessage];
			//FIXME: I'm not quite sure which key should have the human-readable message and what should be made the exception name.
			[userInfo setObject: message forKey: NSLocalizedFailureReasonErrorKey];
			[userInfo setObject: message forKey: NSLocalizedRecoverySuggestionErrorKey];
		}
		
		retval = [[PGTSResultError alloc] initWithDomain: kPGTSErrorDomain code: kPGTSUnsuccessfulQueryError userInfo: userInfo];
		[retval autorelease];
	}
	return 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.