baseten / Sources / PGTSMetadataContainer.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
//
// PGTSMetadataContainer.m
// BaseTen
//
// Copyright (C) 2009 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 "PGTSMetadataContainer.h"
#import "PGTSMetadataStorage.h"
#import "BXLogger.h"
#import "PGTSConnection.h"
#import "PGTSResultSet.h"
#import "PGTSDatabaseDescription.h"
#import "PGTSSchemaDescription.h"
#import "PGTSTypeDescription.h"
#import "PGTSTableDescription.h"
#import "PGTSColumnDescription.h"
#import "PGTSIndexDescription.h"
#import "PGTSRoleDescription.h"
#import "PGTSOids.h"
#import "BXEnumerate.h"



@implementation PGTSMetadataContainer
- (id) initWithStorage: (PGTSMetadataStorage *) storage key: (NSURL *) key
{
	if ((self = [super init]))
	{
		mStorage = [storage retain];
		mStorageKey = [key retain];
	}
	return self;
}

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

- (void) dealloc
{
	[mStorage containerWillDeallocate: mStorageKey];
	[mStorage release];
	[mStorageKey release];
	[mDatabase release];
	[super dealloc];
}

- (Class) databaseDescriptionClass
{
	return [PGTSDatabaseDescription class];
}

- (Class) tableDescriptionClass
{
	return [PGTSTableDescription class];
}

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

- (void) prepareForConnection: (PGTSConnection *) connection;
{
	[self doesNotRecognizeSelector: _cmd];
}

- (void) reloadUsingConnection: (PGTSConnection *) connection
{
	[self doesNotRecognizeSelector: _cmd];
}
@end



@implementation PGTSEFMetadataContainer
//FIXME: come up with a better way to handle query problems than ExpectV.
- (void) fetchTypes: (PGTSConnection *) connection
{
	ExpectV (connection);
	NSString* query = 
	@"SELECT t.oid, typname, typnamespace, typelem, typdelim, typtype, typlen "
	@" FROM pg_type t ";
	PGTSResultSet* res = [connection executeQuery: query];
	ExpectV ([res querySucceeded]);
	
	{
		[res setDeterminesFieldClassesAutomatically: NO];
		//Oid is parsed manually.
		[res setClass: [NSString class] forKey: @"typname"];
		[res setClass: [NSNumber class] forKey: @"typnamespace"];
		[res setClass: [NSNumber class] forKey: @"typelem"];
		[res setClass: [NSString class] forKey: @"typdelim"];
		[res setClass: [NSString class] forKey: @"typtype"];
		[res setClass: [NSNumber class] forKey: @"typlen"];
		
		while ([res advanceRow])
		{
			PGTSTypeDescription* type = [[[PGTSTypeDescription alloc] init] autorelease];
			
			//Oid needs to be parsed manually to prevent infinite recursion.
			//The type description of Oid might not be cached yet.
			char* oidString = PQgetvalue ([res PGresult], [res currentRow], 0);
			long oid = strtol (oidString, NULL, 10);
			[type setOid: oid];
			
			[type setName: [res valueForKey: @"typname"]];
			[type setElementOid: [[res valueForKey: @"typelem"] PGTSOidValue]];
			unichar delimiter = [[res valueForKey: @"typdelim"] characterAtIndex: 0];
			ExpectV (delimiter <= UCHAR_MAX);
			[type setDelimiter: delimiter];
			unichar kind = [[res valueForKey: @"typtype"] characterAtIndex: 0];
			ExpectV (kind <= UCHAR_MAX);
			[type setKind: kind];
			NSInteger length = [[res valueForKey: @"typlen"] integerValue];
			[type setLength: length];
			
			[type setSchema: [mDatabase schemaWithOid: [[res valueForKey: @"typnamespace"] PGTSOidValue]]];
			
			[mDatabase addType: type];
		}		
	}
}


- (void) fetchSchemas: (PGTSConnection *) connection
{
	ExpectV (connection);
	NSString* query = 
	@"SELECT oid, nspname "
	@" FROM pg_namespace "
	@" WHERE nspname NOT IN ('information_schema', 'baseten') AND "
	@"  nspname NOT LIKE 'pg_%'";
	PGTSResultSet* res = [connection executeQuery: query];
	ExpectV ([res querySucceeded]);
	
	{
		while ([res advanceRow])
		{
			PGTSSchemaDescription* schema = [[[PGTSSchemaDescription alloc] init] autorelease];
			NSNumber* oid = [res valueForKey: @"oid"];
			[schema setOid: [oid PGTSOidValue]];
			[schema setName: [res valueForKey: @"nspname"]];
			
			[mDatabase addSchema: schema];
		}
	}
}


