baseten / Sources / BXEntityDescription.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
//
// BXEntityDescription.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 "BXEntityDescription.h"
#import "BXEntityDescriptionPrivate.h"
#import "BXDatabaseContext.h"
#import "BXAttributeDescription.h"
#import "BXRelationshipDescription.h"
#import "BXRelationshipDescriptionPrivate.h"
#import "BXAttributeDescriptionPrivate.h"
#import "BXPropertyDescriptionPrivate.h"
#import "BXDatabaseObject.h"
#import "BXConstantsPrivate.h"
#import "BXLogger.h"
#import "BXWeakNotification.h"
#import "PGTSHOM.h"
#import "PGTSCollections.h"
#import "BXEnumerate.h"
#import "NSURL+BaseTenAdditions.h"


/**
 * \brief An entity description contains information about a specific table or view in a given database.
 *
 * Only one entity description instance is created for a combination of a database
 * URI, a schema and a table.
 *
 * \note This class's documented methods are thread-safe. Creating objects, however, is not.
 * \note For this class to work in non-GC applications, the corresponding database context must be retained as well.
 * \ingroup descriptions
 */
@implementation BXEntityDescription
- (void) dealloc
{
	[mDatabaseURI release];
	[mSchemaName release];
	[mAttributes release];
	[mValidationLock release];
	[mObjectIDs release];
	[mRelationships release];
	
	[super dealloc];
}

/** 
 * \brief The schema name. 
 */
- (NSString *) schemaName
{
    return [[mSchemaName retain] autorelease];
}

/** 
 * \brief The database URI. 
 */
- (NSURL *) databaseURI
{
    return [[mDatabaseURI retain] autorelease];
}

- (id) initWithCoder: (NSCoder *) decoder
{
    NSString* name = [decoder decodeObjectForKey: @"name"];
	NSString* schemaName = [decoder decodeObjectForKey: @"schemaName"];
	NSURL* databaseURI = [decoder decodeObjectForKey: @"databaseURI"];

	if ((self = [self initWithDatabaseURI: databaseURI table: name inSchema: schemaName]))
	{
		Class cls = NSClassFromString ([decoder decodeObjectForKey: @"databaseObjectClassName"]);
		if (Nil != cls)
			[self setDatabaseObjectClass: cls];
		[self setAttributes: [decoder decodeObjectForKey: @"attributes"]];
	}
	return self;
}

- (void) encodeWithCoder: (NSCoder *) encoder
{
    [encoder encodeObject: mName forKey: @"name"];
    [encoder encodeObject: mSchemaName forKey: @"schemaName"];
    [encoder encodeObject: mDatabaseURI forKey: @"databaseURI"];
    [encoder encodeObject: NSStringFromClass (mDatabaseObjectClass) forKey: @"databaseObjectClassName"];
	[encoder encodeObject: mAttributes forKey: @"attributes"];
	//FIXME: relationships as well?
	[super encodeWithCoder: encoder];
}

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

- (BOOL) isEqual: (BXEntityDescription *) desc
{
    BOOL retval = NO;
    
    if (self == desc)
        retval = YES;
    else if ([super isEqual: desc])
	{		
		NSString* s1 = [self schemaName];
		NSString* s2 = [desc schemaName];
		
		if (! [s1 isEqualToString: s2])
			goto bail;
		
		NSURL* u1 = [self databaseURI];
		NSURL* u2 = [self databaseURI];
		
		if (! [u1 isEqual: u2])
			goto bail;
			
		retval = YES;
	}
bail:
    return retval;
}

- (unsigned int) hash
{
    return mHash;
}

- (NSString *) description
{
    return [NSString stringWithFormat: @"<%@ %@ (%p) validated: %d enabled: %d>", 
			mDatabaseURI, [self name], self, [self isValidated], [self isEnabled]];
}

/**
 * \brief Set the class for this entity.
 *
 * Objects fetched using this entity will be instances of
 * the given class, which needs to be a subclass of BXDatabaseObject.
 * \param   cls     The object class.
 * \note	If objects have been fetched from this entity before setting
 *          a class, those objects might be returned by subsequent
 *          fetches. It is best to set the class before connecting to the
 *          database.
 */
- (void) setDatabaseObjectClass: (Class) cls
{
	if (YES == [cls isSubclassOfClass: [BXDatabaseObject class]])
	{
		@synchronized (self)
		{
			mDatabaseObjectClass = cls;
		}
	}
	else
	{
		NSString* reason = [NSString stringWithFormat: @"Expected %@ to be a subclass of BXDatabaseObject.", cls];
		[NSException exceptionWithName: NSInternalInconsistencyException
								reason: reason userInfo: nil];
	}
}

/**
 * \brief The class for this entity.
 * \return          The default class is BXDatabaseObject.
 */
- (Class) databaseObjectClass
{
	id retval = nil;
	@synchronized (self)
	{
	    retval = mDatabaseObjectClass;
	}
	return retval;
}

/**
 * \brief Registered object IDs for this entity.
 */
