I'm looking for a quick way to debug my SQLite queries in an iOS app. I have something like this:
NSString *sql = [NSString stringWithString: @"SELECT * FROM table WHERE foo = ? AND bar = ?"];
NSArray *params = [NSArray arrayWithObjects: @"baz", @"bat", nil];
NSLog(@"%@ %@", sql, params);
I'd like to know if there is a one or two-liner to replace the question marks with the params to make the output more readable. I'm not looking for something that outputs valid sql but rather something easier to read than my current NSLog.
@interface NSString (SQLQueryDebugging)
- (NSString *)stringBySubstitutingParameters:(NSArray *)params forInstancesOfPlaceholder:(NSString *)placeholder;
@end
@implementation NSString (SQLQueryDebugging)
- (NSString *)stringBySubstitutingParameters:(NSArray *)params forInstancesOfPlaceholder:(NSString *)placeholder
{
NSString *composedQuery = self;
NSRange substitutionRange = [composedQuery rangeOfString:placeholder];
NSInteger parameterIndex = 0;
while(substitutionRange.length != 0)
{
NSString *currentParam = [params objectAtIndex:parameterIndex];
composedQuery = [composedQuery stringByReplacingCharactersInRange:substitutionRange withString:currentParam];
++parameterIndex;
NSInteger lastSubstitutionIndex = substitutionRange.location + [currentParam length];
NSRange searchRange = NSMakeRange(lastSubstitutionIndex, [composedQuery length] - lastSubstitutionIndex);
substitutionRange = [composedQuery rangeOfString:placeholder options:0 range:searchRange];
}
return composedQuery;
}
Drop that in somewhere, then you can get what you want with:
NSString *completeSQL = [sql stringBySubstitutingParameters:params forInstancesOfPlaceholder:@"?"];