- (void) fetchRoles: (PGTSConnection *) connection
{
	ExpectV (connection);

	//We could easily fetch login, connection limit etc. privileges here.
	NSString* query =
	@"SELECT oid, rolname "
	@" FROM pg_roles ";
	PGTSResultSet* res = [connection executeQuery: query];
	ExpectV ([res querySucceeded]);
	
	{
		while ([res advanceRow]) 
		{
			PGTSRoleDescription* role = [[[PGTSRoleDescription alloc] init] autorelease];
			NSNumber* oid = [res valueForKey: @"oid"];
			[role setOid: [oid PGTSOidValue]];
			[role setName: [res valueForKey: @"rolname"]];
			
			[mDatabase addRole: role];
		}
	}
	
	query = 
	@"SELECT roleid, member "
	@" FROM pg_auth_members ";
	res = [connection executeQuery: query];
	
	{
		while ([res advanceRow])
		{
			Oid roleOid = [[res valueForKey: @"roleid"] PGTSOidValue];
			Oid memberOid = [[res valueForKey: @"member"] PGTSOidValue];
			PGTSRoleDescription* role = [mDatabase roleWithOid: roleOid];
			PGTSRoleDescription* member = [mDatabase roleWithOid: memberOid];
			[role addMember: member];
		}
	}
}


- (void) fetchRelations: (PGTSConnection *) connection
{
	ExpectV (connection);
	NSString* query = 
	@"SELECT c.oid, c.relnamespace, c.relname, c.relkind, c.relacl, c.relowner "
	@" FROM pg_class c "
	@" INNER JOIN pg_namespace n ON c.relnamespace = n.oid "
	@" WHERE c.relkind IN ('r', 'v') AND "
	@"  n.nspname NOT IN ('information_schema', 'baseten') AND "
	@"  n.nspname NOT LIKE 'pg_%'";
	PGTSResultSet* res = [connection executeQuery: query];
	ExpectV ([res querySucceeded]);
	
	{
		while ([res advanceRow]) 
		{
			PGTSTableDescription* table = [[[[self tableDescriptionClass] alloc] init] autorelease];
			[table setOid: [[res valueForKey: @"oid"] PGTSOidValue]];
			[table setName: [res valueForKey: @"relname"]];
			unichar kind = [[res valueForKey: @"relkind"] characterAtIndex: 0];
			ExpectV (kind <= UCHAR_MAX);
			[table setKind: kind];
			[table setACL: [res valueForKey: @"relacl"]];
			
			[table setOwner: [mDatabase roleWithOid: [[res valueForKey: @"relowner"] PGTSOidValue]]];
			[table setSchema: [mDatabase schemaWithOid: [[res valueForKey: @"relnamespace"] PGTSOidValue]]];
			
			[mDatabase addTable: table];
		}
	}
}


- (void) fetchInheritance: (PGTSConnection *) connection
{
	ExpectV (connection);
	NSString* query =
	@"SELECT inhrelid, inhparent FROM pg_inherits ORDER BY inhrelid, inhseqno";
	PGTSResultSet* res = [connection executeQuery: query];
	ExpectV ([res querySucceeded]);
	
	{
		while ([res advanceRow])
		{
			Oid currentOid = [[res valueForKey: @"inhrelid"] PGTSOidValue];
			PGTSTableDescription* table = [mDatabase tableWithOid: currentOid];
			if (table)
			{
				Oid parentOid = [[res valueForKey: @"inhparent"] PGTSOidValue];
				[table addInheritedOid: parentOid];
			}
		}
	}
}


