]> err.no Git - scalable-opengroupware.org/blob - SOGo/SoObjects/SOGo/AgenorUserDefaults.m
implemented profile saving
[scalable-opengroupware.org] / SOGo / SoObjects / SOGo / AgenorUserDefaults.m
1 /*
2   Copyright (C) 2005 SKYRIX Software AG
3
4   This file is part of OpenGroupware.org.
5
6   OGo is free software; you can redistribute it and/or modify it under
7   the terms of the GNU Lesser General Public License as published by the
8   Free Software Foundation; either version 2, or (at your option) any
9   later version.
10
11   OGo is distributed in the hope that it will be useful, but WITHOUT ANY
12   WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
14   License for more details.
15
16   You should have received a copy of the GNU Lesser General Public
17   License along with OGo; see the file COPYING.  If not, write to the
18   Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19   02111-1307, USA.
20 */
21
22 #include "AgenorUserDefaults.h"
23 #include <GDLContentStore/GCSChannelManager.h>
24 #include <GDLContentStore/NSURL+GCS.h>
25 #include <GDLAccess/EOAdaptorChannel.h>
26 #include <GDLAccess/EOAdaptorContext.h>
27 #include <GDLAccess/EOAttribute.h>
28 #include "common.h"
29
30 @implementation AgenorUserDefaults
31
32 static NSString *uidColumnName = @"uid";
33
34 - (id)initWithTableURL:(NSURL *)_url uid:(NSString *)_uid {
35   if ((self = [super init])) {
36     if (_url == nil || [_uid length] < 1) {
37       [self errorWithFormat:@"tried to create AgenorUserDefaults w/o args!"];
38       [self release];
39       return nil;
40     }
41
42     self->parent = [[NSUserDefaults standardUserDefaults] retain];
43     self->url = [_url copy];
44     self->uid = [_uid copy];
45   }
46   return self;
47 }
48 - (id)init {
49   return [self initWithTableURL:nil uid:nil];
50 }
51
52 - (void)dealloc {
53   [self->attributes release];
54   [self->lastFetch  release];
55   [self->parent     release];
56   [self->url        release];
57   [self->uid        release];
58   [super dealloc];
59 }
60
61 /* accessors */
62
63 - (NSURL *)tableURL {
64   return self->url;
65 }
66 - (NSString *)uid {
67   return self->uid;
68 }
69
70 - (NSUserDefaults *)parentDefaults {
71   return self->parent;
72 }
73
74 /* operation */
75
76 - (void)_loadAttributes:(NSArray *)_attrs {
77   NSMutableArray      *fields;
78   NSMutableDictionary *attrmap;
79   unsigned i, count;
80   
81   fields  = [[NSMutableArray      alloc] initWithCapacity:16];
82   attrmap = [[NSMutableDictionary alloc] initWithCapacity:16];
83   for (i = 0, count = [_attrs count]; i < count; i++) {
84     EOAttribute *attr;
85     NSString    *name;
86     
87     attr = [_attrs objectAtIndex:i];
88     name = [attr valueForKey:@"name"];
89     [attrmap setObject:attr forKey:name];
90     
91     if (![name isEqual:uidColumnName]) 
92       [fields  addObject:name];
93   }
94   
95   ASSIGNCOPY(self->fieldNames, fields);
96   ASSIGNCOPY(self->attributes, attrmap);
97   [attrmap release];
98   [fields  release];
99 }
100
101 - (BOOL)primaryFetchProfile {
102   GCSChannelManager *cm;
103   EOAdaptorChannel  *channel;
104   NSDictionary      *row;
105   NSException       *ex;
106   NSString          *sql;
107   NSArray           *attrs;
108   
109   cm = [GCSChannelManager defaultChannelManager];
110   if ((channel = [cm acquireOpenChannelForURL:[self tableURL]]) == nil) {
111     [self errorWithFormat:@"failed to acquire channel for URL: %@", 
112           [self tableURL]];
113     return NO;
114   }
115   
116   /* generate SQL */
117   
118   sql = [[self tableURL] gcsTableName];
119   sql = [@"SELECT * FROM " stringByAppendingString:sql];
120   sql = [sql stringByAppendingFormat:@" WHERE %@ = '%@'", 
121              uidColumnName, [self uid]];
122   
123   /* run SQL */
124   
125   if ((ex = [channel evaluateExpressionX:sql]) != nil) {
126     [self errorWithFormat:@"could not run SQL '%@': %@", sql, ex];
127     [cm releaseChannel:channel];
128     return NO;
129   }
130
131   /* fetch schema */
132   
133   attrs = [channel describeResults:NO /* don't beautify */];
134   [self _loadAttributes:attrs];
135   
136   /* fetch values */
137   
138   row = [channel fetchAttributes:attrs withZone:NULL];
139   [channel cancelFetch];
140   
141   /* remember values */
142   
143   [self->values release]; self->values = nil;
144   if (row != nil)
145     self->values = [row mutableCopy];
146   else
147     self->values = [[NSMutableDictionary alloc] initWithCapacity:8];
148   [self->values removeObjectForKey:uidColumnName];
149   
150   ASSIGN(self->lastFetch, [NSCalendarDate date]);
151   self->defFlags.modified = 0;
152   
153   [cm releaseChannel:channel];
154   return YES;
155 }
156
157 - (NSString *)generateSQLForUpdate {
158   NSMutableString *sql;
159   unsigned i, count;
160   
161   if ([self->values count] == 0)
162     return nil;
163   
164   sql = [NSMutableString stringWithCapacity:2048];
165   
166   [sql appendString:@"UPDATE "];
167   [sql appendString:[[self tableURL] gcsTableName]];
168   [sql appendString:@" SET "];
169   
170   for (i = 0, count = [self->fieldNames count]; i < count; i++) {
171     EOAttribute *attr;
172     NSString    *name;
173     id value;
174     
175     name  = [self->fieldNames objectAtIndex:i];
176     value = [self->values objectForKey:name];
177     attr  = [self->attributes objectForKey:name];
178     
179     if (i != 0) [sql appendString:@", "];
180     [sql appendString:[attr columnName]];
181     
182     if ([value isNotNull]) {
183       /* a rather limited set of supported value types */
184       
185       if ([[attr externalType] hasPrefix:@"int"])
186         [sql appendFormat:@" = %i", [value intValue]];
187       else {
188         // TODO: any other escaping?! move to adaptor?
189         value = [value stringValue];
190         value = [value stringByReplacingString:@"'" withString:@"''"];
191         [sql appendString:@" = '"];
192         [sql appendString:value];
193         [sql appendString:@"'"];
194       }
195     }
196     else
197       [sql appendString:@" = NULL"];
198   }
199   
200   [sql appendString:@" WHERE "];
201   [sql appendString:uidColumnName];
202   [sql appendString:@" = '"];
203   [sql appendString:[self uid]];
204   [sql appendString:@"'"];
205   return sql;
206 }
207
208 - (BOOL)primaryStoreProfile {
209   GCSChannelManager *cm;
210   EOAdaptorChannel  *channel;
211   NSException       *ex;
212   NSString          *sql;
213   
214   cm = [GCSChannelManager defaultChannelManager];
215   if ((channel = [cm acquireOpenChannelForURL:[self tableURL]]) == nil) {
216     [self errorWithFormat:@"failed to acquire channel for URL: %@", 
217           [self tableURL]];
218     return NO;
219   }
220   
221   /* run SQL */
222   
223   sql = [self generateSQLForUpdate];
224   if ((ex = [channel evaluateExpressionX:sql]) != nil) {
225     [self errorWithFormat:@"could not run SQL '%@': %@", sql, ex];
226     [cm releaseChannel:channel];
227     return NO;
228   }
229   
230   /* commit */
231   
232   ex = nil;
233   if ([[channel adaptorContext] hasOpenTransaction])
234     ex = [channel evaluateExpressionX:@"COMMIT TRANSACTION"];
235   
236   [cm releaseChannel:channel];
237   
238   if (ex != nil) {
239     [self errorWithFormat:@"could not commit transaction for update: %@", ex];
240     return NO;
241   }
242   
243   self->defFlags.modified = 0;
244   return YES;
245 }
246
247
248 - (BOOL)fetchProfile {
249   if (self->values != nil)
250     return YES;
251   
252   return [self primaryFetchProfile];
253 }
254
255 - (NSArray *)primaryDefaultNames {
256   if (![self fetchProfile])
257     return nil;
258   
259   return self->fieldNames;
260 }
261
262 /* value access */
263
264 - (void)setObject:(id)_value forKey:(NSString *)_key {
265   if (![self fetchProfile])
266     return;
267   
268   if (![self->fieldNames containsObject:_key]) {
269     [self errorWithFormat:@"tried to write key: '%@'", _key];
270     return;
271   }
272   
273   /* check whether the value is actually modified */
274   if (!self->defFlags.modified) {
275     id old;
276
277     old = [self->values objectForKey:_key];
278     if (old == _value || [old isEqual:_value]) /* value didn't change */
279       return;
280   
281     /* we need to this because our typed accessors convert to strings */
282     // TODO: especially problematic with bools
283     if ([_value isKindOfClass:[NSString class]]) {
284       if (![old isKindOfClass:[NSString class]])
285         if ([[old description] isEqualToString:_value])
286         return;
287     }
288   }
289   
290   /* set in hash and mark as modified */
291   [self->values setObject:(_value ? _value : [NSNull null])  forKey:_key];
292   self->defFlags.modified = 1;
293 }
294
295 - (id)objectForKey:(NSString *)_key {
296   id value;
297   
298   if (![self fetchProfile])
299     return nil;
300   
301   if (![self->fieldNames containsObject:_key])
302     return [self->parent objectForKey:_key];
303   
304   value = [self->values objectForKey:_key];
305   return [value isNotNull] ? value : nil;
306 }
307
308 - (void)removeObjectForKey:(NSString *)_key {
309   [self setObject:nil forKey:_key];
310 }
311
312 /* saving changes */
313
314 - (BOOL)synchronize {
315   if (!self->defFlags.modified) /* was not modified */
316     return YES;
317   
318   /* ensure fetched data (more or less guaranteed by modified!=0) */
319   if (![self fetchProfile])
320     return NO;
321   
322   /* store */
323   if (![self primaryStoreProfile]) {
324     [self primaryFetchProfile];
325     return NO;
326   }
327   
328   /* refetch */
329   return [self primaryFetchProfile];
330 }
331
332 - (void)flush {
333   [self->values     release]; self->values     = nil;
334   [self->fieldNames release]; self->fieldNames = nil;
335   [self->attributes release]; self->attributes = nil;
336   [self->lastFetch  release]; self->lastFetch  = nil;
337   self->defFlags.modified = 0;
338 }
339
340 /* typed accessors */
341
342 - (NSArray *)arrayForKey:(NSString *)_key {
343   id obj = [self objectForKey:_key];
344   return [obj isKindOfClass:[NSArray class]] ? obj : nil;
345 }
346
347 - (NSDictionary *)dictionaryForKey:(NSString *)_key {
348   id obj = [self objectForKey:_key];
349   return [obj isKindOfClass:[NSDictionary class]] ? obj : nil;
350 }
351
352 - (NSData *)dataForKey:(NSString *)_key {
353   id obj = [self objectForKey:_key];
354   return [obj isKindOfClass:[NSData class]] ? obj : nil;
355 }
356
357 - (NSArray *)stringArrayForKey:(NSString *)_key {
358   id obj = [self objectForKey:_key];
359   int n;
360   Class strClass = [NSString class];
361   
362   if (![obj isKindOfClass:[NSArray class]])
363     return nil;
364         
365   for (n = [obj count]-1; n >= 0; n--) {
366     if (![[obj objectAtIndex:n] isKindOfClass:strClass])
367       return nil;
368   }
369   return obj;
370 }
371
372 - (NSString *)stringForKey:(NSString *)_key {
373   id obj = [self objectForKey:_key];
374   return [obj isKindOfClass:[NSString class]] ? obj : nil;
375 }
376
377 - (BOOL)boolForKey:(NSString *)_key {
378   // TODO: need special support here for int-DB fields
379   id obj;
380   
381   if ((obj = [self objectForKey:_key]) == nil)
382     return NO;
383   if ([obj isKindOfClass:[NSString class]]) {
384     if ([obj compare:@"YES" options:NSCaseInsensitiveSearch] == NSOrderedSame)
385       return YES;
386   }
387   if ([obj respondsToSelector:@selector(intValue)])
388     return [obj intValue] ? YES : NO;
389   return NO;
390 }
391
392 - (float)floatForKey:(NSString *)_key {
393   id obj = [self stringForKey:_key];
394   return (obj != nil) ? [obj floatValue] : 0.0;
395 }
396 - (int)integerForKey:(NSString *)_key {
397   id obj = [self stringForKey:_key];
398   return (obj != nil) ? [obj intValue] : 0;
399 }
400
401 - (void)setBool:(BOOL)value forKey:(NSString *)_key {
402   // TODO: need special support here for int-DB fields
403   [self setObject:(value ? @"YES" : @"NO") forKey:_key];
404 }
405 - (void)setFloat:(float)value forKey:(NSString *)_key {
406   [self setObject:[NSString stringWithFormat:@"%f", value] forKey:_key];
407 }
408 - (void)setInteger:(int)value forKey:(NSString *)_key {
409   [self setObject:[NSString stringWithFormat:@"%d", value] forKey:_key];
410 }
411
412 /* description */
413
414 - (NSString *)description {
415   NSMutableString *ms;
416   
417   ms = [NSMutableString stringWithCapacity:16];
418   [ms appendFormat:@"<0x%08X[%@]>", self, NSStringFromClass([self class])];
419   [ms appendFormat:@" uid=%@",        self->uid];
420   [ms appendFormat:@" url=%@",        [self->url absoluteString]];
421   [ms appendFormat:@" parent=0x%08X", self->parent];
422   [ms appendString:@">"];
423   return ms;
424 }
425
426 @end /* AgenorUserDefaults */