- (NSArray *) objectIDs
{
	id retval = nil;
	@synchronized (mObjectIDs)
	{
		retval = [mObjectIDs allObjects];
	}
	return retval;
}

static int
FilterPkeyAttributes (id attribute, void* arg)
{
	int retval = 0;
	long shouldBePkey = (long) arg;
	if ([attribute isPrimaryKey] == shouldBePkey)
		retval = 1;
	return retval;
}

/**
 * \brief Primary key fields for this entity.
 *
 * The fields get determined automatically after database connection has been made.
 * \return          An array of BXAttributeDescriptions
 * \see #isValidated
 */
- (NSArray *) primaryKeyFields
{
	return [mAttributes PGTSValueSelectFunction: &FilterPkeyAttributes argument: (void *) 1L] ?: nil;
}
	
+ (NSSet *) keyPathsForValuesAffectingFields
{
	return [NSSet setWithObject: @"primaryKeyFields"];
}

/** 
 * \brief Non-primary key fields for this entity.
 * \return          An array of BXAttributeDescriptions
 * \see #isValidated
 */
- (NSArray *) fields
{
	return [mAttributes PGTSValueSelectFunction: &FilterPkeyAttributes argument: (void *) 0L] ?: nil;
}

/** 
 * \brief Whether this entity is marked as a view or not. 
 */
- (BOOL) isView
{
    return (mFlags & kBXEntityIsView) ? YES : NO;
}

- (NSComparisonResult) caseInsensitiveCompare: (BXEntityDescription *) anotherEntity
{
    NSComparisonResult retval = NSOrderedSame;
    if (self != anotherEntity)
    {
        retval = [[self schemaName] caseInsensitiveCompare: [anotherEntity schemaName]];
        if (NSOrderedSame == retval)
        {
            retval = [[self name] caseInsensitiveCompare: [anotherEntity name]];
        }
    }
    return retval;
}

/** 
 * \brief Attributes for this entity.
 *
 * Primary key fields and other fields for this entity.
 * \return          An NSDictionary with NSStrings as keys and BXAttributeDescriptions as objects.
 * \see #isValidated
 */
- (NSDictionary *) attributesByName
{
	return [[mAttributes retain] autorelease];
}

/**
 * \brief Entity validation.
 *
 * The entity will be validated after a database connection has been made. Afterwards, 
 * #fields, #primaryKeyFields, #attributesByName and #relationshipsByName return meaningful values.
 *
 * \note To call this safely, \em mValidationLock should be acquired first. Our validation methods do this, though.
 */
//FIXME: should we have a separate variable for validation status?
- (BOOL) isValidated
{
	return (mFlags & kBXEntityIsValidated) ? YES : NO;
}

/**
 * \brief Relationships for this entity.
 * \return An NSDictionary with NSStrings as keys and BXRelationshipDescriptions as objects.
 */
- (NSDictionary *) relationshipsByName
{
	if (! [self hasCapability: kBXEntityCapabilityRelationships])
		[NSException raise: NSInvalidArgumentException format: @"Entity %@ doesn't have relationship capability. (BaseTen enabling is required for this.)", self];
	return [[mRelationships retain] autorelease];
}

- (BOOL) hasCapability: (enum BXEntityCapability) aCapability
{
	return (mCapabilities & aCapability ? YES : NO);
}

/** 
 * \brief Whether this entity has been BaseTen enabled or not.
 */
- (BOOL) isEnabled
{
	return (mFlags & kBXEntityIsEnabled) ? YES : NO;
}

- (void) viewGetsUpdatedWith: (NSArray *) entities
{
	BXAssertVoidReturn ([self isView], @"Expected entity %@ to be a view.", self);
	[self inherits: entities];
}

- (id) viewsUpdated
{
	BXAssertValueReturn ([self isView], nil, @"Expected entity %@ to be a view.", self);
	return [self inheritedEntities];
}

- (void) inherits: (NSArray *) entities
{
    @synchronized (mSuperEntities)
    {
        //FIXME: We only implement cascading notifications from "root tables" to inheriting tables and not vice-versa.
        //FIXME: only single entity supported for now.
        BXAssertVoidReturn (0 == [mSuperEntities count], @"Expected inheritance/dependant relations not to have been set.");
        BXAssertVoidReturn (1 == [entities count], @"Multiple inheritance/dependant relations is not supported.");
        BXEnumerate (currentEntity, e, [entities objectEnumerator])
        {
            [mSuperEntities addObject: currentEntity];
            [currentEntity addSubEntity: self];
        }
    }
}

- (void) addSubEntity: (BXEntityDescription *) entity
{
    @synchronized (mSubEntities)
    {
        //FIXME: We only implement cascading notifications from "root tables" to inheriting tables and not vice-versa.
        [mSubEntities addObject: entity];
    }
}

- (id) inheritedEntities
{
    id retval = nil;
    @synchronized (mSuperEntities)
    {
        retval = [mSuperEntities allObjects];
    }
    return retval;
}