- (void) fetchColumns: (PGTSConnection *) connection
{
	ExpectV (connection);
	
	{
		NSString* query = 
		@"SELECT a.attrelid, a.attname, a.attnum, a.atttypid, a.attnotnull, a.attinhcount, pg_get_expr (d.adbin, d.adrelid, false) AS default "
		@" FROM pg_attribute a "
		@" INNER JOIN pg_class c ON a.attrelid = c.oid "
		@" INNER JOIN pg_namespace n ON n.oid = c.relnamespace "
		@" LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid and a.attnum = d.adnum "
		@" WHERE a.attisdropped = false AND "
		@"  c.relkind IN ('r', 'v') AND "
		@"  n.nspname NOT IN ('information_schema', 'baseten') AND "
		@"  n.nspname NOT LIKE 'pg_%'";
		
		PGTSResultSet* res = [connection executeQuery: query];
		ExpectV ([res querySucceeded]);
		
		while ([res advanceRow])
		{
			Oid typeOid = [[res valueForKey: @"atttypid"] PGTSOidValue];
			Oid relid = [[res valueForKey: @"attrelid"] PGTSOidValue];
			NSInteger inhcount = [[res valueForKey: @"attinhcount"] integerValue];
			PGTSTypeDescription* type = [mDatabase typeWithOid: typeOid];
			PGTSColumnDescription* column = nil;
			if ([@"xml" isEqualToString: [type name]])
				column = [[[PGTSXMLColumnDescription alloc] init] autorelease];
			else
				column = [[[PGTSColumnDescription alloc] init] autorelease];
			
			[column setType: type];
			[column setName: [res valueForKey: @"attname"]];
			[column setIndex: [[res valueForKey: @"attnum"] integerValue]];
			[column setNotNull: [[res valueForKey: @"attnotnull"] boolValue]];
			[column setInherited: (0 == inhcount ? NO : YES)];
			[column setDefaultValue: [res valueForKey: @"default"]];
			//FIXME: mark inherited columns.
			
			[[mDatabase tableWithOid: relid] addColumn: column];
		}
	}
	
	{
		//Fetch some column-specific constraints.
		//We can't determine whether a column accepts only XML document from its type.
		//Instead, we have to look for a constraint like 'CHECK ((column) IS DOCUMENT)'
		//or 'CHECK ("Column" IS DOCUMENT)'. We do this by comparing the constraint 
		//definition to an expression, where a number of parentheses is allowed around 
		//its parts. We use the reconstructed constraint instead of what the user wrote.
		NSString* query =
		@"SELECT conrelid, conkey "
		@"FROM ( "
		@"  SELECT c.conrelid, c.conkey [1], a.attname, "
		@"    regexp_matches (pg_get_constraintdef (c.oid, false), "
		@"	    '^CHECK ?[(]+(?:\"([^\"]+)\")|([^( ][^ )]*)[ )]+IS DOCUMENT[ )]+$' "
		@"    ) AS matches "
		@"  FROM pg_constraint c "
		@"  INNER JOIN pg_attribute a ON (c.conrelid = a.attrelid AND c.conkey [1] = a.attnum) "
		@"  INNER JOIN pg_type t ON (t.oid = a.atttypid AND t.typname = 'xml') "
		@"	WHERE c.contype = 'c' AND 1 = array_upper (c.conkey, 1) "
		@") c "
		@"WHERE attname = ANY (matches)";
		PGTSResultSet* res = [connection executeQuery: query];
		ExpectV ([res querySucceeded])
		
		while ([res advanceRow])
		{
			Oid relid = [[res valueForKey: @"conrelid"] PGTSOidValue];
			NSInteger attnum = [[res valueForKey: @"conkey"] integerValue];
			[[[mDatabase tableWithOid: relid] columnAtIndex: attnum] setRequiresDocuments: YES];
		}
	}
}


- (void) fetchUniqueIndexes: (PGTSConnection *) connection
{
	ExpectV (connection);
	//indexrelid is oid of the index, indrelid of the table.
	NSString* query = 
	@"SELECT i.indexrelid, i.indrelid, c.relname, i.indisprimary, i.indkey::INTEGER[] "
	@" FROM pg_index i "
	@" INNER JOIN pg_class c ON i.indexrelid = c.oid "
	@" INNER JOIN pg_namespace n ON c.relnamespace = n.oid "
	@" WHERE i.indisunique = true AND "
	@"  n.nspname NOT IN ('information_schema', 'baseten') AND "
	@"  n.nspname NOT LIKE 'pg_%' "
	@" ORDER BY i.indrelid ASC, i.indisprimary DESC";
	PGTSResultSet* res = [connection executeQuery: query];
	ExpectV ([res querySucceeded]);

	while ([res advanceRow]) 
	{
		PGTSIndexDescription* index = [[[PGTSIndexDescription alloc] init] autorelease];
		PGTSTableDescription* table = [mDatabase tableWithOid: [[res valueForKey: @"indrelid"] PGTSOidValue]];
		
		[index setName: [res valueForKey: @"relname"]];
		[index setOid: [[res valueForKey: @"indexrelid"] PGTSOidValue]];
		[index setPrimaryKey: [[res valueForKey: @"indisprimary"] boolValue]];

		NSArray* indices = [res valueForKey: @"indkey"];
		NSMutableSet* columns = [NSMutableSet setWithCapacity: [indices count]];
		BXEnumerate (currentIndex, e, [indices objectEnumerator])
		{
			NSInteger i = [currentIndex integerValue];
			if (0 < i)
			{
				id column = [table columnAtIndex: i];
				ExpectV (column);
				[columns addObject: column];
			}
		}
		[index setColumns: columns];
		
		[table addIndex: index];
	}
}


- (id) databaseDescription
{
	id retval = nil;
	@synchronized (self)
	{
		retval = [[mDatabase retain] autorelease];
	}
	return retval;
}


- (void) loadUsing: (PGTSConnection *) connection
{
	[mDatabase release];
	mDatabase = [[[self databaseDescriptionClass] alloc] init];
	
	//Order is important.
	[self fetchTypes: connection];
	[self fetchSchemas: connection];
	[self fetchRoles: connection];
	[self fetchRelations: connection];
	[self fetchInheritance: connection];
	[self fetchColumns: connection];
	[self fetchUniqueIndexes: connection];	
}


- (void) prepareForConnection: (PGTSConnection *) connection
{
	@synchronized (self)
	{
		if (! mDatabase)
			[self loadUsing: connection];
	}
}


- (void) reloadUsingConnection: (PGTSConnection *) connection
{
	@synchronized (self)
	{
		[self loadUsing: connection];
	}
}
@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.