Source

baseten / Sources / BXDatabaseObjectID.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
//
// BXDatabaseObjectID.m
// BaseTen
//
// Copyright (C) 2006-2008 Marko Karppinen & Co. LLC.
//
// Before using this software, please review the available licensing options
// by visiting http://basetenframework.org/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 "BXDatabaseObjectModel.h"
#import "BXDatabaseObjectID.h"
#import "BXDatabaseObjectIDPrivate.h"
#import "BXEntityDescription.h"
#import "BXEntityDescriptionPrivate.h"
#import "BXDatabaseContext.h"
#import "BXInterface.h"
#import "BXAttributeDescription.h"
#import "BXDatabaseObject.h"
#import "BXDatabaseObjectPrivate.h"
#import "BXLogger.h"
#import "BXEnumerate.h"
#import "BXURLEncoding.h"
#import "BXException.h"
#import "NSURL+BaseTenAdditions.h"


/**
 * \brief A unique identifier for a database object.
 *
 * \ingroup baseten
 */
@implementation BXDatabaseObjectID

+ (NSURL *) URIRepresentationForEntity: (BXEntityDescription *) anEntity primaryKeyFields: (NSDictionary *) pkeyDict
{
    NSURL* databaseURI = [anEntity databaseURI];
    NSMutableArray* parts = [NSMutableArray arrayWithCapacity: [pkeyDict count]];
    
    //If the pkey fields are unknown, we have to trust the user on this one.
    NSArray* keys = nil;
    if ([anEntity primaryKeyFields])
    {
        NSMutableArray* temp = [NSMutableArray array];
        BXEnumerate (currentKey, e, [[anEntity primaryKeyFields] objectEnumerator])
        {
            if ([currentKey isPrimaryKey])
                [temp addObject: [currentKey name]];
        }
        [temp sortUsingSelector: @selector (compare:)];
        keys = temp;
    }
    else
    {
        keys = [pkeyDict keysSortedByValueUsingSelector: @selector (compare:)];
    }
    
    BXEnumerate (currentKey, e, [keys objectEnumerator])
    {
        id currentValue = [pkeyDict objectForKey: currentKey];
        BXAssertValueReturn ([NSNull null] != currentValue, nil, @"A pkey value was NSNull. Entity: %@", anEntity);
        
        NSString* valueForURL = @"";
        char argtype = 'd';
        //NSStrings and NSNumbers get a special treatment
        if ([currentValue isKindOfClass: [NSString class]])
        {
            valueForURL = [currentValue stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            argtype = 's';
        }
        else if ([currentValue isKindOfClass: [NSNumber class]])
        {
            valueForURL = [currentValue stringValue];
            argtype = 'n';
        }
        else
        {
            //Just use NSData
            valueForURL = [NSString BXURLEncodedData: [NSArchiver archivedDataWithRootObject: currentValue]];            
        }
        
        [parts addObject: [NSString stringWithFormat: @"%@,%c=%@", 
            [currentKey stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
            argtype, valueForURL]];
    }
    
    NSString* absolutePath = [[NSString stringWithFormat: @"/%@/%@/%@?",
        [databaseURI path],
        [[anEntity schemaName] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
        [[anEntity name] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]] stringByStandardizingPath];
    absolutePath = [absolutePath stringByAppendingString: [parts componentsJoinedByString: @"&"]];
    
    NSURL* URIRepresentation = [[NSURL URLWithString: absolutePath relativeToURL: databaseURI] absoluteURL];
    return URIRepresentation;
}

+ (BOOL) parseURI: (NSURL *) anURI
           entity: (NSString **) outEntityName
           schema: (NSString **) outSchemaName
 primaryKeyFields: (NSDictionary **) outPkeyDict
{
    //FIXME: URI validation?
    //NSString* absoluteURI = [anURI absoluteString];
    NSString* query = [anURI query];
    NSString* path = [anURI path];
    
    NSArray* pathComponents = [path pathComponents];
    NSUInteger count = [pathComponents count];
    NSString* tableName = [pathComponents objectAtIndex: count - 1];
    NSString* schemaName = [pathComponents objectAtIndex: count - 2];
    //FIXME: object address and context address should be compared.
    //NSString* dbAddress = [absoluteURI substringToIndex: [absoluteURI length] - ([tableName length] + 1 + [query length])];
        
	NSMutableDictionary* pkeyDict = [NSMutableDictionary dictionary];
	NSScanner* queryScanner = [NSScanner scannerWithString: query];
	while (NO == [queryScanner isAtEnd])
	{
		NSString* key = nil;
		NSString* type = nil;
		id value = nil;
		
		[queryScanner scanUpToString: @"," intoString: &key];
		[queryScanner scanString: @"," intoString: NULL];
		[queryScanner scanUpToString: @"=" intoString: &type];
		[queryScanner scanString: @"=" intoString: NULL];
		
		unichar c = [type characterAtIndex: 0];
		switch (c)
		{
			case 's':
				[queryScanner scanUpToString: @"&" intoString: &value];
				value = [value stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
				break;
			case 'n':
			{
				NSDecimal dec;
				[queryScanner scanDecimal: &dec];
				value = [NSDecimalNumber decimalNumberWithDecimal: dec];
				break;
			}
			case 'd':
			{
				NSString* encodedString = nil;
				[queryScanner scanUpToString: @"&" intoString: &encodedString];
				NSData* archivedData = [encodedString BXURLDecodedData];
				value = [NSUnarchiver unarchiveObjectWithData: archivedData];
				break;
			}
			default:
                goto bail;
                break;
		}	
		[pkeyDict setObject: value forKey: key];
		
		[queryScanner scanUpToString: @"&" intoString: NULL];
		[queryScanner scanString: @"&" intoString: NULL];
	}
    
    if (NULL != outEntityName) *outEntityName = tableName;
    if (NULL != outSchemaName) *outSchemaName = schemaName;
    if (NULL != outPkeyDict) *outPkeyDict = pkeyDict;
    
	return YES;
	
bail:
	{
		return NO;
	}
}

/** 
 * \brief Create an object identifier from an NSURL.
 * \note This is not the designated initializer.
 */
- (id) initWithURI: (NSURL *) anURI context: (BXDatabaseContext *) context
{
    NSString* entityName = nil;
    NSString* schemaName = nil;
    NSDictionary* pkeyDict = nil;

    if ([[self class] parseURI: anURI entity: &entityName
                        schema: &schemaName primaryKeyFields: &pkeyDict])
    {
		BXEntityDescription *entity = [[context databaseObjectModel] entityForTable: entityName inSchema: schemaName];
		if (! entity)
		{
			NSError *error = [BXDatabaseObjectModel errorForMissingEntity: entityName inSchema: schemaName];
			@throw [error BXExceptionWithName: NSInvalidArgumentException];
		}
		
        [[self class] verifyPkey: pkeyDict entity: entity];
        self = [self initWithEntity: entity objectURI: anURI];
    }
    return self;
}

- (id) initWithURI: (NSURL *) anURI context: (BXDatabaseContext *) context error: (NSError **) error
{
	BXDeprecationLog ();
	return [self initWithURI: anURI context: context];
}

- (NSString *) description
{
    return [NSString stringWithFormat: @"<%@ (%p) %@>", [self class], self, [self URIRepresentation]];
}

- (void) dealloc
{
    if (YES == mRegistered)
        [mEntity unregisterObjectID: self];
    
    [mURIRepresentation release];
    [mEntity release];
    [super dealloc];
}

/** \brief The entity of the receiver. */
- (BXEntityDescription *) entity
{
    return mEntity;
}

/** \brief URI representation of the receiver. */
- (NSURL *) URIRepresentation
{
    return mURIRepresentation;
}

- (NSUInteger) hash
{
    return mHash;
}

/** 
 * \brief An NSPredicate for this object ID.
 * The predicate can be used to fetch the object from the database, for example.
 */
- (NSPredicate *) predicate
{
    NSPredicate* retval = nil;
    NSDictionary* pkeyFValues = nil;
    BOOL ok = [[self class] parseURI: mURIRepresentation entity: NULL schema: NULL primaryKeyFields: &pkeyFValues];
    if (ok)
    {
        NSDictionary* attributes = [mEntity attributesByName];
		Expect (attributes);
        NSMutableArray* predicates = [NSMutableArray arrayWithCapacity: [pkeyFValues count]];
    
        BXEnumerate (currentKey, e, [pkeyFValues keyEnumerator])
        {
            NSExpression* rhs = [NSExpression expressionForConstantValue: [pkeyFValues objectForKey: currentKey]];
            NSExpression* lhs = [NSExpression expressionForKeyPath: currentKey];
            NSPredicate* predicate = 
                [NSComparisonPredicate predicateWithLeftExpression: lhs
                                                   rightExpression: rhs
                                                          modifier: NSDirectPredicateModifier
                                                              type: NSEqualToPredicateOperatorType
                                                           options: 0];
            [predicates addObject: predicate];
        }
        
        if (0 < [predicates count])
            retval = [NSCompoundPredicate andPredicateWithSubpredicates: predicates];
    }
    
    return retval;
}

- (BOOL) isEqual: (id) anObject
{
    BOOL retval = NO;
    if (NO == [anObject isKindOfClass: [BXDatabaseObjectID class]])
        retval = [super isEqual: anObject];
    else
    {
        BXDatabaseObjectID* anId = (BXDatabaseObjectID *) anObject;
        if (0 == anId->mHash || 0 == mHash || anId->mHash == mHash)
        {
            retval = [mURIRepresentation isEqual: anId->mURIRepresentation];
        }
    }
    return retval;
}

@end


@implementation BXDatabaseObjectID (NSCopying)
/** \brief Retain on copy. */
- (id) copyWithZone: (NSZone *) zone
{
    return [self retain];
}

- (id) mutableCopyWithZone: (NSZone *) zone
{
    return [[[self class] allocWithZone: zone]
        initWithEntity: mEntity objectURI: mURIRepresentation];
}
@end


@implementation BXDatabaseObjectID (PrivateMethods)

+ (void) verifyPkey: (NSDictionary *) pkeyDict entity: (BXEntityDescription *) entity
{
    NSArray* pkeyFields = [entity primaryKeyFields];
    if (nil != pkeyFields)
    {
        BXAssertVoidReturn ([pkeyFields count] <= [pkeyDict count],
                              @"Expected to have received values for all primary key fields.");
        BXEnumerate (currentAttribute, e, [pkeyFields objectEnumerator])
        {
            BXAssertVoidReturn (nil != [pkeyDict objectForKey: [currentAttribute name]], 
                                  @"Primary key not included: %@ given: %@", currentAttribute, pkeyDict);
        }
    }
}

/** 
 * \internal
 * \name Creating object IDs */
//@{
/**
 * \internal
 * \brief A convenience method.
 */
+ (id) IDWithEntity: (BXEntityDescription *) aDesc primaryKeyFields: (NSDictionary *) pkeyFValues
{
    NSArray* keys = [pkeyFValues allKeys];
    BXEnumerate (currentKey, e, [keys objectEnumerator])
    {
        BXAssertValueReturn ([currentKey isKindOfClass: [NSString class]],
                               nil, @"Expected to receive only NSStrings as keys. Keys: %@", keys);
    }
    [self verifyPkey: pkeyFValues entity: aDesc];

    NSURL* uri = [[self class] URIRepresentationForEntity: aDesc primaryKeyFields: pkeyFValues];
    BXAssertValueReturn (nil != uri, nil, @"Expected to have received an URI.");
    return [[[[self class] alloc] initWithEntity: aDesc objectURI: uri] autorelease];
}

/** 
 * \internal
 * \brief The designated initializer.
 */
- (id) initWithEntity: (BXEntityDescription *) anEntity objectURI: (NSURL *) anURI
{
    BXAssertValueReturn (nil != anEntity, nil, @"Expected entity not to be nil.");
    BXAssertValueReturn (nil != anURI, nil, @"Expected anURI not to be nil.");
    
    if ((self = [super init]))
    {
		{
			NSString* entityName = nil;
			NSString* schemaName = nil;
			BXAssertValueReturn ([[self class] parseURI: anURI entity: &entityName schema: &schemaName primaryKeyFields: NULL],
								   nil, @"Expected object URI to be parseable.");
			BXAssertValueReturn ([[anEntity name] isEqualToString: entityName], nil, @"Expected entity names to match.");
			BXAssertValueReturn ([[anEntity schemaName] isEqualToString: schemaName], nil, @"Expected schema names to match.");
		}
		
        mURIRepresentation = [anURI retain];
        mEntity = [anEntity retain];
        mRegistered = NO;
        mHash = [mURIRepresentation BXHash];
    }
    return self;
}
//@}

- (id) init
{
    //We need either an URI or an entity and primary key fields
    [self release];
    return nil;
}

#if 0
- (BXDatabaseObjectID *) partialKeyForView: (BXEntityDescription *) view
{
    BXAssertValueReturn ([view isView], nil, @"Expected given entity (%@) to be a view.", view);
    
    NSArray* keys = [view primaryKeyFields];
    NSArray* myKeys = [[self entity] correspondingProperties: keys];
    NSArray* values = [self objectsForKeys: myKeys];
    return [[self class] IDWithEntity: view primaryKeyFields: [NSDictionary dictionaryWithObjects: values forKeys: keys]];
}
#endif

- (void) setStatus: (enum BXObjectDeletionStatus) status forObjectRegisteredInContext: (BXDatabaseContext *) context
{
	[[context registeredObjectWithID: self] setDeleted: status];
}

- (NSDictionary *) allValues
{
	NSDictionary* retval = nil;
	BOOL ok = [[self class] parseURI: mURIRepresentation
							  entity: NULL
							  schema: NULL
					primaryKeyFields: &retval];
	BXAssertLog (ok, @"Expected URI to have been parsed correctly: %@", mURIRepresentation);
	return retval;
}

- (void) setEntity: (BXEntityDescription *) entity
{
    BXAssertVoidReturn (NO == mRegistered, @"Expected object ID not to have been registered.");
    NSString* path = [NSString stringWithFormat: @"../%@/%@?%@", 
        [entity schemaName], [entity name], [mURIRepresentation query]];
    
    mHash = 0;
    NSURL* newURI = [NSURL URLWithString: path relativeToURL: mURIRepresentation];
    [mURIRepresentation release];
    mURIRepresentation = [[newURI absoluteURL] retain];
}

@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.