- (id) subEntities
{
    id retval = nil;
    @synchronized (mSubEntities)
    {
        retval = [mSubEntities allObjects];
    }
    return retval;
}

/**
 * \internal
 * \brief Whether this entity gets changed by triggers, rules etc.
 *
 * If the entity gets changed only directly, some queries may possibly be optimized.
 */
- (BOOL) getsChangedByTriggers
{
	return mFlags & kBXEntityGetsChangedByTriggers ? YES : NO;
}

- (void) setGetsChangedByTriggers: (BOOL) flag
{
	if (flag)
		mFlags |= kBXEntityGetsChangedByTriggers;
	else
		mFlags &= ~kBXEntityGetsChangedByTriggers;
}
@end


@implementation BXEntityDescription (PrivateMethods)
/**
 * \internal
 * \brief The designated initializer.
 *
 * Create the entity.
 * \param       anURI   The database URI
 * \param       tName   Table name
 * \param       sName   Schema name
 */
- (id) initWithDatabaseURI: (NSURL *) anURI table: (NSString *) tName inSchema: (NSString *) sName
{
	BXAssertValueReturn (nil != sName, nil, @"Expected sName not to be nil.");
	BXAssertValueReturn (nil != anURI, nil, @"Expected anURI to be set.");
	
    if ((self = [super initWithName: tName]))
    {
        mDatabaseObjectClass = [BXDatabaseObject class];
        mDatabaseURI = [anURI copy];
        mSchemaName = [sName copy];
		
		mObjectIDs = PGTSSetCreateMutableWeakNonretaining ();
        mSuperEntities = PGTSSetCreateMutableWeakNonretaining ();
        mSubEntities = PGTSSetCreateMutableWeakNonretaining ();
		
		mValidationLock = [[NSLock alloc] init];
		mHash = ([super hash] ^ [mSchemaName hash] ^ [mDatabaseURI BXHash]);
    }
    return self;
}

- (id) init
{
	[self doesNotRecognizeSelector: _cmd];
    return nil;
}

- (id) initWithName: (NSString *) aName
{
	[self doesNotRecognizeSelector: _cmd];
    return nil;
}
//@}

- (void) registerObjectID: (BXDatabaseObjectID *) anID
{
	@synchronized (mObjectIDs)
	{
		BXAssertVoidReturn ([anID entity] == self, 
							  @"Attempted to register an object ID the entity of which is other than self.\n"
							  "\tanID:\t%@ \n\tself:\t%@", anID, self);
		if (self == [anID entity])
			[mObjectIDs addObject: anID];
	}
}

- (void) unregisterObjectID: (BXDatabaseObjectID *) anID
{
	@synchronized (mObjectIDs)
	{
		[mObjectIDs removeObject: anID];
	}
}

//Not thread-safe.
- (void) setAttributes: (NSDictionary *) attributes
{
	if (attributes != mAttributes)
	{
		[mAttributes release];
		mAttributes = [attributes copy];
	}
}

- (void) resetAttributeExclusion
{
	[[mAttributes PGTSDo] resetAttributeExclusion];
}

- (NSArray *) attributes: (NSArray *) strings
{
	return [mAttributes objectsForKeys: strings notFoundMarker: [NSNull null]];
}

- (void) setValidated: (BOOL) flag
{
	if (flag)
		mFlags |= kBXEntityIsValidated;
	else
		mFlags &= ~kBXEntityIsValidated;
}

- (void) setIsView: (BOOL) flag
{
	if (flag)
		mFlags |= kBXEntityIsView;
	else
		mFlags &= ~kBXEntityIsView;
}

//Not thread-safe.
- (void) setRelationships: (NSDictionary *) aDict
{
	if (mRelationships != aDict)
	{
		[mRelationships release];
		mRelationships = [aDict copy];
	}
}

- (void) setHasCapability: (enum BXEntityCapability) aCapability to: (BOOL) flag
{
	if (flag)
		mCapabilities |= aCapability;
	else
		mCapabilities &= ~aCapability;
}

- (void) setEnabled: (BOOL) flag
{
	if (flag)
		mFlags |= kBXEntityIsEnabled;
	else
		mFlags &= ~kBXEntityIsEnabled;
}

static int
InverseToOneRelationships (id arg)
{
	int retval = 0;
	BXRelationshipDescription* relationship = (BXRelationshipDescription *) arg;
	if ([relationship isInverse] && ! [relationship isToMany])
		retval = 1;
	return retval;
}


- (id) inverseToOneRelationships;
{
	return [mRelationships PGTSValueSelectFunction: &InverseToOneRelationships];
}

- (BOOL) beginValidation
{
	BOOL locked = [mValidationLock tryLock];
	if (locked && [self isValidated])
	{
		[mValidationLock unlock];
		locked = NO;
	}
	return locked;
}

- (void) endValidation
{
	if ([self hasCapability: kBXEntityCapabilityRelationships])
	{
		BXEnumerate (currentRelationship, e, [[self relationshipsByName] objectEnumerator])
			[currentRelationship makeAttributeDependency];
	}
	[mValidationLock unlock];
}
@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.