diff --git a/Clocker.xcodeproj/project.pbxproj b/Clocker.xcodeproj/project.pbxproj index 939a169..c237401 100755 --- a/Clocker.xcodeproj/project.pbxproj +++ b/Clocker.xcodeproj/project.pbxproj @@ -41,6 +41,8 @@ 9A5951F51C1D3D81009C17AA /* CLTimezoneCellView.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A5951F41C1D3D81009C17AA /* CLTimezoneCellView.m */; }; 9A5951FA1C1D5214009C17AA /* iVersion.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A5951F91C1D5214009C17AA /* iVersion.m */; }; 9A5951FD1C1D592D009C17AA /* iVersion.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 9A5951FC1C1D592D009C17AA /* iVersion.bundle */; }; + 9A5B3D3A1E3C3588006E8DD2 /* MoLoginItem.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A5B3D391E3C3588006E8DD2 /* MoLoginItem.framework */; }; + 9A5B3D3B1E3C3588006E8DD2 /* MoLoginItem.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = 9A5B3D391E3C3588006E8DD2 /* MoLoginItem.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 9A5B6C6E1D3DF6E4000EAAF1 /* CLParentViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A5B6C6D1D3DF6E4000EAAF1 /* CLParentViewController.m */; }; 9A5B6C711D4087A5000EAAF1 /* NSString+CLStringAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A5B6C701D4087A5000EAAF1 /* NSString+CLStringAdditions.m */; }; 9A5B6C781D459438000EAAF1 /* CLTimezoneDataOperations.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A5B6C771D459438000EAAF1 /* CLTimezoneDataOperations.m */; }; @@ -72,7 +74,6 @@ 9A87DACB1C358FA800A8CF3B /* NSDate+DateTools.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A87DAC31C358FA800A8CF3B /* NSDate+DateTools.m */; }; 9A9E63861C2C673E009A299B /* CLAppFeedbackWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 9A9E63841C2C673E009A299B /* CLAppFeedbackWindowController.m */; }; 9A9E87621C1FEDB500A7A2DF /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A9E87611C1FEDB500A7A2DF /* CFNetwork.framework */; }; - 9A9E87681C1FEDD300A7A2DF /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A9E87671C1FEDD300A7A2DF /* Security.framework */; }; 9A9E876A1C1FEDDB00A7A2DF /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9A9E87691C1FEDDB00A7A2DF /* SystemConfiguration.framework */; }; 9AA4AC8C1CEC0FA60054ACB7 /* FloatingView.m in Sources */ = {isa = PBXBuildFile; fileRef = 9AA4AC871CEC0FA60054ACB7 /* FloatingView.m */; }; 9AA4AC8D1CEC0FA60054ACB7 /* CLShortcutAnimatedView.m in Sources */ = {isa = PBXBuildFile; fileRef = 9AA4AC891CEC0FA60054ACB7 /* CLShortcutAnimatedView.m */; }; @@ -86,6 +87,8 @@ 9AC678E41C1ABAB9003B4F6B /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9AC678E31C1ABAB9003B4F6B /* QuartzCore.framework */; settings = {ATTRIBUTES = (Weak, ); }; }; 9ACE03EF1CB0ADE00039FC01 /* Firebase.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9ACE03EE1CB0ADE00039FC01 /* Firebase.framework */; }; 9ACF469D1DCBD45200C49B51 /* Quartz.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9ACF469C1DCBD45200C49B51 /* Quartz.framework */; }; + 9AF6721A1E3BEE6B00210A1B /* FMDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9AF672101E3BE83A00210A1B /* FMDB.framework */; }; + 9AF6721B1E3BEE6B00210A1B /* FMDB.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = 9AF672101E3BE83A00210A1B /* FMDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 9AF9A16B1C250AB300EE7C2A /* Reachability.m in Sources */ = {isa = PBXBuildFile; fileRef = 9AF9A16A1C250AB300EE7C2A /* Reachability.m */; }; DD4F7C0913C30F9F00825C6E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DD4F7C0813C30F9F00825C6E /* Cocoa.framework */; }; /* End PBXBuildFile section */ @@ -168,6 +171,55 @@ remoteGlobalIDString = 0D6B2468180304DE00CE1142; remoteInfo = Demo; }; + 9AF672051E3BE83A00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 8DD76FA10486AA7600D96B5E; + remoteInfo = fmdb; + }; + 9AF672071E3BE83A00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = EE4290EF12B42F870088BD94; + remoteInfo = FMDB; + }; + 9AF672091E3BE83A00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = BF5D041618416BB2008C5AA9; + remoteInfo = Tests; + }; + 9AF6720B1E3BE83A00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 6290CBB5188FE836009790F8; + remoteInfo = "FMDB-IOS"; + }; + 9AF6720D1E3BE83A00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 83C73EFE1C326AB000FFC730; + remoteInfo = "FMDB iOS"; + }; + 9AF6720F1E3BE83A00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 83C73F0B1C326ADA00FFC730; + remoteInfo = "FMDB MacOS"; + }; + 9AF6721C1E3BEE6B00210A1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 83C73F0A1C326ADA00FFC730; + remoteInfo = "FMDB MacOS"; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -187,8 +239,10 @@ dstSubfolderSpec = 10; files = ( 9A86E2C41CE04F7B00547EE7 /* ShortcutRecorder.framework in CopyFiles */, + 9A5B3D3B1E3C3588006E8DD2 /* MoLoginItem.framework in CopyFiles */, 9A3169BD1D2CB9B40079FDF8 /* pop.framework in CopyFiles */, 9A86E2C51CE04F7B00547EE7 /* PTHotKey.framework in CopyFiles */, + 9AF6721B1E3BEE6B00210A1B /* FMDB.framework in CopyFiles */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -245,6 +299,7 @@ 9A5951F91C1D5214009C17AA /* iVersion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = iVersion.m; path = "Clocker/Updated Version/iVersion.m"; sourceTree = ""; }; 9A5951FC1C1D592D009C17AA /* iVersion.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; name = iVersion.bundle; path = "Clocker/Updated Version/iVersion.bundle"; sourceTree = ""; }; 9A5B1A8D1BECDFB700A77C68 /* Clocker.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = Clocker.entitlements; path = Clocker/Clocker.entitlements; sourceTree = ""; }; + 9A5B3D391E3C3588006E8DD2 /* MoLoginItem.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MoLoginItem.framework; path = Frameworks/MoLoginItem.framework; sourceTree = ""; }; 9A5B6C6C1D3DF6E4000EAAF1 /* CLParentViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CLParentViewController.h; path = Clocker/CLParentViewController.h; sourceTree = ""; }; 9A5B6C6D1D3DF6E4000EAAF1 /* CLParentViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CLParentViewController.m; path = Clocker/CLParentViewController.m; sourceTree = ""; }; 9A5B6C6F1D4087A5000EAAF1 /* NSString+CLStringAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+CLStringAdditions.h"; path = "Clocker/Utilities/NSString+CLStringAdditions.h"; sourceTree = ""; }; @@ -323,6 +378,7 @@ 9AC678E31C1ABAB9003B4F6B /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; 9ACE03EE1CB0ADE00039FC01 /* Firebase.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Firebase.framework; path = Frameworks/Firebase.framework; sourceTree = ""; }; 9ACF469C1DCBD45200C49B51 /* Quartz.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Quartz.framework; path = System/Library/Frameworks/Quartz.framework; sourceTree = SDKROOT; }; + 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = fmdb.xcodeproj; path = Clocker/FMDB/fmdb.xcodeproj; sourceTree = ""; }; 9AF9A1691C250AB300EE7C2A /* Reachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Reachability.h; path = Clocker/Reachability/Reachability.h; sourceTree = ""; }; 9AF9A16A1C250AB300EE7C2A /* Reachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Reachability.m; path = Clocker/Reachability/Reachability.m; sourceTree = ""; }; DD4F7C0413C30F9F00825C6E /* Clocker.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Clocker.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -342,16 +398,17 @@ 9A86E2C11CE04F4300547EE7 /* ShortcutRecorder.framework in Frameworks */, 9A9E876A1C1FEDDB00A7A2DF /* SystemConfiguration.framework in Frameworks */, 9A9E87621C1FEDB500A7A2DF /* CFNetwork.framework in Frameworks */, + 9AF6721A1E3BEE6B00210A1B /* FMDB.framework in Frameworks */, 9ABFB3801CA6882000E10745 /* ApplicationServices.framework in Frameworks */, 9A20A04B1C4DEED200FB45AB /* IOKit.framework in Frameworks */, 9A3169BC1D2CB9B40079FDF8 /* pop.framework in Frameworks */, - 9A9E87681C1FEDD300A7A2DF /* Security.framework in Frameworks */, 9A5951BA1C1D0A22009C17AA /* Crashlytics.framework in Frameworks */, 9A43792A1BEC230A00F4E27F /* libc++.tbd in Frameworks */, 9A4379251BEC223900F4E27F /* Security.framework in Frameworks */, DD4F7C0913C30F9F00825C6E /* Cocoa.framework in Frameworks */, 9A4379271BEC223900F4E27F /* Fabric.framework in Frameworks */, 9ACE03EF1CB0ADE00039FC01 /* Firebase.framework in Frameworks */, + 9A5B3D3A1E3C3588006E8DD2 /* MoLoginItem.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -585,6 +642,19 @@ name = Model; sourceTree = ""; }; + 9AF671FD1E3BE83A00210A1B /* Products */ = { + isa = PBXGroup; + children = ( + 9AF672061E3BE83A00210A1B /* fmdb */, + 9AF672081E3BE83A00210A1B /* libFMDB.a */, + 9AF6720A1E3BE83A00210A1B /* Tests.xctest */, + 9AF6720C1E3BE83A00210A1B /* libFMDB-IOS.a */, + 9AF6720E1E3BE83A00210A1B /* FMDB.framework */, + 9AF672101E3BE83A00210A1B /* FMDB.framework */, + ); + name = Products; + sourceTree = ""; + }; 9AF9A1681C250AA300EE7C2A /* Reachability */ = { isa = PBXGroup; children = ( @@ -597,6 +667,8 @@ DD4F7BF913C30F9F00825C6E = { isa = PBXGroup; children = ( + 9A5B3D391E3C3588006E8DD2 /* MoLoginItem.framework */, + 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */, 9AA4AC851CEC0EE40054ACB7 /* Onboarding Animated Views */, 9AB89E021CE97A4900EC8EB1 /* Media.xcassets */, 9A86E2B51CE04F1600547EE7 /* ShortcutRecorder.xcodeproj */, @@ -675,6 +747,7 @@ ); dependencies = ( 9A3169BF1D2CB9B40079FDF8 /* PBXTargetDependency */, + 9AF6721D1E3BEE6B00210A1B /* PBXTargetDependency */, ); name = Clocker; productName = Popup; @@ -701,6 +774,9 @@ com.apple.Sandbox = { enabled = 1; }; + com.apple.iCloud = { + enabled = 0; + }; }; }; }; @@ -716,6 +792,10 @@ productRefGroup = DD4F7C0513C30F9F00825C6E /* Products */; projectDirPath = ""; projectReferences = ( + { + ProductGroup = 9AF671FD1E3BE83A00210A1B /* Products */; + ProjectRef = 9AF671FC1E3BE83A00210A1B /* fmdb.xcodeproj */; + }, { ProductGroup = 9A82F32C1CDFF8CE00CC8906 /* Products */; ProjectRef = 9A82F32B1CDFF8CE00CC8906 /* pop.xcodeproj */; @@ -803,6 +883,48 @@ remoteRef = 9A86E2BF1CE04F1600547EE7 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; + 9AF672061E3BE83A00210A1B /* fmdb */ = { + isa = PBXReferenceProxy; + fileType = "compiled.mach-o.executable"; + path = fmdb; + remoteRef = 9AF672051E3BE83A00210A1B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 9AF672081E3BE83A00210A1B /* libFMDB.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libFMDB.a; + remoteRef = 9AF672071E3BE83A00210A1B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 9AF6720A1E3BE83A00210A1B /* Tests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = Tests.xctest; + remoteRef = 9AF672091E3BE83A00210A1B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 9AF6720C1E3BE83A00210A1B /* libFMDB-IOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libFMDB-IOS.a"; + remoteRef = 9AF6720B1E3BE83A00210A1B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 9AF6720E1E3BE83A00210A1B /* FMDB.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = FMDB.framework; + remoteRef = 9AF6720D1E3BE83A00210A1B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 9AF672101E3BE83A00210A1B /* FMDB.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = FMDB.framework; + remoteRef = 9AF6720F1E3BE83A00210A1B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -909,6 +1031,11 @@ name = "pop-osx-framework"; targetProxy = 9A3169BE1D2CB9B40079FDF8 /* PBXContainerItemProxy */; }; + 9AF6721D1E3BEE6B00210A1B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "FMDB MacOS"; + targetProxy = 9AF6721C1E3BEE6B00210A1B /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -1058,6 +1185,7 @@ ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Clocker/Clocker-Prefix.pch"; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_UNUSED_LABEL = YES; GCC_WARN_UNUSED_PARAMETER = NO; INFOPLIST_FILE = "Clocker/Clocker-Info.plist"; @@ -1168,6 +1296,7 @@ ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Clocker/Clocker-Prefix.pch"; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_UNUSED_LABEL = YES; GCC_WARN_UNUSED_PARAMETER = NO; INFOPLIST_FILE = "Clocker/Clocker-Info.plist"; @@ -1203,6 +1332,7 @@ ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Clocker/Clocker-Prefix.pch"; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_UNUSED_LABEL = YES; GCC_WARN_UNUSED_PARAMETER = NO; INFOPLIST_FILE = "Clocker/Clocker-Info.plist"; diff --git a/Clocker.xcodeproj/project.xcworkspace/xcuserdata/abhishekbanthia.xcuserdatad/UserInterfaceState.xcuserstate b/Clocker.xcodeproj/project.xcworkspace/xcuserdata/abhishekbanthia.xcuserdatad/UserInterfaceState.xcuserstate index 55376f8..b546c1b 100644 Binary files a/Clocker.xcodeproj/project.xcworkspace/xcuserdata/abhishekbanthia.xcuserdatad/UserInterfaceState.xcuserstate and b/Clocker.xcodeproj/project.xcworkspace/xcuserdata/abhishekbanthia.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Clocker/Appearance Tab/CLAppearanceViewController.m b/Clocker/Appearance Tab/CLAppearanceViewController.m index f9a91d5..6fb071f 100644 --- a/Clocker/Appearance Tab/CLAppearanceViewController.m +++ b/Clocker/Appearance Tab/CLAppearanceViewController.m @@ -101,7 +101,7 @@ typedef NS_ENUM(NSUInteger, CLClockerMode) { [sharedDelegate.panelController updateDefaultPreferences]; } - [Answers logCustomEventWithName:@"RelativeDate" customAttributes:@{@"displayMode" : modeSegment.selectedSegment == CLFloatingMode ? @"Floating Mode" : @"Menubar Mode"}]; + [Answers logCustomEventWithName:@"Clocker Mode" customAttributes:@{@"displayMode" : modeSegment.selectedSegment == CLFloatingMode ? @"Floating Mode" : @"Menubar Mode"}]; } diff --git a/Clocker/ApplicationDelegate.m b/Clocker/ApplicationDelegate.m index 2d5d135..d370ddb 100755 --- a/Clocker/ApplicationDelegate.m +++ b/Clocker/ApplicationDelegate.m @@ -32,6 +32,10 @@ #import "CommonStrings.h" #import "iVersion.h" #import "CLOnboardingWindowController.h" +#import +#import "CLTimezoneData.h" +#import "CLTimezoneDataOperations.h" +#import "MoLoginItem/MoLoginItem.h" @implementation ApplicationDelegate @@ -66,7 +70,7 @@ void *kContextActivePanel = &kContextActivePanel; //Configure iRate [iRate sharedInstance].useAllAvailableLanguages = YES; [iVersion sharedInstance].useAllAvailableLanguages = YES; - [[iRate sharedInstance] setVerboseLogging:YES]; + [[iRate sharedInstance] setVerboseLogging:NO]; [[iVersion sharedInstance] setVerboseLogging:NO]; [iRate sharedInstance].promptForNewVersionIfUserRated = YES; } @@ -75,6 +79,8 @@ void *kContextActivePanel = &kContextActivePanel; - (void)applicationDidFinishLaunching:(NSNotification *)notification { + [self setupDatabase]; + NSNumber *opened = [[NSUserDefaults standardUserDefaults] objectForKey:@"noOfTimes"]; if (opened == nil) { @@ -112,6 +118,127 @@ void *kContextActivePanel = &kContextActivePanel; } +- (void)setupDatabase +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSString *applicationSupportDirectory = [[paths firstObject] stringByAppendingPathComponent:@"Clocker"];; + + NSError *error = nil; + + if(![[NSFileManager defaultManager] createDirectoryAtPath:applicationSupportDirectory withIntermediateDirectories:YES attributes:NULL error:&error]){ + NSLog(@"%@", error); + return; + } + + NSString *dbPath = [applicationSupportDirectory stringByAppendingPathComponent:@"Timezones.db"]; + FMDatabase *database = [FMDatabase databaseWithPath:dbPath]; + database.crashOnErrors = YES; + if (![database open]) { + NSLog(@"%@", database.lastErrorMessage); + + } + else + { + NSString *checkIfTableExistsStatement = @"select sql from SQLITE_MASTER where name = 'CLTimezoneData'"; + FMResultSet *checkIfTableExistsResult = [database executeQuery:checkIfTableExistsStatement]; + + + if (![checkIfTableExistsResult next]) + { + NSString *tableCreationStatement = [NSString stringWithFormat:@"create table CLTimezoneData (timezoneNumber INT primary key , timezoneID TEXT, custom_label TEXT, formatted_address TEXT, latitude TEXT, longitude TEXT, is_favourite INT, place_id TEXT,selectionType INT)"]; + + FMResultSet *resultSet = [database executeQuery:tableCreationStatement]; + + if ([resultSet next]) { + [self addObjectsToDatabase:database]; + } + } + + [self addObjectsToDatabase:database]; + + } + +} + +- (void)addObjectsToDatabase:(FMDatabase *)database +{ + __block NSInteger emptyTimezones = 0; + __block NSMutableArray *workingTimezones = [NSMutableArray array]; + + FMResultSet *resultSet = [database executeQuery:@"SELECT COUNT(*) FROM CLTimezoneData"]; + if ([resultSet next]) { + + NSInteger totalCount = [resultSet intForColumnIndex:0]; + + if (totalCount == 0) { + + NSArray *defaultZones = [[NSUserDefaults standardUserDefaults] objectForKey:CLDefaultPreferenceKey]; + + [defaultZones enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { + + CLTimezoneData *dataObject = [CLTimezoneData getCustomObject:obj]; + + if ([dataObject isEmpty]) { + + emptyTimezones++; + /*Remove it from the goddarn collection.*/ + } + else + { + + [workingTimezones addObject:dataObject]; + + BOOL success = [database executeUpdate:@"INSERT INTO CLTimezoneData (timezoneNumber, timezoneID, custom_label, formatted_address, latitude, longitude, is_favourite,place_id, selectionType) VALUES (?, ?, ?, ?, ?, ? , ?, ?, ?)", @(idx+1), dataObject.timezoneID, dataObject.customLabel ?: [NSNull null], dataObject.formattedAddress, dataObject.latitude, dataObject.longitude, dataObject.isFavourite, dataObject.place_id,@(dataObject.selectionType)]; + + !success ? NSLog(@"error = %@", [database lastErrorMessage]) : NSLog(@"Data inserted successfully"); + } + + }]; + } + else + { + NSLog(@"Count is not zero :%zd", totalCount); + } + } + + if (emptyTimezones > 0) { + + [[NSUserDefaults standardUserDefaults] setObject:nil forKey:CLDefaultPreferenceKey]; + [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"favouriteTimezone"]; + + for (id object in workingTimezones) + { + CLTimezoneDataOperations *dataOperations = [[CLTimezoneDataOperations alloc] initWithTimezoneData:object]; + [dataOperations save]; + } + + [self showErrorMessageForEmptyTimezones]; + } +} + +- (void)showErrorMessageForEmptyTimezones +{ + [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; + NSAlert *alert = [NSAlert new]; + alert.messageText = @"Please add your timezones again 😅"; + alert.informativeText = [NSString stringWithFormat:@"Clocker has encountered an error while reading certain timezones. Please add them again."]; + [alert addButtonWithTitle:@"Okay"]; + NSModalResponse response = [alert runModal]; + if (response == NSModalResponseStop) { + dispatch_async(dispatch_get_main_queue(), ^{ + + [self openPreferences]; + }); + + } +} + +- (void)openPreferences +{ + [self.panelController openPreferenceWindowWithValue:YES]; +} + + - (void)initializeDefaults { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; @@ -161,6 +288,10 @@ void *kContextActivePanel = &kContextActivePanel; if (startClockerAtLogin == nil) { [userDefaults setObject:@0 forKey:CLStartAtLogin]; } + else if([startClockerAtLogin isEqualToNumber:@(1)]) + { + MOEnableLoginItem(YES); + } NSNumber *displayMode = [userDefaults objectForKey:CLShowAppInForeground]; if (displayMode == nil) { @@ -182,6 +313,8 @@ void *kContextActivePanel = &kContextActivePanel; [userDefaults setObject:@4 forKey:CLUserFontSizePreference]; } + + //If mode selected is 1, then show the window when the app starts if (displayMode.integerValue == 1) { diff --git a/Clocker/FMDB/.gitignore b/Clocker/FMDB/.gitignore new file mode 100755 index 0000000..838dbb6 --- /dev/null +++ b/Clocker/FMDB/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +build +*.xcodeproj/*.pbxuser +*.xcodeproj/*.perspectivev3 +*.xcodeproj/xcuserdata +fmdb.xcodeproj/*.mode1v3 +*.xcodeproj/project.xcworkspace/xcuserdata/ +fmdb.xcodeproj/project.xcworkspace diff --git a/Clocker/FMDB/LICENSE.txt b/Clocker/FMDB/LICENSE.txt new file mode 100755 index 0000000..addfc1a --- /dev/null +++ b/Clocker/FMDB/LICENSE.txt @@ -0,0 +1,28 @@ +If you are using FMDB in your project, I'd love to hear about it. Let Gus know +by sending an email to gus@flyingmeat.com. + +And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you +might consider purchasing a drink of their choosing if FMDB has been useful to +you. + +Finally, and shortly, this is the MIT License. + +Copyright (c) 2008-2014 Flying Meat Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/Clocker/FMDB/README.markdown b/Clocker/FMDB/README.markdown new file mode 100755 index 0000000..823ec0a --- /dev/null +++ b/Clocker/FMDB/README.markdown @@ -0,0 +1,437 @@ +# FMDB v2.6.2 + +This is an Objective-C wrapper around SQLite: http://sqlite.org/ + +## The FMDB Mailing List: +http://groups.google.com/group/fmdb + +## Read the SQLite FAQ: +http://www.sqlite.org/faq.html + +Since FMDB is built on top of SQLite, you're going to want to read this page top to bottom at least once. And while you're there, make sure to bookmark the SQLite Documentation page: http://www.sqlite.org/docs.html + +## Contributing +Do you have an awesome idea that deserves to be in FMDB? You might consider pinging ccgus first to make sure he hasn't already ruled it out for some reason. Otherwise pull requests are great, and make sure you stick to the local coding conventions. However, please be patient and if you haven't heard anything from ccgus for a week or more, you might want to send a note asking what's up. + +## CocoaPods + +[![Dependency Status](https://www.versioneye.com/objective-c/fmdb/2.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/2.3) +[![Reference Status](https://www.versioneye.com/objective-c/fmdb/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/references) + +FMDB can be installed using [CocoaPods](https://cocoapods.org/). + +```ruby +pod 'FMDB' +# pod 'FMDB/FTS' # FMDB with FTS +# pod 'FMDB/standalone' # FMDB with latest SQLite amalgamation source +# pod 'FMDB/standalone/FTS' # FMDB with latest SQLite amalgamation source and FTS +# pod 'FMDB/SQLCipher' # FMDB with SQLCipher +``` + +**If using FMDB with [SQLCipher](https://www.zetetic.net/sqlcipher/) you must use the FMDB/SQLCipher subspec. The FMDB/SQLCipher subspec declares SQLCipher as a dependency, allowing FMDB to be compiled with the `-DSQLITE_HAS_CODEC` flag.** + +## FMDB Class Reference: +http://ccgus.github.io/fmdb/html/index.html + +## Automatic Reference Counting (ARC) or Manual Memory Management? +You can use either style in your Cocoa project. FMDB will figure out which you are using at compile time and do the right thing. + +## Usage +There are three main classes in FMDB: + +1. `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. +2. `FMResultSet` - Represents the results of executing a query on an `FMDatabase`. +3. `FMDatabaseQueue` - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class. It's described in the "Thread Safety" section below. + +### Database Creation +An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + +1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. +2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. +3. `NULL`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + +(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html) + +```objc +NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp.db"]; +FMDatabase *db = [FMDatabase databaseWithPath:path]; +``` + +### Opening + +Before you can interact with the database, it must be opened. Opening fails if there are insufficient resources or permissions to open and/or create the database. + +```objc +if (![db open]) { + // [db release]; // uncomment this line in manual referencing code; in ARC, this is not necessary/permitted + db = nil; + return; +} +``` + +### Executing Updates + +Any sort of SQL statement which is not a `SELECT` statement qualifies as an update. This includes `CREATE`, `UPDATE`, `INSERT`, `ALTER`, `COMMIT`, `BEGIN`, `DETACH`, `DELETE`, `DROP`, `END`, `EXPLAIN`, `VACUUM`, and `REPLACE` statements (plus many more). Basically, if your SQL statement does not begin with `SELECT`, it is an update statement. + +Executing updates returns a single value, a `BOOL`. A return value of `YES` means the update was successfully executed, and a return value of `NO` means that some error was encountered. You may invoke the `-lastErrorMessage` and `-lastErrorCode` methods to retrieve more information. + +### Executing Queries + +A `SELECT` statement is a query and is executed via one of the `-executeQuery...` methods. + +Executing queries returns an `FMResultSet` object if successful, and `nil` upon failure. You should use the `-lastErrorMessage` and `-lastErrorCode` methods to determine why a query failed. + +In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" from one record to the other. With FMDB, the easiest way to do that is like this: + +```objc +FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"]; +while ([s next]) { + //retrieve values for each record +} +``` + +You must always invoke `-[FMResultSet next]` before attempting to access the values returned in a query, even if you're only expecting one: + +```objc +FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"]; +if ([s next]) { + int totalCount = [s intForColumnIndex:0]; +} +``` + +`FMResultSet` has many methods to retrieve data in an appropriate format: + +- `intForColumn:` +- `longForColumn:` +- `longLongIntForColumn:` +- `boolForColumn:` +- `doubleForColumn:` +- `stringForColumn:` +- `dateForColumn:` +- `dataForColumn:` +- `dataNoCopyForColumn:` +- `UTF8StringForColumnName:` +- `objectForColumnName:` + +Each of these methods also has a `{type}ForColumnIndex:` variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name. + +Typically, there's no need to `-close` an `FMResultSet` yourself, since that happens when either the result set is deallocated, or the parent database is closed. + +### Closing + +When you have finished executing queries and updates on the database, you should `-close` the `FMDatabase` connection so that SQLite will relinquish any resources it has acquired during the course of its operation. + +```objc +[db close]; +``` + +### Transactions + +`FMDatabase` can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement. + +### Multiple Statements and Batch Stuff + +You can use `FMDatabase`'s executeStatements:withResultBlock: to do multiple statements in a string: + +```objc +NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);" + "create table bulktest2 (id integer primary key autoincrement, y text);" + "create table bulktest3 (id integer primary key autoincrement, z text);" + "insert into bulktest1 (x) values ('XXX');" + "insert into bulktest2 (y) values ('YYY');" + "insert into bulktest3 (z) values ('ZZZ');"; + +success = [db executeStatements:sql]; + +sql = @"select count(*) as count from bulktest1;" + "select count(*) as count from bulktest2;" + "select count(*) as count from bulktest3;"; + +success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) { + NSInteger count = [dictionary[@"count"] integerValue]; + XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary); + return 0; +}]; +``` + +### Data Sanitization + +When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax: + +```sql +INSERT INTO myTable VALUES (?, ?, ?, ?) +``` + +The `?` character is recognized by SQLite as a placeholder for a value to be inserted. The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an `NSArray`, `NSDictionary`, or a `va_list`), which are properly escaped for you. + +And, to use that SQL with the `?` placeholders from Objective-C: + +```objc +NSInteger identifier = 42; +NSString *name = @"Liam O'Flaherty (\"the famous Irish author\")"; +NSDate *date = [NSDate date]; +NSString *comment = nil; + +BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]]; +if (!success) { + NSLog(@"error = %@", [db lastErrorMessage]); +} +``` + +> **Note:** Fundamental data types, like the `NSInteger` variable `identifier`, should be as a `NSNumber` objects, achieved by using the `@` syntax, shown above. Or you can use the `[NSNumber numberWithInt:identifier]` syntax, too. +> +> Likewise, SQL `NULL` values should be inserted as `[NSNull null]`. For example, in the case of `comment` which might be `nil` (and is in this example), you can use the `comment ?: [NSNull null]` syntax, which will insert the string if `comment` is not `nil`, but will insert `[NSNull null]` if it is `nil`. + +In Swift, you would use `executeUpdate(values:)`, which not only is a concise Swift syntax, but also `throws` errors for proper Swift 2 error handling: + +```swift +do { + let identifier = 42 + let name = "Liam O'Flaherty (\"the famous Irish author\")" + let date = NSDate() + let comment: String? = nil + + try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()]) +} catch { + print("error = \(error)") +} +``` + +> **Note:** In Swift, you don't have to wrap fundamental numeric types like you do in Objective-C. But if you are going to insert an optional string, you would probably use the `comment ?? NSNull()` syntax (i.e., if it is `nil`, use `NSNull`, otherwise use the string). + +Alternatively, you may use named parameters syntax: + +```sql +INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment) +``` + +The parameters *must* start with a colon. SQLite itself supports other characters, but internally the dictionary keys are prefixed with a colon, do **not** include the colon in your dictionary keys. + +```objc +NSDictionary *arguments = @{@"identifier": @(identifier), @"name": name, @"date": date, @"comment": comment ?: [NSNull null]}; +BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)" withParameterDictionary:arguments]; +if (!success) { + NSLog(@"error = %@", [db lastErrorMessage]); +} +``` + +The key point is that one should not use `NSString` method `stringWithFormat` to manually insert values into the SQL statement, itself. Nor should one Swift string interpolation to insert values into the SQL. Use `?` placeholders for values to be inserted into the database (or used in `WHERE` clauses in `SELECT` statements). + +

Using FMDatabaseQueue and Thread Safety.

+ +Using a single instance of `FMDatabase` from multiple threads at once is a bad idea. It has always been OK to make a `FMDatabase` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. Bad things will eventually happen and you'll eventually get something to crash, or maybe get an exception, or maybe meteorites will fall out of the sky and hit your Mac Pro. *This would suck*. + +**So don't instantiate a single `FMDatabase` object and use it across multiple threads.** + +Instead, use `FMDatabaseQueue`. Instantiate a single `FMDatabaseQueue` and use it across multiple threads. The `FMDatabaseQueue` object will synchronize and coordinate access across the multiple threads. Here's how to use it: + +First, make your queue. + +```objc +FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; +``` + +Then use it like so: + + +```objc +[queue inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3]; + + FMResultSet *rs = [db executeQuery:@"select * from foo"]; + while ([rs next]) { + … + } +}]; +``` + +An easy way to wrap things up in a transaction can be done like this: + +```objc +[queue inTransaction:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3]; + + if (whoopsSomethingWrongHappened) { + *rollback = YES; + return; + } + + // etc ... +}]; +``` + +The Swift 3 equivalent would be: + +```swift +queue.inTransaction { db, rollback in + do { + try db?.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1]) + try db?.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2]) + try db?.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3]) + + if whoopsSomethingWrongHappened { + rollback?.pointee = true + return + } + + // etc ... + } catch { + rollback?.pointee = true + print(error) + } +} +``` + +(Note, in Swift 3, use `pointee`. But in Swift 2.3, use `memory` rather than `pointee`.) + +`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. + +**Note:** The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + +## Making custom sqlite functions, based on blocks. + +You can do this! For an example, look for `-makeFunctionNamed:` in main.m + +## Swift + +You can use FMDB in Swift projects too. + +To do this, you must: + +1. Copy the relevant `.m` and `.h` files from the FMDB `src` folder into your project. + + You can copy all of them (which is easiest), or only the ones you need. Likely you will need [`FMDatabase`](http://ccgus.github.io/fmdb/html/Classes/FMDatabase.html) and [`FMResultSet`](http://ccgus.github.io/fmdb/html/Classes/FMResultSet.html) at a minimum. [`FMDatabaseAdditions`](http://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html) provides some very useful convenience methods, so you will likely want that, too. If you are doing multithreaded access to a database, [`FMDatabaseQueue`](http://ccgus.github.io/fmdb/html/Classes/FMDatabaseQueue.html) is quite useful, too. If you choose to not copy all of the files from the `src` directory, though, you may want to update `FMDB.h` to only reference the files that you included in your project. + + Note, if you're copying all of the files from the `src` folder into to your project (which is recommended), you may want to drag the individual files into your project, not the folder, itself, because if you drag the folder, you won't be prompted to add the bridging header (see next point). + +2. If prompted to create a "bridging header", you should do so. If not prompted and if you don't already have a bridging header, add one. + + For more information on bridging headers, see [Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_76). + +3. In your bridging header, add a line that says: + ```objc + #import "FMDB.h" + ``` + +4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift 2 fashion. + +If you do the above, you can then write Swift code that uses `FMDatabase`. For example, in Swift 3: + +```swift +let fileURL = try! FileManager.default + .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) + .appendingPathComponent("test.sqlite") + +guard let database = FMDatabase(path: fileURL.path) else { + print("unable to create database") + return +} + +guard database.open() else { + print("Unable to open database") + return +} + +do { + try database.executeUpdate("create table test(x text, y text, z text)", values: nil) + try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"]) + try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"]) + + let rs = try database.executeQuery("select x, y, z from test", values: nil) + while rs.next() { + if let x = rs.string(forColumn: "x"), let y = rs.string(forColumn: "y"), let z = rs.string(forColumn: "z") { + print("x = \(x); y = \(y); z = \(z)") + } + } +} catch { + print("failed: \(error.localizedDescription)") +} + +database.close() +``` + +Or in Swift 2: + +```swift +let fileURL = try! NSFileManager.defaultManager() + .URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) + .URLByAppendingPathComponent("test.sqlite") + +let database = FMDatabase(path: fileURL.path) + +if !database.open() { + print("Unable to open database") + return +} + +do { + try database.executeUpdate("create table test(x text, y text, z text)", values: nil) + try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"]) + try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"]) + + let rs = try database.executeQuery("select x, y, z from test", values: nil) + while rs.next() { + let x = rs.stringForColumn("x") + let y = rs.stringForColumn("y") + let z = rs.stringForColumn("z") + print("x = \(x); y = \(y); z = \(z)") + } +} catch let error as NSError { + print("failed: \(error.localizedDescription)") +} + +database.close() +``` + +## History + +The history and changes are availbe on its [GitHub page](https://github.com/ccgus/fmdb) and are summarized in the "CHANGES_AND_TODO_LIST.txt" file. + +## Contributors + +The contributors to FMDB are contained in the "Contributors.txt" file. + +## Additional projects using FMDB, which might be interesting to the discerning developer. + + * FMDBMigrationManager, A SQLite schema migration management system for FMDB: https://github.com/layerhq/FMDBMigrationManager + * FCModel, An alternative to Core Data for people who like having direct SQL access: https://github.com/marcoarment/FCModel + +## Quick notes on FMDB's coding style + +Spaces, not tabs. Square brackets, not dot notation. Look at what FMDB already does with curly brackets and such, and stick to that style. + +## Reporting bugs + +Reduce your bug down to the smallest amount of code possible. You want to make it super easy for the developers to see and reproduce your bug. If it helps, pretend that the person who can fix your bug is active on shipping 3 major products, works on a handful of open source projects, has a newborn baby, and is generally very very busy. + +And we've even added a template function to main.m (FMDBReportABugFunction) in the FMDB distribution to help you out: + +* Open up fmdb project in Xcode. +* Open up main.m and modify the FMDBReportABugFunction to reproduce your bug. + * Setup your table(s) in the code. + * Make your query or update(s). + * Add some assertions which demonstrate the bug. + +Then you can bring it up on the FMDB mailing list by showing your nice and compact FMDBReportABugFunction, or you can report the bug via the github FMDB bug reporter. + +**Optional:** + +Figure out where the bug is, fix it, and send a patch in or bring that up on the mailing list. Make sure all the other tests run after your modifications. + +## Support + +The support channels for FMDB are the mailing list (see above), filing a bug here, or maybe on Stack Overflow. So that is to say, support is provided by the community and on a voluntary basis. + +FMDB development is overseen by Gus Mueller of Flying Meat. If FMDB been helpful to you, consider purchasing an app from FM or telling all your friends about it. + +## License + +The license for FMDB is contained in the "License.txt" file. + +If you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you. + +(The drink is for them of course, shame on you for trying to keep it.) diff --git a/Clocker/FMDB/Tests/FMDBTempDBTests.h b/Clocker/FMDB/Tests/FMDBTempDBTests.h new file mode 100755 index 0000000..c84ab8f --- /dev/null +++ b/Clocker/FMDB/Tests/FMDBTempDBTests.h @@ -0,0 +1,24 @@ +// +// FMDBTempDBTests.h +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import +#import "FMDatabase.h" + +@protocol FMDBTempDBTests + +@optional ++ (void)populateDatabase:(FMDatabase *)database; + +@end + +@interface FMDBTempDBTests : XCTestCase + +@property FMDatabase *db; +@property (readonly) NSString *databasePath; + +@end diff --git a/Clocker/FMDB/Tests/FMDBTempDBTests.m b/Clocker/FMDB/Tests/FMDBTempDBTests.m new file mode 100755 index 0000000..bb759df --- /dev/null +++ b/Clocker/FMDB/Tests/FMDBTempDBTests.m @@ -0,0 +1,63 @@ +// +// FMDBTempDBTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import "FMDBTempDBTests.h" + +static NSString *const testDatabasePath = @"/tmp/tmp.db"; +static NSString *const populatedDatabasePath = @"/tmp/tmp-populated.db"; + +@implementation FMDBTempDBTests + ++ (void)setUp +{ + [super setUp]; + + // Delete old populated database + NSFileManager *fileManager = [NSFileManager defaultManager]; + [fileManager removeItemAtPath:populatedDatabasePath error:NULL]; + + if ([self respondsToSelector:@selector(populateDatabase:)]) { + FMDatabase *db = [FMDatabase databaseWithPath:populatedDatabasePath]; + + [db open]; + [self populateDatabase:db]; + [db close]; + } +} + +- (void)setUp +{ + [super setUp]; + + // Delete the old database + NSFileManager *fileManager = [NSFileManager defaultManager]; + [fileManager removeItemAtPath:testDatabasePath error:NULL]; + + if ([[self class] respondsToSelector:@selector(populateDatabase:)]) { + [fileManager copyItemAtPath:populatedDatabasePath toPath:testDatabasePath error:NULL]; + } + + self.db = [FMDatabase databaseWithPath:testDatabasePath]; + + XCTAssertTrue([self.db open], @"Wasn't able to open database"); + [self.db setShouldCacheStatements:YES]; +} + +- (void)tearDown +{ + [super tearDown]; + + [self.db close]; +} + +- (NSString *)databasePath +{ + return testDatabasePath; +} + +@end diff --git a/Clocker/FMDB/Tests/FMDatabaseAdditionsTests.m b/Clocker/FMDB/Tests/FMDatabaseAdditionsTests.m new file mode 100755 index 0000000..9f6e84f --- /dev/null +++ b/Clocker/FMDB/Tests/FMDatabaseAdditionsTests.m @@ -0,0 +1,132 @@ +// +// FMDatabaseAdditionsTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import +#import "FMDatabaseAdditions.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabaseAdditionsTests : FMDBTempDBTests + +@end + +@implementation FMDatabaseAdditionsTests + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testFunkyTableNames +{ + [self.db executeUpdate:@"create table '234 fds' (foo text)"]; + XCTAssertFalse([self.db hadError], @"table creation should have succeeded"); + FMResultSet *rs = [self.db getTableSchema:@"234 fds"]; + XCTAssertTrue([rs next], @"Schema should have succeded"); + [rs close]; + XCTAssertFalse([self.db hadError], @"There shouldn't be any errors"); +} + +- (void)testBoolForQuery +{ + BOOL result = [self.db boolForQuery:@"SELECT ? not null", @""]; + XCTAssertTrue(result, @"Empty strings should be considered true"); + + result = [self.db boolForQuery:@"SELECT ? not null", [NSMutableData data]]; + XCTAssertTrue(result, @"Empty mutable data should be considered true"); + + result = [self.db boolForQuery:@"SELECT ? not null", [NSData data]]; + XCTAssertTrue(result, @"Empty data should be considered true"); +} + + +- (void)testIntForQuery +{ + [self.db executeUpdate:@"create table t1 (a integer)"]; + [self.db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]]; + + XCTAssertEqual([self.db changes], 1, @"There should only be one change"); + + int ia = [self.db intForQuery:@"select a from t1 where a = ?", [NSNumber numberWithInt:5]]; + XCTAssertEqual(ia, 5, @"foo"); +} + +- (void)testDateForQuery +{ + NSDate *date = [NSDate date]; + [self.db executeUpdate:@"create table datetest (a double, b double, c double)"]; + [self.db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date]; + + NSDate *foo = [self.db dateForQuery:@"select b from datetest where c = 0"]; + XCTAssertEqualWithAccuracy([foo timeIntervalSinceDate:date], 0.0, 1.0, @"Dates should be the same to within a second"); +} + +- (void)testTableExists +{ + XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)"]); + + XCTAssertTrue([self.db tableExists:@"t4"]); + XCTAssertFalse([self.db tableExists:@"thisdoesntexist"]); + + FMResultSet *rs = [self.db getSchema]; + while ([rs next]) { + XCTAssertEqualObjects([rs stringForColumn:@"type"], @"table"); + } + +} + +- (void)testColumnExists +{ + [self.db executeUpdate:@"create table nulltest (a text, b text)"]; + + XCTAssertTrue([self.db columnExists:@"a" inTableWithName:@"nulltest"]); + XCTAssertTrue([self.db columnExists:@"b" inTableWithName:@"nulltest"]); + XCTAssertFalse([self.db columnExists:@"c" inTableWithName:@"nulltest"]); +} + +- (void)testUserVersion { + + [[self db] setUserVersion:12]; + + XCTAssertTrue([[self db] userVersion] == 12); +} + +- (void)testApplicationID { +#if SQLITE_VERSION_NUMBER >= 3007017 + uint32_t appID = NSHFSTypeCodeFromFileType(NSFileTypeForHFSTypeCode('fmdb')); + + [self.db setApplicationID:appID]; + + uint32_t rAppID = [self.db applicationID]; + + XCTAssertEqual(rAppID, appID); + + [self.db setApplicationIDString:@"acrn"]; + + NSString *s = [self.db applicationIDString]; + + XCTAssertEqualObjects(s, @"acrn"); +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + XCTFail("%@", errorMessage); + if (self.db.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + +@end diff --git a/Clocker/FMDB/Tests/FMDatabaseFTS3Tests.m b/Clocker/FMDB/Tests/FMDatabaseFTS3Tests.m new file mode 100755 index 0000000..e877412 --- /dev/null +++ b/Clocker/FMDB/Tests/FMDatabaseFTS3Tests.m @@ -0,0 +1,157 @@ +// +// FMDatabaseFTS3Tests.m +// fmdb +// +// Created by Seaview Software on 8/26/14. +// +// + +#import "FMDBTempDBTests.h" +#import "FMDatabase+FTS3.h" +#import "FMTokenizers.h" + +@interface FMDatabaseFTS3Tests : FMDBTempDBTests + +@end + +/** + This tokenizer extends the simple tokenizer to remove 's' from the end of each token if present. + Used for testing of the tokenization system. + */ +@interface FMDepluralizerTokenizer : NSObject ++ (instancetype)tokenizerWithBaseTokenizer:(id)tokenizer; +@property (nonatomic, strong) id m_baseTokenizer; +@end + +static id g_simpleTok = nil; +static id g_depluralizeTok = nil; + +@implementation FMDatabaseFTS3Tests + ++ (void)populateDatabase:(FMDatabase *)db +{ + [db executeUpdate:@"CREATE VIRTUAL TABLE mail USING fts3(subject, body)"]; + + [db executeUpdate:@"INSERT INTO mail VALUES('hello world', 'This message is a hello world message.')"]; + [db executeUpdate:@"INSERT INTO mail VALUES('urgent: serious', 'This mail is seen as a more serious mail')"]; + + // Create a tokenizer instance that will not be de-allocated when the method finishes. + g_simpleTok = [[FMSimpleTokenizer alloc] initWithLocale:NULL]; + [FMDatabase registerTokenizer:g_simpleTok withKey:@"testTok"]; + + g_depluralizeTok = [FMDepluralizerTokenizer tokenizerWithBaseTokenizer:g_simpleTok]; + [FMDatabase registerTokenizer:g_depluralizeTok withKey:@"depluralize"]; +} + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testOffsets +{ + FMResultSet *results = [self.db executeQuery:@"SELECT offsets(mail) FROM mail WHERE mail MATCH 'world'"]; + + if ([results next]) { + FMTextOffsets *offsets = [results offsetsForColumnIndex:0]; + + [offsets enumerateWithBlock:^(NSInteger columnNumber, NSInteger termNumber, NSRange matchRange) { + if (columnNumber == 0) { + XCTAssertEqual(termNumber, 0L); + XCTAssertEqual(matchRange.location, 6UL); + XCTAssertEqual(matchRange.length, 5UL); + } else if (columnNumber == 1) { + XCTAssertEqual(termNumber, 0L); + XCTAssertEqual(matchRange.location, 24UL); + XCTAssertEqual(matchRange.length, 5UL); + } + }]; + } +} + +- (void)testTokenizer +{ + [self.db installTokenizerModule]; + + BOOL ok = [self.db executeUpdate:@"CREATE VIRTUAL TABLE simple USING fts3(tokenize=fmdb testTok)"]; + XCTAssertTrue(ok, @"Failed to create virtual table: %@", [self.db lastErrorMessage]); + + // The FMSimpleTokenizer handles non-ASCII characters well, since it's based on CFStringTokenizer. + NSString *text = @"I like the band Queensrÿche. They are really great musicians."; + + ok = [self.db executeUpdate:@"INSERT INTO simple VALUES(?)", text]; + XCTAssertTrue(ok, @"Failed to insert data: %@", [self.db lastErrorMessage]); + + FMResultSet *results = [self.db executeQuery:@"SELECT * FROM simple WHERE simple MATCH ?", @"Queensrÿche"]; + XCTAssertTrue([results next], @"Failed to find result"); + + ok = [self.db executeUpdate:@"CREATE VIRTUAL TABLE depluralize_t USING fts3(tokenize=fmdb depluralize)"]; + XCTAssertTrue(ok, @"Failed to create virtual table with depluralize tokenizer: %@", [self.db lastErrorMessage]); + + ok = [self.db executeUpdate:@"INSERT INTO depluralize_t VALUES(?)", text]; + XCTAssertTrue(ok, @"Failed to insert data: %@", [self.db lastErrorMessage]); + + //If depluralization is working, searching for 'bands' should still provide a match as 'band' is in the text + results = [self.db executeQuery:@"SELECT * FROM depluralize_t WHERE depluralize_t MATCH ?", @"bands"]; + XCTAssertTrue([results next], @"Failed to find result"); + + //Demonstrate that depluralization mattered; we should NOT find any results when searching the simple table as it does not use that tokenizer + results = [self.db executeQuery:@"SELECT * FROM simple WHERE simple MATCH ?", @"bands"]; + XCTAssertFalse([results next], @"Found a result where none should be found"); +} + +@end + + + +#pragma mark - + +@implementation FMDepluralizerTokenizer + ++ (instancetype)tokenizerWithBaseTokenizer:(id)tokenizer +{ + return [[self alloc] initWithBaseTokenizer:tokenizer]; +} + +- (instancetype)initWithBaseTokenizer:(id)tokenizer +{ + NSParameterAssert(tokenizer); + + if ((self = [super init])) { + self.m_baseTokenizer = tokenizer; + } + return self; +} + +- (void)openTokenizerCursor:(FMTokenizerCursor *)cursor +{ + [self.m_baseTokenizer openTokenizerCursor:cursor]; +} + +- (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor +{ + BOOL done = [self.m_baseTokenizer nextTokenForCursor:cursor]; + + if (!done) { + NSMutableString *tokenString = (__bridge NSMutableString *)(cursor->tokenString); + if ([tokenString hasSuffix:@"s"]) + [tokenString deleteCharactersInRange:NSMakeRange(tokenString.length-1, 1)]; + } + + return done; +} + +- (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor +{ + [self.m_baseTokenizer closeTokenizerCursor:cursor]; +} + + +@end diff --git a/Clocker/FMDB/Tests/FMDatabaseFTS3WithModuleNameTests.m b/Clocker/FMDB/Tests/FMDatabaseFTS3WithModuleNameTests.m new file mode 100755 index 0000000..f48cc1e --- /dev/null +++ b/Clocker/FMDB/Tests/FMDatabaseFTS3WithModuleNameTests.m @@ -0,0 +1,83 @@ +// +// FMDatabaseFTS3WithKeyTests.m +// fmdb +// +// Created by Stephan Heilner on 1/21/15. +// +// + +#import "FMDBTempDBTests.h" +#import "FMDatabase+FTS3.h" +#import "FMTokenizers.h" + +@interface FMDatabaseFTS3WithModuleNameTests : FMDBTempDBTests + +@end + +static id g_testTok = nil; + +@implementation FMDatabaseFTS3WithModuleNameTests + ++ (void)populateDatabase:(FMDatabase *)db +{ + [db executeUpdate:@"CREATE VIRTUAL TABLE mail USING fts3(subject, body)"]; + + [db executeUpdate:@"INSERT INTO mail VALUES('hello world', 'This message is a hello world message.')"]; + [db executeUpdate:@"INSERT INTO mail VALUES('urgent: serious', 'This mail is seen as a more serious mail')"]; + + // Create a tokenizer instance that will not be de-allocated when the method finishes. + g_testTok = [[FMSimpleTokenizer alloc] initWithLocale:NULL]; + [FMDatabase registerTokenizer:g_testTok]; +} + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testOffsets +{ + FMResultSet *results = [self.db executeQuery:@"SELECT offsets(mail) FROM mail WHERE mail MATCH 'world'"]; + + if ([results next]) { + FMTextOffsets *offsets = [results offsetsForColumnIndex:0]; + + [offsets enumerateWithBlock:^(NSInteger columnNumber, NSInteger termNumber, NSRange matchRange) { + if (columnNumber == 0) { + XCTAssertEqual(termNumber, 0L); + XCTAssertEqual(matchRange.location, 6UL); + XCTAssertEqual(matchRange.length, 5UL); + } else if (columnNumber == 1) { + XCTAssertEqual(termNumber, 0L); + XCTAssertEqual(matchRange.location, 24UL); + XCTAssertEqual(matchRange.length, 5UL); + } + }]; + } +} + +- (void)testTokenizer +{ + [self.db installTokenizerModuleWithName:@"TestModuleName"]; + + BOOL ok = [self.db executeUpdate:@"CREATE VIRTUAL TABLE simple_fts USING fts3(tokenize=TestModuleName)"]; + XCTAssertTrue(ok, @"Failed to create virtual table: %@", [self.db lastErrorMessage]); + + // The FMSimpleTokenizer handles non-ASCII characters well, since it's based on CFStringTokenizer. + NSString *text = @"I like the band Queensrÿche. They are really great."; + + ok = [self.db executeUpdate:@"INSERT INTO simple_fts VALUES(?)", text]; + XCTAssertTrue(ok, @"Failed to insert data: %@", [self.db lastErrorMessage]); + + FMResultSet *results = [self.db executeQuery:@"SELECT * FROM simple_fts WHERE simple_fts MATCH ?", @"Queensrÿche"]; + XCTAssertTrue([results next], @"Failed to find result"); +} + +@end diff --git a/Clocker/FMDB/Tests/FMDatabasePoolTests.m b/Clocker/FMDB/Tests/FMDatabasePoolTests.m new file mode 100755 index 0000000..03fb086 --- /dev/null +++ b/Clocker/FMDB/Tests/FMDatabasePoolTests.m @@ -0,0 +1,303 @@ +// +// FMDatabasePoolTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import + +@interface FMDatabasePoolTests : FMDBTempDBTests + +@property FMDatabasePool *pool; + +@end + +@implementation FMDatabasePoolTests + ++ (void)populateDatabase:(FMDatabase *)db +{ + [db executeUpdate:@"create table easy (a text)"]; + [db executeUpdate:@"create table easy2 (a text)"]; + + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]]; + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]]; + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]]; + + [db executeUpdate:@"create table likefoo (foo text)"]; + [db executeUpdate:@"insert into likefoo values ('hi')"]; + [db executeUpdate:@"insert into likefoo values ('hello')"]; + [db executeUpdate:@"insert into likefoo values ('not')"]; +} + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. + + [self setPool:[FMDatabasePool databasePoolWithPath:self.databasePath]]; + + [[self pool] setDelegate:self]; + +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testPoolIsInitiallyEmpty +{ + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)0, @"Pool should be empty on creation"); +} + +- (void)testDatabaseCreation +{ + __block FMDatabase *db1; + + [self.pool inDatabase:^(FMDatabase *db) { + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1, @"Should only have one database at this point"); + + db1 = db; + + }]; + + [self.pool inDatabase:^(FMDatabase *db) { + XCTAssertEqualObjects(db, db1, @"We should get the same database back because there was no need to create a new one"); + + [self.pool inDatabase:^(FMDatabase *db2) { + XCTAssertNotEqualObjects(db2, db, @"We should get a different database because the first was in use."); + }]; + + }]; + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)2); + + [self.pool releaseAllDatabases]; + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)0, @"We should be back to zero databases again"); +} + +- (void)testCheckedInCheckoutOutCount +{ + [self.pool inDatabase:^(FMDatabase *aDb) { + + XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)0); + XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)1); + + XCTAssertTrue(([aDb executeUpdate:@"insert into easy (a) values (?)", @"hi"])); + + // just for fun. + FMResultSet *rs = [aDb executeQuery:@"select * from easy"]; + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + while ([rs next]) { ; } // whatevers. + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); + XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)0); + XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)1); + }]; + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); +} + +- (void)testMaximumDatabaseLimit +{ + [self.pool setMaximumNumberOfDatabasesToCreate:2]; + + [self.pool inDatabase:^(FMDatabase *db) { + [self.pool inDatabase:^(FMDatabase *db2) { + [self.pool inDatabase:^(FMDatabase *db3) { + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)2); + XCTAssertNil(db3, @"The third database must be nil because we have a maximum of 2 databases in the pool"); + }]; + + }]; + }]; +} + +- (void)testTransaction +{ + [self.pool inTransaction:^(FMDatabase *adb, BOOL *rollback) { + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]]; + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]]; + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]]; + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); + XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)0); + XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)1); + }]; + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); + XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)1); + XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)0); +} + +- (void)testSelect +{ + [self.pool inDatabase:^(FMDatabase *db) { + FMResultSet *rs = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1001]]; + XCTAssertNotNil(rs); + XCTAssertTrue ([rs next]); + XCTAssertFalse([rs next]); + }]; +} + +- (void)testTransactionRollback +{ + [self.pool inDeferredTransaction:^(FMDatabase *adb, BOOL *rollback) { + XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1004]])); + XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1005]])); + XCTAssertTrue([[adb executeQuery:@"select * from easy where a == '1004'"] next], @"1004 should be in database"); + + *rollback = YES; + }]; + + [self.pool inDatabase:^(FMDatabase *db) { + XCTAssertFalse([[db executeQuery:@"select * from easy where a == '1004'"] next], @"1004 should not be in database"); + }]; + + XCTAssertEqual([self.pool countOfOpenDatabases], (NSUInteger)1); + XCTAssertEqual([self.pool countOfCheckedInDatabases], (NSUInteger)1); + XCTAssertEqual([self.pool countOfCheckedOutDatabases], (NSUInteger)0); +} + +- (void)testSavepoint +{ + NSError *err = [self.pool inSavePoint:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1006]]; + }]; + + XCTAssertNil(err); +} + +- (void)testNestedSavepointRollback +{ + NSError *err = [self.pool inSavePoint:^(FMDatabase *adb, BOOL *rollback) { + XCTAssertFalse([adb hadError]); + XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1009]])); + + [adb inSavePoint:^(BOOL *arollback) { + XCTAssertTrue(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1010]])); + *arollback = YES; + }]; + }]; + + + XCTAssertNil(err); + + [self.pool inDatabase:^(FMDatabase *db) { + FMResultSet *rs = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1009]]; + XCTAssertTrue ([rs next]); + XCTAssertFalse([rs next]); // close it out. + + rs = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1010]]; + XCTAssertFalse([rs next]); + }]; +} + +- (void)testLikeStringQuery +{ + [self.pool inDatabase:^(FMDatabase *db) { + int count = 0; + FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; + while ([rsl next]) { + count++; + } + + XCTAssertEqual(count, 2); + + count = 0; + rsl = [db executeQuery:@"select * from likefoo where foo like ?", @"h%"]; + while ([rsl next]) { + count++; + } + + XCTAssertEqual(count, 2); + + }]; +} + +- (void)testStressTest +{ + size_t ops = 128; + + dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(ops, dqueue, ^(size_t nby) { + + // just mix things up a bit for demonstration purposes. + if (nby % 2 == 1) { + + [NSThread sleepForTimeInterval:.001]; + } + + [self.pool inDatabase:^(FMDatabase *db) { + FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; + XCTAssertNotNil(rsl); + int i = 0; + while ([rsl next]) { + i++; + if (nby % 3 == 1) { + [NSThread sleepForTimeInterval:.0005]; + } + } + XCTAssertEqual(i, 2); + }]; + }); + + XCTAssert([self.pool countOfOpenDatabases] < 64, @"There should be significantly less than 64 databases after that stress test"); +} + + +- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database { + [database setMaxBusyRetryTimeInterval:10]; + // [database setCrashOnErrors:YES]; + return YES; +} + +- (void)testReadWriteStressTest +{ + int ops = 16; + + dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(ops, dqueue, ^(size_t nby) { + + // just mix things up a bit for demonstration purposes. + if (nby % 2 == 1) { + [NSThread sleepForTimeInterval:.01]; + + [self.pool inTransaction:^(FMDatabase *db, BOOL *rollback) { + FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; + XCTAssertNotNil(rsl); + while ([rsl next]) { + ;// whatever. + } + + }]; + + } + + if (nby % 3 == 1) { + [NSThread sleepForTimeInterval:.01]; + } + + [self.pool inTransaction:^(FMDatabase *db, BOOL *rollback) { + XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('1')"]); + XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('2')"]); + XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('3')"]); + }]; + }); + + [self.pool releaseAllDatabases]; + + [self.pool inDatabase:^(FMDatabase *db) { + XCTAssertTrue([db executeUpdate:@"insert into likefoo values ('1')"]); + }]; +} + +@end diff --git a/Clocker/FMDB/Tests/FMDatabaseQueueTests.m b/Clocker/FMDB/Tests/FMDatabaseQueueTests.m new file mode 100755 index 0000000..b1c572a --- /dev/null +++ b/Clocker/FMDB/Tests/FMDatabaseQueueTests.m @@ -0,0 +1,182 @@ +// +// FMDatabaseQueueTests.m +// fmdb +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import +#import "FMDatabaseQueue.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabaseQueueTests : FMDBTempDBTests + +@property FMDatabaseQueue *queue; + +@end + +@implementation FMDatabaseQueueTests + ++ (void)populateDatabase:(FMDatabase *)db +{ + [db executeUpdate:@"create table easy (a text)"]; + + [db executeUpdate:@"create table qfoo (foo text)"]; + [db executeUpdate:@"insert into qfoo values ('hi')"]; + [db executeUpdate:@"insert into qfoo values ('hello')"]; + [db executeUpdate:@"insert into qfoo values ('not')"]; +} + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. + + self.queue = [FMDatabaseQueue databaseQueueWithPath:self.databasePath]; +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testQueueSelect +{ + [self.queue inDatabase:^(FMDatabase *adb) { + int count = 0; + FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; + while ([rsl next]) { + count++; + } + + XCTAssertEqual(count, 2); + + count = 0; + rsl = [adb executeQuery:@"select * from qfoo where foo like ?", @"h%"]; + while ([rsl next]) { + count++; + } + + XCTAssertEqual(count, 2); + }]; +} + +- (void)testReadOnlyQueue +{ + FMDatabaseQueue *queue2 = [FMDatabaseQueue databaseQueueWithPath:self.databasePath flags:SQLITE_OPEN_READONLY]; + XCTAssertNotNil(queue2); + + { + [queue2 inDatabase:^(FMDatabase *db2) { + FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM qfoo"]; + XCTAssertNotNil(rs1); + + [rs1 close]; + + XCTAssertFalse(([db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]), @"Insert should fail because this is a read-only database"); + }]; + + [queue2 close]; + + // Check that when we re-open the database, it's still read-only + [queue2 inDatabase:^(FMDatabase *db2) { + FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM qfoo"]; + XCTAssertNotNil(rs1); + + [rs1 close]; + + XCTAssertFalse(([db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]), @"Insert should fail because this is a read-only database"); + }]; + } +} + +- (void)testStressTest +{ + size_t ops = 16; + + dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(ops, dqueue, ^(size_t nby) { + + // just mix things up a bit for demonstration purposes. + if (nby % 2 == 1) { + [NSThread sleepForTimeInterval:.01]; + + [self.queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { + FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; + while ([rsl next]) { + ;// whatever. + } + }]; + + } + + if (nby % 3 == 1) { + [NSThread sleepForTimeInterval:.01]; + } + + [self.queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { + XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('1')"]); + XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('2')"]); + XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('3')"]); + }]; + }); + + [self.queue close]; + + [self.queue inDatabase:^(FMDatabase *adb) { + XCTAssertTrue([adb executeUpdate:@"insert into qfoo values ('1')"]); + }]; +} + +- (void)testTransaction +{ + [self.queue inDatabase:^(FMDatabase *adb) { + [adb executeUpdate:@"create table transtest (a integer)"]; + XCTAssertTrue([adb executeUpdate:@"insert into transtest values (1)"]); + XCTAssertTrue([adb executeUpdate:@"insert into transtest values (2)"]); + + int rowCount = 0; + FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; + while ([ars next]) { + rowCount++; + } + + XCTAssertEqual(rowCount, 2); + }]; + + [self.queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { + XCTAssertTrue([adb executeUpdate:@"insert into transtest values (3)"]); + + if (YES) { + // uh oh!, something went wrong (not really, this is just a test + *rollback = YES; + return; + } + + XCTFail(@"This shouldn't be reached"); + }]; + + [self.queue inDatabase:^(FMDatabase *adb) { + + int rowCount = 0; + FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; + while ([ars next]) { + rowCount++; + } + + XCTAssertFalse([adb hasOpenResultSets]); + + XCTAssertEqual(rowCount, 2); + }]; + +} + +@end diff --git a/Clocker/FMDB/Tests/FMDatabaseTests.m b/Clocker/FMDB/Tests/FMDatabaseTests.m new file mode 100755 index 0000000..9c423dc --- /dev/null +++ b/Clocker/FMDB/Tests/FMDatabaseTests.m @@ -0,0 +1,1183 @@ +// +// Tests.m +// Tests +// +// Created by Graham Dennis on 24/11/2013. +// +// + +#import "FMDBTempDBTests.h" +#import "FMDatabase.h" +#import "FMDatabaseAdditions.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + + +@interface FMDatabaseTests : FMDBTempDBTests + +@end + +@implementation FMDatabaseTests + ++ (void)populateDatabase:(FMDatabase *)db +{ + [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; + + [db beginTransaction]; + int i = 0; + while (i++ < 20) { + [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , + @"hi'", // look! I put in a ', and I'm not escaping it! + [NSString stringWithFormat:@"number %d", i], + [NSNumber numberWithInt:i], + [NSDate date], + [NSNumber numberWithFloat:2.2f]]; + } + [db commit]; + + // do it again, just because + [db beginTransaction]; + i = 0; + while (i++ < 20) { + [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , + @"hi again'", // look! I put in a ', and I'm not escaping it! + [NSString stringWithFormat:@"number %d", i], + [NSNumber numberWithInt:i], + [NSDate date], + [NSNumber numberWithFloat:2.2f]]; + } + [db commit]; + + [db executeUpdate:@"create table t3 (a somevalue)"]; + + [db beginTransaction]; + for (int i=0; i < 20; i++) { + [db executeUpdate:@"insert into t3 (a) values (?)", [NSNumber numberWithInt:i]]; + } + [db commit]; +} + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. + +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; + +} + +- (void)testOpenWithVFS +{ + // create custom vfs + sqlite3_vfs vfs = *sqlite3_vfs_find(NULL); + vfs.zName = "MyCustomVFS"; + XCTAssertEqual(SQLITE_OK, sqlite3_vfs_register(&vfs, 0)); + // use custom vfs to open a in memory database + FMDatabase *db = [[FMDatabase alloc] initWithPath:@":memory:"]; + [db openWithFlags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"MyCustomVFS"]; + XCTAssertFalse([db hadError], @"Open with a custom VFS should have succeeded"); +} + +- (void)testFailOnOpenWithUnknownVFS +{ + FMDatabase *db = [[FMDatabase alloc] initWithPath:@":memory:"]; + [db openWithFlags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:@"UnknownVFS"]; + XCTAssertTrue([db hadError], @"Should have failed"); +} + +- (void)testFailOnUnopenedDatabase +{ + [self.db close]; + + XCTAssertNil([self.db executeQuery:@"select * from table"], @"Shouldn't get results from an empty table"); + XCTAssertTrue([self.db hadError], @"Should have failed"); +} + +- (void)testFailOnBadStatement +{ + XCTAssertFalse([self.db executeUpdate:@"blah blah blah"], @"Invalid statement should fail"); + XCTAssertTrue([self.db hadError], @"Should have failed"); +} + +- (void)testFailOnBadStatementWithError +{ + NSError *error = nil; + XCTAssertFalse([self.db executeUpdate:@"blah blah blah" withErrorAndBindings:&error], @"Invalid statement should fail"); + XCTAssertNotNil(error, @"Should have a non-nil NSError"); + XCTAssertEqual([error code], (NSInteger)SQLITE_ERROR, @"Error should be SQLITE_ERROR"); +} + +- (void)testPragmaJournalMode +{ + FMResultSet *ps = [self.db executeQuery:@"pragma journal_mode=delete"]; + XCTAssertFalse([self.db hadError], @"pragma should have succeeded"); + XCTAssertNotNil(ps, @"Result set should be non-nil"); + XCTAssertTrue([ps next], @"Result set should have a next result"); + [ps close]; +} + +- (void)testPragmaPageSize +{ + [self.db executeUpdate:@"PRAGMA page_size=2048"]; + XCTAssertFalse([self.db hadError], @"pragma should have succeeded"); +} + +- (void)testVacuum +{ + [self.db executeUpdate:@"VACUUM"]; + XCTAssertFalse([self.db hadError], @"VACUUM should have succeeded"); +} + +- (void)testSelectULL +{ + // Unsigned long long + [self.db executeUpdate:@"create table ull (a integer)"]; + + [self.db executeUpdate:@"insert into ull (a) values (?)", [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]]; + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); + + FMResultSet *rs = [self.db executeQuery:@"select a from ull"]; + while ([rs next]) { + XCTAssertEqual([rs unsignedLongLongIntForColumnIndex:0], ULLONG_MAX, @"Result should be ULLONG_MAX"); + XCTAssertEqual([rs unsignedLongLongIntForColumn:@"a"], ULLONG_MAX, @"Result should be ULLONG_MAX"); + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testSelectByColumnName +{ + FMResultSet *rs = [self.db executeQuery:@"select rowid,* from test where a = ?", @"hi"]; + + XCTAssertNotNil(rs, @"Should have a non-nil result set"); + + while ([rs next]) { + [rs intForColumn:@"c"]; + XCTAssertNotNil([rs stringForColumn:@"b"], @"Should have non-nil string for 'b'"); + XCTAssertNotNil([rs stringForColumn:@"a"], @"Should have non-nil string for 'a'"); + XCTAssertNotNil([rs stringForColumn:@"rowid"], @"Should have non-nil string for 'rowid'"); + XCTAssertNotNil([rs dateForColumn:@"d"], @"Should have non-nil date for 'd'"); + [rs doubleForColumn:@"d"]; + [rs doubleForColumn:@"e"]; + + XCTAssertEqualObjects([rs columnNameForIndex:0], @"rowid", @"Wrong column name for result set column number"); + XCTAssertEqualObjects([rs columnNameForIndex:1], @"a", @"Wrong column name for result set column number"); + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testSelectWithIndexedAndKeyedSubscript +{ + FMResultSet *rs = [self.db executeQuery:@"select rowid, a, b, c from test"]; + + XCTAssertNotNil(rs, @"Should have a non-nil result set"); + + while ([rs next]) { + XCTAssertEqualObjects(rs[0], rs[@"rowid"], @"Column zero should be equal to 'rowid'"); + XCTAssertEqualObjects(rs[1], rs[@"a"], @"Column 1 should be equal to 'a'"); + XCTAssertEqualObjects(rs[2], rs[@"b"], @"Column 2 should be equal to 'b'"); + XCTAssertEqualObjects(rs[3], rs[@"c"], @"Column 3 should be equal to 'c'"); + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testBusyRetryTimeout +{ + [self.db executeUpdate:@"create table t1 (a integer)"]; + [self.db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]]; + + [self.db setMaxBusyRetryTimeInterval:2]; + + FMDatabase *newDB = [FMDatabase databaseWithPath:self.databasePath]; + [newDB open]; + + FMResultSet *rs = [newDB executeQuery:@"select rowid,* from test where a = ?", @"hi'"]; + [rs next]; // just grab one... which will keep the db locked + + XCTAssertFalse([self.db executeUpdate:@"insert into t1 values (5)"], @"Insert should fail because the db is locked by a read"); + XCTAssertEqual([self.db lastErrorCode], SQLITE_BUSY, @"SQLITE_BUSY should be the last error"); + + [rs close]; + [newDB close]; + + XCTAssertTrue([self.db executeUpdate:@"insert into t1 values (5)"], @"The database shouldn't be locked at this point"); +} + +- (void)testCaseSensitiveResultDictionary +{ + // case sensitive result dictionary test + [self.db executeUpdate:@"create table cs (aRowName integer, bRowName text)"]; + [self.db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)", [NSNumber numberWithBool:1], @"hello"]; + + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); + + FMResultSet *rs = [self.db executeQuery:@"select * from cs"]; + while ([rs next]) { + NSDictionary *d = [rs resultDictionary]; + + XCTAssertNotNil([d objectForKey:@"aRowName"], @"aRowName should be non-nil"); + XCTAssertNil([d objectForKey:@"arowname"], @"arowname should be nil"); + XCTAssertNotNil([d objectForKey:@"bRowName"], @"bRowName should be non-nil"); + XCTAssertNil([d objectForKey:@"browname"], @"browname should be nil"); + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testBoolInsert +{ + [self.db executeUpdate:@"create table btest (aRowName integer)"]; + [self.db executeUpdate:@"insert into btest (aRowName) values (?)", [NSNumber numberWithBool:12]]; + + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); + + FMResultSet *rs = [self.db executeQuery:@"select * from btest"]; + while ([rs next]) { + + XCTAssertTrue([rs boolForColumnIndex:0], @"first column should be true."); + XCTAssertTrue([rs intForColumnIndex:0] == 1, @"first column should be equal to 1 - it was %d.", [rs intForColumnIndex:0]); + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testNamedParametersCount +{ + XCTAssertTrue([self.db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]); + + NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; + [dictionaryArgs setObject:@"Text1" forKey:@"a"]; + [dictionaryArgs setObject:@"Text2" forKey:@"b"]; + [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; + [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; + XCTAssertTrue([self.db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); + + FMResultSet *rs = [self.db executeQuery:@"select * from namedparamcounttest"]; + + XCTAssertNotNil(rs); + + [rs next]; + + XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1"); + XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2"); + XCTAssertEqual([rs intForColumn:@"c"], 1); + XCTAssertEqual([rs doubleForColumn:@"d"], 2.0); + + [rs close]; + + // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since + // a is in there, and that's all we need. + rs = [self.db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs]; + + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + [rs close]; + + // ***** Please note the following codes ***** + + dictionaryArgs = [NSMutableDictionary dictionary]; + + [dictionaryArgs setObject:@"NewText1" forKey:@"a"]; + [dictionaryArgs setObject:@"NewText2" forKey:@"b"]; + [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"]; + + XCTAssertTrue([self.db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs]); + +} + +- (void)testBlobs +{ + [self.db executeUpdate:@"create table blobTable (a text, b blob)"]; + + // let's read an image from safari's app bundle. + NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"]; + if (safariCompass) { + [self.db executeUpdate:@"insert into blobTable (a, b) values (?, ?)", @"safari's compass", safariCompass]; + + FMResultSet *rs = [self.db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"]; + XCTAssertTrue([rs next]); + NSData *readData = [rs dataForColumn:@"b"]; + XCTAssertEqualObjects(readData, safariCompass); + + // ye shall read the header for this function, or suffer the consequences. + NSData *readDataNoCopy = [rs dataNoCopyForColumn:@"b"]; + XCTAssertEqualObjects(readDataNoCopy, safariCompass); + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); + } +} + +- (void)testNullValues +{ + [self.db executeUpdate:@"create table t2 (a integer, b integer)"]; + + BOOL result = [self.db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]]; + XCTAssertTrue(result, @"Failed to insert a nil value"); + + FMResultSet *rs = [self.db executeQuery:@"select * from t2"]; + while ([rs next]) { + XCTAssertNil([rs stringForColumnIndex:0], @"Wasn't able to retrieve a null string"); + XCTAssertEqualObjects([rs stringForColumnIndex:1], @"5"); + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testNestedResultSets +{ + FMResultSet *rs = [self.db executeQuery:@"select * from t3"]; + while ([rs next]) { + int foo = [rs intForColumnIndex:0]; + + int newVal = foo + 100; + + [self.db executeUpdate:@"update t3 set a = ? where a = ?", [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]]; + + FMResultSet *rs2 = [self.db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]]; + [rs2 next]; + + XCTAssertEqual([rs2 intForColumnIndex:0], newVal); + + [rs2 close]; + } + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testNSNullInsertion +{ + [self.db executeUpdate:@"create table nulltest (a text, b text)"]; + + [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", [NSNull null], @"a"]; + [self.db executeUpdate:@"insert into nulltest (a, b) values (?, ?)", nil, @"b"]; + + FMResultSet *rs = [self.db executeQuery:@"select * from nulltest"]; + + while ([rs next]) { + XCTAssertNil([rs stringForColumnIndex:0]); + XCTAssertNotNil([rs stringForColumnIndex:1]); + } + + [rs close]; + + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testNullDates +{ + NSDate *date = [NSDate date]; + [self.db executeUpdate:@"create table datetest (a double, b double, c double)"]; + [self.db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date]; + + FMResultSet *rs = [self.db executeQuery:@"select * from datetest"]; + + XCTAssertNotNil(rs); + + while ([rs next]) { + + NSDate *b = [rs dateForColumnIndex:1]; + NSDate *c = [rs dateForColumnIndex:2]; + + XCTAssertNil([rs dateForColumnIndex:0]); + XCTAssertNotNil(c, @"zero date shouldn't be nil"); + + XCTAssertEqualWithAccuracy([b timeIntervalSinceDate:date], 0.0, 1.0, @"Dates should be the same to within a second"); + XCTAssertEqualWithAccuracy([c timeIntervalSince1970], 0.0, 1.0, @"Dates should be the same to within a second"); + } + [rs close]; + + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testLotsOfNULLs +{ + NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"]; + + if (!safariCompass) + return; + + [self.db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"]; + + [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]]; + [self.db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]]; + + FMResultSet *rs = [self.db executeQuery:@"select * from nulltest2"]; + + while ([rs next]) { + + int i = [rs intForColumnIndex:2]; + + if (i == 12) { + // it's the first row we inserted. + XCTAssertFalse([rs columnIndexIsNull:0]); + XCTAssertFalse([rs columnIndexIsNull:1]); + XCTAssertFalse([rs columnIndexIsNull:2]); + XCTAssertFalse([rs columnIndexIsNull:3]); + XCTAssertFalse([rs columnIndexIsNull:4]); + XCTAssertTrue( [rs columnIndexIsNull:5]); + + XCTAssertEqualObjects([rs dataForColumn:@"d"], safariCompass); + XCTAssertNil([rs dataForColumn:@"notthere"]); + XCTAssertNil([rs stringForColumnIndex:-2], @"Negative columns should return nil results"); + XCTAssertTrue([rs boolForColumnIndex:4]); + XCTAssertTrue([rs boolForColumn:@"b"]); + + XCTAssertEqualWithAccuracy(4.4, [rs doubleForColumn:@"f"], 0.0000001, @"Saving a float and returning it as a double shouldn't change the result much"); + + XCTAssertEqual([rs intForColumn:@"i"], 12); + XCTAssertEqual([rs intForColumnIndex:2], 12); + + XCTAssertEqual([rs intForColumnIndex:12], 0, @"Non-existent columns should return zero for ints"); + XCTAssertEqual([rs intForColumn:@"notthere"], 0, @"Non-existent columns should return zero for ints"); + + XCTAssertEqual([rs longForColumn:@"i"], 12l); + XCTAssertEqual([rs longLongIntForColumn:@"i"], 12ll); + } + else { + // let's test various null things. + + XCTAssertTrue([rs columnIndexIsNull:0]); + XCTAssertTrue([rs columnIndexIsNull:1]); + XCTAssertTrue([rs columnIndexIsNull:2]); + XCTAssertTrue([rs columnIndexIsNull:3]); + XCTAssertTrue([rs columnIndexIsNull:4]); + XCTAssertTrue([rs columnIndexIsNull:5]); + + + XCTAssertNil([rs dataForColumn:@"d"]); + } + } + + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testUTF8Strings +{ + [self.db executeUpdate:@"create table utest (a text)"]; + [self.db executeUpdate:@"insert into utest values (?)", @"/übertest"]; + + FMResultSet *rs = [self.db executeQuery:@"select * from utest where a = ?", @"/übertest"]; + XCTAssertTrue([rs next]); + [rs close]; + XCTAssertFalse([self.db hasOpenResultSets], @"Shouldn't have any open result sets"); + XCTAssertFalse([self.db hadError], @"Shouldn't have any errors"); +} + +- (void)testArgumentsInArray +{ + [self.db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"]; + [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]]; + [self.db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]]; + + + FMResultSet *rs = [self.db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]]; + + XCTAssertTrue([rs next]); + + XCTAssertTrue([rs hasAnotherRow]); + XCTAssertFalse([self.db hadError]); + + XCTAssertEqualObjects([rs stringForColumnIndex:0], @"one"); + XCTAssertEqual([rs intForColumnIndex:1], 2); + + XCTAssertTrue([rs next]); + + XCTAssertEqual([rs intForColumnIndex:1], 3); + + XCTAssertFalse([rs next]); + XCTAssertFalse([rs hasAnotherRow]); +} + +- (void)testColumnNamesContainingPeriods +{ + XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)"]); + [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"]; + + FMResultSet *rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"]; + + XCTAssertNotNil(rs); + + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one"); + XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two"); + + XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two"), 0, @"String comparison should return zero"); + + [rs close]; + + // let's try these again, with the withArgumentsInArray: variation + XCTAssertTrue([self.db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]); + XCTAssertTrue([self.db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]); + + [self.db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]]; + + rs = [self.db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]]; + + XCTAssertNotNil(rs); + + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"t4.a"], @"one"); + XCTAssertEqualObjects([rs stringForColumn:@"b"], @"two"); + + XCTAssertEqual(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two"), 0, @"String comparison should return zero"); + + [rs close]; +} + +- (void)testFormatStringParsing +{ + XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]); + [self.db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll]; + + FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42]; + XCTAssertNotNil(rs); + + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"a"], @"text"); + XCTAssertEqual([rs intForColumn:@"b"], 42); + XCTAssertEqualObjects([rs stringForColumn:@"c"], @"BLOB"); + XCTAssertEqualObjects([rs stringForColumn:@"d"], @"d"); + XCTAssertEqual([rs longLongIntForColumn:@"e"], 12345678901234ll); + + [rs close]; +} + +- (void)testFormatStringParsingWithSizePrefixes +{ + XCTAssertTrue([self.db executeUpdate:@"create table t55 (a text, b int, c float)"]); + short testShort = -4; + float testFloat = 5.5; + [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat]; + + unsigned short testUShort = 6; + [self.db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat]; + + + FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"]; + XCTAssertNotNil(rs); + + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a"); + XCTAssertEqual([rs intForColumn:@"b"], -4); + XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5"); + + + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"a"], @"a"); + XCTAssertEqual([rs intForColumn:@"b"], 6); + XCTAssertEqualObjects([rs stringForColumn:@"c"], @"5.5"); + + [rs close]; +} + +- (void)testFormatStringParsingWithNilValue +{ + XCTAssertTrue([self.db executeUpdate:@"create table tatwhat (a text)"]); + + BOOL worked = [self.db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil]; + + XCTAssertTrue(worked); + + FMResultSet *rs = [self.db executeQueryWithFormat:@"select * from tatwhat"]; + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + XCTAssertTrue([rs columnIndexIsNull:0]); + + XCTAssertFalse([rs next]); +} + +- (void)testUpdateWithErrorAndBindings +{ + XCTAssertTrue([self.db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]); + + NSError *err = nil; + BOOL result = [self.db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]]; + XCTAssertTrue(result); +} + +- (void)testSelectWithEmptyArgumentsArray +{ + FMResultSet *rs = [self.db executeQuery:@"select * from test where a=?" withArgumentsInArray:@[]]; + XCTAssertNil(rs); +} + +- (void)testDatabaseAttach +{ + NSFileManager *fileManager = [NSFileManager new]; + [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil]; + + FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"]; + XCTAssertTrue([dbB open]); + XCTAssertTrue([dbB executeUpdate:@"create table attached (a text)"]); + XCTAssertTrue(([dbB executeUpdate:@"insert into attached values (?)", @"test"])); + XCTAssertTrue([dbB close]); + + [self.db executeUpdate:@"attach database '/tmp/attachme.db' as attack"]; + + FMResultSet *rs = [self.db executeQuery:@"select * from attack.attached"]; + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + [rs close]; +} + +- (void)testNamedParameters +{ + // ------------------------------------------------------------------------------- + // Named parameters. + XCTAssertTrue([self.db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]); + + NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; + [dictionaryArgs setObject:@"Text1" forKey:@"a"]; + [dictionaryArgs setObject:@"Text2" forKey:@"b"]; + [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; + [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; + XCTAssertTrue([self.db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); + + FMResultSet *rs = [self.db executeQuery:@"select * from namedparamtest"]; + + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"a"], @"Text1"); + XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2"); + XCTAssertEqual([rs intForColumn:@"c"], 1); + XCTAssertEqual([rs doubleForColumn:@"d"], 2.0); + + [rs close]; + + + dictionaryArgs = [NSMutableDictionary dictionary]; + + [dictionaryArgs setObject:@"Text2" forKey:@"blah"]; + + rs = [self.db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs]; + + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs stringForColumn:@"b"], @"Text2"); + + [rs close]; +} + +- (void)testPragmaDatabaseList +{ + FMResultSet *rs = [self.db executeQuery:@"pragma database_list"]; + int counter = 0; + while ([rs next]) { + counter++; + XCTAssertEqualObjects([rs stringForColumn:@"file"], self.databasePath); + } + XCTAssertEqual(counter, 1, @"Only one database should be attached"); +} + +- (void)testCachedStatementsInUse +{ + [self.db setShouldCacheStatements:true]; + + [self.db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"]; + [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"]; + [self.db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"]; + + XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); + XCTAssertTrue([[self.db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); +} + +- (void)testStatementCachingWorks +{ + [self.db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"]; + [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; + [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; + [self.db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"]; + + [self.db setShouldCacheStatements:YES]; + + // two iterations. + // the first time through no statements will be from the cache. + // the second time through all statements come from the cache. + for (int i = 1; i <= 2; i++ ) { + + FMResultSet* rs1 = [self.db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows... + XCTAssertNotNil(rs1); + XCTAssertTrue([rs1 next]); + + // confirm that we're seeing the benefits of caching. + XCTAssertEqual([[rs1 statement] useCount], (long)i); + + FMResultSet* rs2 = [self.db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row + XCTAssertNotNil(rs2); + XCTAssertTrue([rs2 next]); + XCTAssertEqual([[rs2 statement] useCount], (long)i); + + // This is the primary check - with the old implementation of statement caching, rs2 would have rejiggered the (cached) statement used by rs1, making this test fail to return the 2nd row in rs1. + XCTAssertTrue([rs1 next]); + + [rs1 close]; + [rs2 close]; + } + +} + +/* + Test the date format + */ + +- (void)testDateFormat +{ + void (^testOneDateFormat)(FMDatabase *, NSDate *) = ^( FMDatabase *db, NSDate *testDate ){ + [db executeUpdate:@"DROP TABLE IF EXISTS test_format"]; + [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"]; + [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate]; + + FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"]; + XCTAssertNotNil(rs); + XCTAssertTrue([rs next]); + + XCTAssertEqualObjects([rs dateForColumnIndex:0], testDate); + + [rs close]; + }; + + NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; + + NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"]; + + // test timestamp dates (ensuring our change does not break those) + testOneDateFormat(self.db,testDate); + + // now test the string-based timestamp + [self.db setDateFormat:fmt]; + testOneDateFormat(self.db, testDate); +} + +- (void)testColumnNameMap +{ + XCTAssertTrue([self.db executeUpdate:@"create table colNameTest (a, b, c, d)"]); + XCTAssertTrue([self.db executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]); + + FMResultSet *ars = [self.db executeQuery:@"select * from colNameTest"]; + XCTAssertNotNil(ars); + + NSDictionary *d = [ars columnNameToIndexMap]; + XCTAssertEqual([d count], (NSUInteger)4); + + XCTAssertEqualObjects([d objectForKey:@"a"], @0); + XCTAssertEqualObjects([d objectForKey:@"b"], @1); + XCTAssertEqualObjects([d objectForKey:@"c"], @2); + XCTAssertEqualObjects([d objectForKey:@"d"], @3); + +} + +- (void)testCustomFunction +{ + [self.db executeUpdate:@"create table ftest (foo text)"]; + [self.db executeUpdate:@"insert into ftest values ('hello')"]; + [self.db executeUpdate:@"insert into ftest values ('hi')"]; + [self.db executeUpdate:@"insert into ftest values ('not h!')"]; + [self.db executeUpdate:@"insert into ftest values ('definitely not h!')"]; + + [self.db makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(void *context, int aargc, void **aargv) { + if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { + + @autoreleasepool { + + const char *c = (const char *)sqlite3_value_text(aargv[0]); + + NSString *s = [NSString stringWithUTF8String:c]; + + sqlite3_result_int(context, [s hasPrefix:@"h"]); + } + } + else { + XCTFail(@"Unknown format for StringStartsWithH (%d)", sqlite3_value_type(aargv[0])); + sqlite3_result_null(context); + } + }]; + + int rowCount = 0; + FMResultSet *ars = [self.db executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; + while ([ars next]) { + rowCount++; + + } + XCTAssertEqual(rowCount, 2); + +} + +- (void)testVersionNumber { + XCTAssertTrue([FMDatabase FMDBVersion] == 0x0262); // this is going to break everytime we bump it. +} + +- (void)testExecuteStatements +{ + BOOL success; + + NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);" + "create table bulktest2 (id integer primary key autoincrement, y text);" + "create table bulktest3 (id integer primary key autoincrement, z text);" + "insert into bulktest1 (x) values ('XXX');" + "insert into bulktest2 (y) values ('YYY');" + "insert into bulktest3 (z) values ('ZZZ');"; + + success = [self.db executeStatements:sql]; + + XCTAssertTrue(success, @"bulk create"); + + sql = @"select count(*) as count from bulktest1;" + "select count(*) as count from bulktest2;" + "select count(*) as count from bulktest3;"; + + success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) { + NSInteger count = [dictionary[@"count"] integerValue]; + XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary); + return 0; + }]; + + XCTAssertTrue(success, @"bulk select"); + + sql = @"drop table bulktest1;" + "drop table bulktest2;" + "drop table bulktest3;"; + + success = [self.db executeStatements:sql]; + + XCTAssertTrue(success, @"bulk drop"); +} + +- (void)testCharAndBoolTypes +{ + XCTAssertTrue([self.db executeUpdate:@"create table charBoolTest (a, b, c)"]); + + BOOL success = [self.db executeUpdate:@"insert into charBoolTest values (?, ?, ?)", @YES, @NO, @('x')]; + XCTAssertTrue(success, @"Unable to insert values"); + + FMResultSet *rs = [self.db executeQuery:@"select * from charBoolTest"]; + XCTAssertNotNil(rs); + + XCTAssertTrue([rs next], @"Did not return row"); + + XCTAssertEqual([rs boolForColumn:@"a"], true); + XCTAssertEqualObjects([rs objectForColumnName:@"a"], @YES); + + XCTAssertEqual([rs boolForColumn:@"b"], false); + XCTAssertEqualObjects([rs objectForColumnName:@"b"], @NO); + + XCTAssertEqual([rs intForColumn:@"c"], 'x'); + XCTAssertEqualObjects([rs objectForColumnName:@"c"], @('x')); + + [rs close]; + + XCTAssertTrue([self.db executeUpdate:@"drop table charBoolTest"], @"Did not drop table"); + +} + +- (void)testSqliteLibVersion +{ + NSString *version = [FMDatabase sqliteLibVersion]; + XCTAssert([version compare:@"3.7" options:NSNumericSearch] == NSOrderedDescending, @"earlier than 3.7"); + XCTAssert([version compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending, @"not earlier than 4.0"); +} + +- (void)testIsThreadSafe +{ + BOOL isThreadSafe = [FMDatabase isSQLiteThreadSafe]; + XCTAssert(isThreadSafe, @"not threadsafe"); +} + +- (void)testOpenNilPath +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed"); + NSString *value = @"baz"; + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed"); + NSString *retrievedValue = [db stringForQuery:@"select bar from foo"]; + XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match"); +} + +- (void)testOpenZeroLengthPath +{ + FMDatabase *db = [[FMDatabase alloc] initWithPath:@""]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed"); + NSString *value = @"baz"; + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed"); + NSString *retrievedValue = [db stringForQuery:@"select bar from foo"]; + XCTAssert([value compare:retrievedValue] == NSOrderedSame, @"values didn't match"); +} + +- (void)testOpenTwice +{ + FMDatabase *db = [[FMDatabase alloc] init]; + [db open]; + XCTAssert([db open], @"Double open failed"); +} + +- (void)testInvalid +{ + NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *path = [documentsPath stringByAppendingPathComponent:@"nonexistentfolder/test.sqlite"]; + + FMDatabase *db = [[FMDatabase alloc] initWithPath:path]; + XCTAssertFalse([db open], @"open did NOT fail"); +} + +- (void)testChangingMaxBusyRetryTimeInterval +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + + NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval; + NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1; + + db.maxBusyRetryTimeInterval = updatedInterval; + NSTimeInterval diff = fabs(db.maxBusyRetryTimeInterval - updatedInterval); + + XCTAssert(diff < 1e-5, @"interval should have changed %.1f", diff); +} + +- (void)testChangingMaxBusyRetryTimeIntervalDatabaseNotOpened +{ + FMDatabase *db = [[FMDatabase alloc] init]; + // XCTAssert([db open], @"open failed"); // deliberately not opened + + NSTimeInterval originalInterval = db.maxBusyRetryTimeInterval; + NSTimeInterval updatedInterval = originalInterval > 0 ? originalInterval + 1 : 1; + + db.maxBusyRetryTimeInterval = updatedInterval; + XCTAssertNotEqual(originalInterval, db.maxBusyRetryTimeInterval, @"interval should not have changed"); +} + +- (void)testZeroMaxBusyRetryTimeInterval +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + + NSTimeInterval updatedInterval = 0; + + db.maxBusyRetryTimeInterval = updatedInterval; + XCTAssertEqual(db.maxBusyRetryTimeInterval, updatedInterval, @"busy handler not disabled"); +} + +- (void)testCloseOpenResultSets +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (bar text)"], @"create failed"); + NSString *value = @"baz"; + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[value]], @"insert failed"); + FMResultSet *rs = [db executeQuery:@"select bar from foo"]; + [db closeOpenResultSets]; + XCTAssertFalse([rs next], @"step should have failed"); +} + +- (void)testGoodConnection +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db goodConnection], @"no good connection"); +} + +- (void)testBadConnection +{ + FMDatabase *db = [[FMDatabase alloc] init]; + // XCTAssert([db open], @"open failed"); // deliberately did not open + XCTAssertFalse([db goodConnection], @"no good connection"); +} + +- (void)testLastRowId +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed"); + + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed"); + sqlite3_int64 firstRowId = [db lastInsertRowId]; + + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed"); + sqlite3_int64 secondRowId = [db lastInsertRowId]; + + XCTAssertEqual(secondRowId - firstRowId, 1, @"rowid should have incremented"); +} + +- (void)testChanges +{ + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (foo_id integer primary key autoincrement, bar text)"], @"create failed"); + + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"baz"]], @"insert failed"); + XCTAssert([db executeUpdate:@"insert into foo (bar) values (?)" withArgumentsInArray:@[@"qux"]], @"insert failed"); + XCTAssert([db executeUpdate:@"update foo set bar = ?" withArgumentsInArray:@[@"xxx"]], @"insert failed"); + int changes = [db changes]; + + XCTAssertEqual(changes, 2, @"two rows should have incremented \(%ld)", (long)changes); +} + +- (void)testBind { + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed"); + + NSNumber *insertedValue; + NSNumber *retrievedValue; + + insertedValue = [NSNumber numberWithChar:51]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithUnsignedChar:52]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithShort:53]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithUnsignedShort:54]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithInt:54]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithUnsignedInt:55]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithLong:56]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithUnsignedLong:57]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithLongLong:56]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithUnsignedLongLong:57]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithFloat:58]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = [NSNumber numberWithDouble:59]; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); + + insertedValue = @TRUE; + XCTAssert([db executeUpdate:@"insert into foo (a) values (?)" withArgumentsInArray:@[insertedValue]], @"insert failed"); + retrievedValue = @([db boolForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]); + XCTAssertEqualObjects(insertedValue, retrievedValue, @"values don't match"); +} + +- (void)testFormatStrings { + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (id integer primary key autoincrement, a numeric)"], @"create failed"); + + BOOL success; + + char insertedChar = 'A'; + success = [db executeUpdateWithFormat:@"insert into foo (a) values (%c)", insertedChar]; + XCTAssert(success, @"insert failed"); + const char *retrievedChar = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String]; + XCTAssertEqual(insertedChar, retrievedChar[0], @"values don't match"); + + const char *insertedString = "baz"; + success = [db executeUpdateWithFormat:@"insert into foo (a) values (%s)", insertedString]; + XCTAssert(success, @"insert failed"); + const char *retrievedString = [[db stringForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])] UTF8String]; + XCTAssert(strcmp(insertedString, retrievedString) == 0, @"values don't match"); + + int insertedInt = 42; + success = [db executeUpdateWithFormat:@"insert into foo (a) values (%d)", insertedInt]; + XCTAssert(success, @"insert failed"); + int retrievedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; + XCTAssertEqual(insertedInt, retrievedInt, @"values don't match"); + + char insertedUnsignedInt = 43; + success = [db executeUpdateWithFormat:@"insert into foo (a) values (%u)", insertedUnsignedInt]; + XCTAssert(success, @"insert failed"); + char retrievedUnsignedInt = [db intForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; + XCTAssertEqual(insertedUnsignedInt, retrievedUnsignedInt, @"values don't match"); + + float insertedFloat = 44; + success = [db executeUpdateWithFormat:@"insert into foo (a) values (%f)", insertedFloat]; + XCTAssert(success, @"insert failed"); + float retrievedFloat = [db doubleForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; + XCTAssertEqual(insertedFloat, retrievedFloat, @"values don't match"); + + unsigned long long insertedUnsignedLongLong = 45; + success = [db executeUpdateWithFormat:@"insert into foo (a) values (%llu)", insertedUnsignedLongLong]; + XCTAssert(success, @"insert failed"); + unsigned long long retrievedUnsignedLongLong = [db longForQuery:@"select a from foo where id = ?", @([db lastInsertRowId])]; + XCTAssertEqual(insertedUnsignedLongLong, retrievedUnsignedLongLong, @"values don't match"); +} + +- (void)testStepError { + FMDatabase *db = [[FMDatabase alloc] init]; + XCTAssert([db open], @"open failed"); + XCTAssert([db executeUpdate:@"create table foo (id integer primary key)"], @"create failed"); + XCTAssert([db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:nil], @"create failed"); + + NSError *error; + BOOL success = [db executeUpdate:@"insert into foo (id) values (?)" values:@[@1] error:&error]; + XCTAssertFalse(success, @"insert of duplicate key should have failed"); + XCTAssertNotNil(error, @"error object should have been generated"); + XCTAssertEqual(error.code, 19, @"error code 19 should have been generated"); +} + +@end diff --git a/Clocker/FMDB/Tests/FMResultSetTests.m b/Clocker/FMDB/Tests/FMResultSetTests.m new file mode 100755 index 0000000..3796828 --- /dev/null +++ b/Clocker/FMDB/Tests/FMResultSetTests.m @@ -0,0 +1,97 @@ +// +// FMResultSetTests.m +// fmdb +// +// Created by Muralidharan,Roshan on 10/6/14. +// +// + +#import "FMDBTempDBTests.h" +#import "FMDatabase.h" +#import "FMResultSet.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMResultSetTests : FMDBTempDBTests + +@end + +@implementation FMResultSetTests + ++ (void)populateDatabase:(FMDatabase *)db +{ + [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; + + [db beginTransaction]; + int i = 0; + while (i++ < 20) { + [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , + @"hi'", + [NSString stringWithFormat:@"number %d", i], + [NSNumber numberWithInt:i], + [NSDate date], + [NSNumber numberWithFloat:2.2f]]; + } + [db commit]; +} + +- (void)testNextWithError_WithoutError +{ + [self.db executeUpdate:@"CREATE TABLE testTable(key INTEGER PRIMARY KEY, value INTEGER)"]; + [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (1, 2)"]; + [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (2, 4)"]; + + FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable WHERE key=1"]; + XCTAssertNotNil(resultSet); + NSError *error; + XCTAssertTrue([resultSet nextWithError:&error]); + XCTAssertNil(error); + + XCTAssertFalse([resultSet nextWithError:&error]); + XCTAssertNil(error); + + [resultSet close]; +} + +- (void)testNextWithError_WithBusyError +{ + [self.db executeUpdate:@"CREATE TABLE testTable(key INTEGER PRIMARY KEY, value INTEGER)"]; + [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (1, 2)"]; + [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (2, 4)"]; + + FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable WHERE key=1"]; + XCTAssertNotNil(resultSet); + + FMDatabase *newDB = [FMDatabase databaseWithPath:self.databasePath]; + [newDB open]; + + [newDB beginTransaction]; + NSError *error; + XCTAssertFalse([resultSet nextWithError:&error]); + [newDB commit]; + + + XCTAssertEqual(error.code, SQLITE_BUSY, @"SQLITE_BUSY should be the last error"); + [resultSet close]; +} + +- (void)testNextWithError_WithMisuseError +{ + [self.db executeUpdate:@"CREATE TABLE testTable(key INTEGER PRIMARY KEY, value INTEGER)"]; + [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (1, 2)"]; + [self.db executeUpdate:@"INSERT INTO testTable (key, value) VALUES (2, 4)"]; + + FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM testTable WHERE key=9"]; + XCTAssertNotNil(resultSet); + XCTAssertFalse([resultSet next]); + NSError *error; + XCTAssertFalse([resultSet nextWithError:&error]); + + XCTAssertEqual(error.code, SQLITE_MISUSE, @"SQLITE_MISUSE should be the last error"); +} + +@end diff --git a/Clocker/FMDB/Tests/Schemes/Tests.xcscheme b/Clocker/FMDB/Tests/Schemes/Tests.xcscheme new file mode 100755 index 0000000..3ccd45a --- /dev/null +++ b/Clocker/FMDB/Tests/Schemes/Tests.xcscheme @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Clocker/FMDB/Tests/Tests-Info.plist b/Clocker/FMDB/Tests/Tests-Info.plist new file mode 100755 index 0000000..169b6f7 --- /dev/null +++ b/Clocker/FMDB/Tests/Tests-Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Clocker/FMDB/Tests/Tests-Prefix.pch b/Clocker/FMDB/Tests/Tests-Prefix.pch new file mode 100755 index 0000000..930e2c9 --- /dev/null +++ b/Clocker/FMDB/Tests/Tests-Prefix.pch @@ -0,0 +1,11 @@ +// +// Prefix header +// +// The contents of this file are implicitly included at the beginning of every source file. +// + +#ifdef __OBJC__ + #import + #import + #import "FMDBTempDBTests.h" +#endif diff --git a/Clocker/FMDB/Tests/en.lproj/InfoPlist.strings b/Clocker/FMDB/Tests/en.lproj/InfoPlist.strings new file mode 100755 index 0000000..477b28f --- /dev/null +++ b/Clocker/FMDB/Tests/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/Clocker/FMDB/fmdb.1 b/Clocker/FMDB/fmdb.1 new file mode 100755 index 0000000..361887e --- /dev/null +++ b/Clocker/FMDB/fmdb.1 @@ -0,0 +1,79 @@ +.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. +.\"See Also: +.\"man mdoc.samples for a complete listing of options +.\"man mdoc for the short list of editing options +.\"/usr/share/misc/mdoc.template +.Dd 5/11/06 \" DATE +.Dt fmdb 1 \" Program name and manual section number +.Os Darwin +.Sh NAME \" Section Header - required - don't modify +.Nm fmdb, +.\" The following lines are read in generating the apropos(man -k) database. Use only key +.\" words here as the database is built based on the words here and in the .ND line. +.Nm Other_name_for_same_program(), +.Nm Yet another name for the same program. +.\" Use .Nm macro to designate other names for the documented program. +.Nd This line parsed for whatis database. +.Sh SYNOPSIS \" Section Header - required - don't modify +.Nm +.Op Fl abcd \" [-abcd] +.Op Fl a Ar path \" [-a path] +.Op Ar file \" [file] +.Op Ar \" [file ...] +.Ar arg0 \" Underlined argument - use .Ar anywhere to underline +arg2 ... \" Arguments +.Sh DESCRIPTION \" Section Header - required - don't modify +Use the .Nm macro to refer to your program throughout the man page like such: +.Nm +Underlining is accomplished with the .Ar macro like this: +.Ar underlined text . +.Pp \" Inserts a space +A list of items with descriptions: +.Bl -tag -width -indent \" Begins a tagged list +.It item a \" Each item preceded by .It macro +Description of item a +.It item b +Description of item b +.El \" Ends the list +.Pp +A list of flags and their descriptions: +.Bl -tag -width -indent \" Differs from above in tag removed +.It Fl a \"-a flag as a list item +Description of -a flag +.It Fl b +Description of -b flag +.El \" Ends the list +.Pp +.\" .Sh ENVIRONMENT \" May not be needed +.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 +.\" .It Ev ENV_VAR_1 +.\" Description of ENV_VAR_1 +.\" .It Ev ENV_VAR_2 +.\" Description of ENV_VAR_2 +.\" .El +.Sh FILES \" File used or created by the topic of the man page +.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact +.It Pa /usr/share/file_name +FILE_1 description +.It Pa /Users/joeuser/Library/really_long_file_name +FILE_2 description +.El \" Ends the list +.\" .Sh DIAGNOSTICS \" May not be needed +.\" .Bl -diag +.\" .It Diagnostic Tag +.\" Diagnostic informtion here. +.\" .It Diagnostic Tag +.\" Diagnostic informtion here. +.\" .El +.Sh SEE ALSO +.\" List links in ascending order by section, alphabetically within a section. +.\" Please do not reference files that do not exist without filing a bug report +.Xr a 1 , +.Xr b 1 , +.Xr c 1 , +.Xr a 2 , +.Xr b 2 , +.Xr a 3 , +.Xr b 3 +.\" .Sh BUGS \" Document known, unremedied bugs +.\" .Sh HISTORY \" Document history if command behaves in a unique manner \ No newline at end of file diff --git a/Clocker/FMDB/fmdb.xcodeproj/project.pbxproj b/Clocker/FMDB/fmdb.xcodeproj/project.pbxproj new file mode 100755 index 0000000..ce7a46b --- /dev/null +++ b/Clocker/FMDB/fmdb.xcodeproj/project.pbxproj @@ -0,0 +1,1218 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 3354379C19E71096005661F3 /* FMResultSetTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 3354379B19E71096005661F3 /* FMResultSetTests.m */; }; + 40A145FE1BE5759400E5D35E /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A146001BE575D000E5D35E /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A146011BE575D600E5D35E /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A146021BE575DD00E5D35E /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A146031BE575E400E5D35E /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A146041BE575EB00E5D35E /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A146051BE6999800E5D35E /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 621721B21892BFE30006691F /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; + 621721B31892BFE30006691F /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; + 621721B41892BFE30006691F /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; + 621721B51892BFE30006691F /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + 621721B61892BFE30006691F /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; + 6290CBB7188FE836009790F8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6290CBB6188FE836009790F8 /* Foundation.framework */; }; + 67CB1E3019AD27D000A3CA7F /* FMDatabaseFTS3Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 67CB1E2F19AD27D000A3CA7F /* FMDatabaseFTS3Tests.m */; }; + 8314AF3318CD73D600EC0E25 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F131C326B9400FFC730 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; + 83C73F141C326B9400FFC730 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; + 83C73F151C326B9400FFC730 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; + 83C73F161C326B9400FFC730 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + 83C73F171C326B9400FFC730 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; + 83C73F181C326BAB00FFC730 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F191C326BAB00FFC730 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F1A1C326BAB00FFC730 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F1B1C326BAB00FFC730 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F1C1C326BAB00FFC730 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F1D1C326BAB00FFC730 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F1E1C326BC100FFC730 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; + 83C73F1F1C326BC100FFC730 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; + 83C73F201C326BC100FFC730 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; + 83C73F211C326BC100FFC730 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + 83C73F221C326BC100FFC730 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; + 83C73F231C326BD600FFC730 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 8314AF3218CD73D600EC0E25 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F241C326BD600FFC730 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F251C326BD600FFC730 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F261C326BD600FFC730 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F271C326BD600FFC730 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F281C326BD600FFC730 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83C73F2A1C326CE800FFC730 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F291C326CE800FFC730 /* libsqlite3.tbd */; }; + 83C73F2C1C326CF400FFC730 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */; }; + 83C73F2F1C326D2F00FFC730 /* FMDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83C73F0B1C326ADA00FFC730 /* FMDB.framework */; }; + 8DD76F9C0486AA7600D96B5E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 08FB779EFE84155DC02AAC07 /* Foundation.framework */; }; + 8DD76F9F0486AA7600D96B5E /* fmdb.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6859EA3029092ED04C91782 /* fmdb.1 */; }; + BF5D041918416BB2008C5AA9 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF5D041818416BB2008C5AA9 /* XCTest.framework */; }; + BF5D041F18416BB2008C5AA9 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */; }; + BF5D042118416BB2008C5AA9 /* FMDatabaseTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */; }; + BF940F5C18417D490001E077 /* FMDBTempDBTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BF940F5B18417D490001E077 /* FMDBTempDBTests.m */; }; + BF940F5E18417DEA0001E077 /* FMDatabaseAdditionsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */; }; + BFC152B118417F0D00605DF7 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + BFE55E131841C9A000CB3A63 /* FMDatabasePoolTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */; }; + BFE55E151841D38800CB3A63 /* FMDatabaseQueueTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */; }; + CC47A00F148581E9002CCDAB /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CC47A010148581E9002CCDAB /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; + CC47A011148581E9002CCDAB /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */; }; + CC50F2CD0DF9183600E4AAAE /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + CC7CE42818F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m in Sources */ = {isa = PBXBuildFile; fileRef = CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */; }; + CC9E4EB913B31188005F9210 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; + CC9E4EBA13B31188005F9210 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = CC9E4EB713B31188005F9210 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CC9E4EBB13B31188005F9210 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = CC9E4EB813B31188005F9210 /* FMDatabasePool.m */; }; + CCA66A2D19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */; }; + CCA66A2E19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */; }; + CCA66A2F19C0CB1900EFDAC1 /* FMTokenizers.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */; }; + CCA66A3019C0CB1900EFDAC1 /* FMTokenizers.m in Sources */ = {isa = PBXBuildFile; fileRef = CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */; }; + CCBE26C113B3BA8C006F6C37 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CCBE26C013B3BA8C006F6C37 /* AppKit.framework */; }; + CCBEBDAC0DF5DE1A003DDD08 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */; }; + CCC24EC20A13E34D00A6D3E3 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; + CCC24EC50A13E34D00A6D3E3 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBE0A13E34D00A6D3E3 /* main.m */; }; + CCC24EC70A13E34D00A6D3E3 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; + D4A740A21A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D4A740A11A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m */; }; + EE42910512B42FBC0088BD94 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */; }; + EE42910612B42FC30088BD94 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EE42910812B42FCC0088BD94 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */; }; + EE42910912B42FD00088BD94 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EE42910A12B42FD20088BD94 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 83C73F2D1C326D2000FFC730 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 83C73F0A1C326ADA00FFC730; + remoteInfo = "FMDB MacOS"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 6290CBB3188FE836009790F8 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DD76F9E0486AA7600D96B5E /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 8; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + 8DD76F9F0486AA7600D96B5E /* fmdb.1 in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 1; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 08FB779EFE84155DC02AAC07 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = ""; }; + 32A70AAB03705E1F00C91783 /* fmdb_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fmdb_Prefix.pch; path = src/sample/fmdb_Prefix.pch; sourceTree = SOURCE_ROOT; }; + 3354379B19E71096005661F3 /* FMResultSetTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSetTests.m; sourceTree = ""; }; + 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libFMDB-IOS.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6290CBB6188FE836009790F8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 6290CBC6188FE837009790F8 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 67CB1E2F19AD27D000A3CA7F /* FMDatabaseFTS3Tests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseFTS3Tests.m; sourceTree = ""; }; + 8314AF3218CD73D600EC0E25 /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDB.h; path = src/fmdb/FMDB.h; sourceTree = ""; }; + 831DE6FD175B7C9C001F7317 /* README.markdown */ = {isa = PBXFileReference; lastKnownFileType = text; path = README.markdown; sourceTree = ""; }; + 832F502419EC4C6B0087DCBF /* FMDatabaseVariadic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FMDatabaseVariadic.swift; path = "src/extra/Swift extensions/FMDatabaseVariadic.swift"; sourceTree = ""; }; + 8352D5AC1A73DCEA003A8E09 /* FMDatabaseAdditionsVariadic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FMDatabaseAdditionsVariadic.swift; path = "src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift"; sourceTree = ""; }; + 83C73EFE1C326AB000FFC730 /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 83C73F0B1C326ADA00FFC730 /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 83C73F291C326CE800FFC730 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; + 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; }; + 83C73F311C326FA600FFC730 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = src/fmdb/Info.plist; sourceTree = ""; }; + 8DD76FA10486AA7600D96B5E /* fmdb */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = fmdb; sourceTree = BUILT_PRODUCTS_DIR; }; + BF5D041618416BB2008C5AA9 /* Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Tests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + BF5D041818416BB2008C5AA9 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; + BF5D041C18416BB2008C5AA9 /* Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Tests-Info.plist"; sourceTree = ""; }; + BF5D041E18416BB2008C5AA9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseTests.m; sourceTree = ""; }; + BF5D042218416BB2008C5AA9 /* Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Tests-Prefix.pch"; sourceTree = ""; }; + BF940F5A18417D490001E077 /* FMDBTempDBTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDBTempDBTests.h; sourceTree = ""; }; + BF940F5B18417D490001E077 /* FMDBTempDBTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDBTempDBTests.m; sourceTree = ""; }; + BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditionsTests.m; sourceTree = ""; }; + BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePoolTests.m; sourceTree = ""; }; + BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueueTests.m; sourceTree = ""; }; + C6859EA3029092ED04C91782 /* fmdb.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = fmdb.1; sourceTree = ""; }; + CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabaseQueue.h; path = src/fmdb/FMDatabaseQueue.h; sourceTree = SOURCE_ROOT; }; + CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabaseQueue.m; path = src/fmdb/FMDatabaseQueue.m; sourceTree = SOURCE_ROOT; }; + CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabaseAdditions.m; path = src/fmdb/FMDatabaseAdditions.m; sourceTree = SOURCE_ROOT; }; + CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabaseAdditions.h; path = src/fmdb/FMDatabaseAdditions.h; sourceTree = SOURCE_ROOT; }; + CC7CE42618F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMDatabase+InMemoryOnDiskIO.h"; path = "src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h"; sourceTree = ""; }; + CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+InMemoryOnDiskIO.m"; path = "src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m"; sourceTree = ""; }; + CC8C138A0E3135C400FBE1E7 /* CHANGES_AND_TODO_LIST.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CHANGES_AND_TODO_LIST.txt; sourceTree = ""; }; + CC8C138B0E3135C400FBE1E7 /* LICENSE.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.txt; sourceTree = ""; }; + CC8C138C0E3135C400FBE1E7 /* CONTRIBUTORS.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CONTRIBUTORS.txt; sourceTree = ""; }; + CC9E4EB713B31188005F9210 /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabasePool.h; path = src/fmdb/FMDatabasePool.h; sourceTree = SOURCE_ROOT; }; + CC9E4EB813B31188005F9210 /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabasePool.m; path = src/fmdb/FMDatabasePool.m; sourceTree = SOURCE_ROOT; }; + CCA66A2819C0CB1900EFDAC1 /* FMDatabase+FTS3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FMDatabase+FTS3.h"; path = "src/extra/fts3/FMDatabase+FTS3.h"; sourceTree = ""; }; + CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FMDatabase+FTS3.m"; path = "src/extra/fts3/FMDatabase+FTS3.m"; sourceTree = ""; }; + CCA66A2A19C0CB1900EFDAC1 /* FMTokenizers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMTokenizers.h; path = src/extra/fts3/FMTokenizers.h; sourceTree = ""; }; + CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMTokenizers.m; path = src/extra/fts3/FMTokenizers.m; sourceTree = ""; }; + CCA66A2C19C0CB1900EFDAC1 /* fts3_tokenizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fts3_tokenizer.h; path = src/extra/fts3/fts3_tokenizer.h; sourceTree = ""; }; + CCBE26C013B3BA8C006F6C37 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = ""; }; + CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = /usr/lib/libsqlite3.dylib; sourceTree = ""; }; + CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMDatabase.h; path = src/fmdb/FMDatabase.h; sourceTree = SOURCE_ROOT; }; + CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMDatabase.m; path = src/fmdb/FMDatabase.m; sourceTree = SOURCE_ROOT; }; + CCC24EBE0A13E34D00A6D3E3 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = src/sample/main.m; sourceTree = SOURCE_ROOT; }; + CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FMResultSet.h; path = src/fmdb/FMResultSet.h; sourceTree = SOURCE_ROOT; }; + CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FMResultSet.m; path = src/fmdb/FMResultSet.m; sourceTree = SOURCE_ROOT; }; + D4A740A11A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseFTS3WithModuleNameTests.m; sourceTree = ""; }; + EE4290EF12B42F870088BD94 /* libFMDB.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libFMDB.a; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 6290CBB2188FE836009790F8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6290CBB7188FE836009790F8 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73EFA1C326AB000FFC730 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F2C1C326CF400FFC730 /* libsqlite3.tbd in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73F071C326ADA00FFC730 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F2A1C326CE800FFC730 /* libsqlite3.tbd in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DD76F9B0486AA7600D96B5E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8DD76F9C0486AA7600D96B5E /* Foundation.framework in Frameworks */, + CCBEBDAC0DF5DE1A003DDD08 /* libsqlite3.dylib in Frameworks */, + CCBE26C113B3BA8C006F6C37 /* AppKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BF5D041318416BB2008C5AA9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F2F1C326D2F00FFC730 /* FMDB.framework in Frameworks */, + BF5D041918416BB2008C5AA9 /* XCTest.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EE4290ED12B42F870088BD94 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 08FB7794FE84155DC02AAC07 /* fmdb */ = { + isa = PBXGroup; + children = ( + C6859EA2029092E104C91782 /* Documentation */, + 08FB7795FE84155DC02AAC07 /* Source */, + 08FB779DFE84155DC02AAC07 /* External Frameworks and Libraries */, + BF5D041A18416BB2008C5AA9 /* Tests */, + BF5D041718416BB2008C5AA9 /* Frameworks */, + 1AB674ADFE9D54B511CA2CBB /* Products */, + ); + name = fmdb; + sourceTree = ""; + }; + 08FB7795FE84155DC02AAC07 /* Source */ = { + isa = PBXGroup; + children = ( + 8314AF3018CD737D00EC0E25 /* fmdb */, + CC7CE42518F5C02E00938264 /* optional extras */, + 8314AF3118CD739500EC0E25 /* sample */, + ); + name = Source; + sourceTree = ""; + }; + 08FB779DFE84155DC02AAC07 /* External Frameworks and Libraries */ = { + isa = PBXGroup; + children = ( + CCBEBDAB0DF5DE1A003DDD08 /* libsqlite3.dylib */, + 08FB779EFE84155DC02AAC07 /* Foundation.framework */, + CCBE26C013B3BA8C006F6C37 /* AppKit.framework */, + ); + name = "External Frameworks and Libraries"; + sourceTree = ""; + }; + 1AB674ADFE9D54B511CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + 8DD76FA10486AA7600D96B5E /* fmdb */, + EE4290EF12B42F870088BD94 /* libFMDB.a */, + BF5D041618416BB2008C5AA9 /* Tests.xctest */, + 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */, + 83C73EFE1C326AB000FFC730 /* FMDB.framework */, + 83C73F0B1C326ADA00FFC730 /* FMDB.framework */, + ); + name = Products; + sourceTree = ""; + }; + 6767F81519AD13C300887DBC /* fts3 */ = { + isa = PBXGroup; + children = ( + CCA66A2819C0CB1900EFDAC1 /* FMDatabase+FTS3.h */, + CCA66A2919C0CB1900EFDAC1 /* FMDatabase+FTS3.m */, + CCA66A2A19C0CB1900EFDAC1 /* FMTokenizers.h */, + CCA66A2B19C0CB1900EFDAC1 /* FMTokenizers.m */, + CCA66A2C19C0CB1900EFDAC1 /* fts3_tokenizer.h */, + ); + name = fts3; + sourceTree = ""; + }; + 8314AF3018CD737D00EC0E25 /* fmdb */ = { + isa = PBXGroup; + children = ( + 8314AF3218CD73D600EC0E25 /* FMDB.h */, + CCC24EBA0A13E34D00A6D3E3 /* FMDatabase.h */, + CCC24EBB0A13E34D00A6D3E3 /* FMDatabase.m */, + CCC24EBF0A13E34D00A6D3E3 /* FMResultSet.h */, + CCC24EC00A13E34D00A6D3E3 /* FMResultSet.m */, + CC47A00D148581E9002CCDAB /* FMDatabaseQueue.h */, + CC47A00E148581E9002CCDAB /* FMDatabaseQueue.m */, + CC50F2CC0DF9183600E4AAAE /* FMDatabaseAdditions.h */, + CC50F2CB0DF9183600E4AAAE /* FMDatabaseAdditions.m */, + CC9E4EB713B31188005F9210 /* FMDatabasePool.h */, + CC9E4EB813B31188005F9210 /* FMDatabasePool.m */, + 83C73F311C326FA600FFC730 /* Info.plist */, + ); + name = fmdb; + sourceTree = ""; + }; + 8314AF3118CD739500EC0E25 /* sample */ = { + isa = PBXGroup; + children = ( + CCC24EBE0A13E34D00A6D3E3 /* main.m */, + 32A70AAB03705E1F00C91783 /* fmdb_Prefix.pch */, + ); + name = sample; + sourceTree = ""; + }; + 832F502319EC4C4A0087DCBF /* Swift extensions */ = { + isa = PBXGroup; + children = ( + 832F502419EC4C6B0087DCBF /* FMDatabaseVariadic.swift */, + 8352D5AC1A73DCEA003A8E09 /* FMDatabaseAdditionsVariadic.swift */, + ); + name = "Swift extensions"; + sourceTree = ""; + }; + 832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */ = { + isa = PBXGroup; + children = ( + CC7CE42618F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.h */, + CC7CE42718F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m */, + ); + name = InMemoryOnDiskIO; + sourceTree = ""; + }; + BF5D041718416BB2008C5AA9 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 83C73F2B1C326CF400FFC730 /* libsqlite3.tbd */, + 83C73F291C326CE800FFC730 /* libsqlite3.tbd */, + BF5D041818416BB2008C5AA9 /* XCTest.framework */, + 6290CBB6188FE836009790F8 /* Foundation.framework */, + 6290CBC6188FE837009790F8 /* UIKit.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + BF5D041A18416BB2008C5AA9 /* Tests */ = { + isa = PBXGroup; + children = ( + BF940F5D18417DEA0001E077 /* FMDatabaseAdditionsTests.m */, + 67CB1E2F19AD27D000A3CA7F /* FMDatabaseFTS3Tests.m */, + D4A740A11A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m */, + BFE55E121841C9A000CB3A63 /* FMDatabasePoolTests.m */, + BFE55E141841D38800CB3A63 /* FMDatabaseQueueTests.m */, + BF5D042018416BB2008C5AA9 /* FMDatabaseTests.m */, + BF940F5A18417D490001E077 /* FMDBTempDBTests.h */, + BF940F5B18417D490001E077 /* FMDBTempDBTests.m */, + 3354379B19E71096005661F3 /* FMResultSetTests.m */, + BF5D041B18416BB2008C5AA9 /* Supporting Files */, + ); + path = Tests; + sourceTree = ""; + }; + BF5D041B18416BB2008C5AA9 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + BF5D041C18416BB2008C5AA9 /* Tests-Info.plist */, + BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */, + BF5D042218416BB2008C5AA9 /* Tests-Prefix.pch */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + C6859EA2029092E104C91782 /* Documentation */ = { + isa = PBXGroup; + children = ( + 831DE6FD175B7C9C001F7317 /* README.markdown */, + CC8C138B0E3135C400FBE1E7 /* LICENSE.txt */, + CC8C138A0E3135C400FBE1E7 /* CHANGES_AND_TODO_LIST.txt */, + CC8C138C0E3135C400FBE1E7 /* CONTRIBUTORS.txt */, + C6859EA3029092ED04C91782 /* fmdb.1 */, + ); + name = Documentation; + sourceTree = ""; + }; + CC7CE42518F5C02E00938264 /* optional extras */ = { + isa = PBXGroup; + children = ( + 832F502319EC4C4A0087DCBF /* Swift extensions */, + 832F502519EC4CA20087DCBF /* InMemoryOnDiskIO */, + 6767F81519AD13C300887DBC /* fts3 */, + ); + name = "optional extras"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 40A145FF1BE575BD00E5D35E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 40A146001BE575D000E5D35E /* FMDatabase.h in Headers */, + 40A146011BE575D600E5D35E /* FMResultSet.h in Headers */, + 40A146041BE575EB00E5D35E /* FMDatabasePool.h in Headers */, + 40A146051BE6999800E5D35E /* FMDB.h in Headers */, + 40A146031BE575E400E5D35E /* FMDatabaseAdditions.h in Headers */, + 40A146021BE575DD00E5D35E /* FMDatabaseQueue.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73EFB1C326AB000FFC730 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F181C326BAB00FFC730 /* FMDB.h in Headers */, + 83C73F191C326BAB00FFC730 /* FMDatabase.h in Headers */, + 83C73F1A1C326BAB00FFC730 /* FMResultSet.h in Headers */, + 83C73F1B1C326BAB00FFC730 /* FMDatabaseQueue.h in Headers */, + 83C73F1C1C326BAB00FFC730 /* FMDatabaseAdditions.h in Headers */, + 83C73F1D1C326BAB00FFC730 /* FMDatabasePool.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73F081C326ADA00FFC730 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F231C326BD600FFC730 /* FMDB.h in Headers */, + 83C73F241C326BD600FFC730 /* FMDatabase.h in Headers */, + 83C73F251C326BD600FFC730 /* FMResultSet.h in Headers */, + 83C73F261C326BD600FFC730 /* FMDatabaseQueue.h in Headers */, + 83C73F271C326BD600FFC730 /* FMDatabaseAdditions.h in Headers */, + 83C73F281C326BD600FFC730 /* FMDatabasePool.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EE4290EB12B42F870088BD94 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + EE42910612B42FC30088BD94 /* FMDatabaseAdditions.h in Headers */, + EE42910912B42FD00088BD94 /* FMResultSet.h in Headers */, + 40A145FE1BE5759400E5D35E /* FMDatabase.h in Headers */, + 8314AF3318CD73D600EC0E25 /* FMDB.h in Headers */, + CC9E4EBA13B31188005F9210 /* FMDatabasePool.h in Headers */, + CC47A00F148581E9002CCDAB /* FMDatabaseQueue.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 6290CBB4188FE836009790F8 /* FMDB-IOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6290CBD7188FE837009790F8 /* Build configuration list for PBXNativeTarget "FMDB-IOS" */; + buildPhases = ( + 6290CBB1188FE836009790F8 /* Sources */, + 6290CBB2188FE836009790F8 /* Frameworks */, + 6290CBB3188FE836009790F8 /* CopyFiles */, + 40A145FF1BE575BD00E5D35E /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "FMDB-IOS"; + productName = "FMDB-IOS"; + productReference = 6290CBB5188FE836009790F8 /* libFMDB-IOS.a */; + productType = "com.apple.product-type.library.static"; + }; + 83C73EFD1C326AB000FFC730 /* FMDB iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 83C73F051C326AB000FFC730 /* Build configuration list for PBXNativeTarget "FMDB iOS" */; + buildPhases = ( + 83C73EF91C326AB000FFC730 /* Sources */, + 83C73EFA1C326AB000FFC730 /* Frameworks */, + 83C73EFB1C326AB000FFC730 /* Headers */, + 83C73EFC1C326AB000FFC730 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "FMDB iOS"; + productName = "FMDB iOS"; + productReference = 83C73EFE1C326AB000FFC730 /* FMDB.framework */; + productType = "com.apple.product-type.framework"; + }; + 83C73F0A1C326ADA00FFC730 /* FMDB MacOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 83C73F101C326ADB00FFC730 /* Build configuration list for PBXNativeTarget "FMDB MacOS" */; + buildPhases = ( + 83C73F061C326ADA00FFC730 /* Sources */, + 83C73F071C326ADA00FFC730 /* Frameworks */, + 83C73F081C326ADA00FFC730 /* Headers */, + 83C73F091C326ADA00FFC730 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "FMDB MacOS"; + productName = "FMDB MacOS"; + productReference = 83C73F0B1C326ADA00FFC730 /* FMDB.framework */; + productType = "com.apple.product-type.framework"; + }; + 8DD76F960486AA7600D96B5E /* fmdb */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "fmdb" */; + buildPhases = ( + 8DD76F990486AA7600D96B5E /* Sources */, + 8DD76F9B0486AA7600D96B5E /* Frameworks */, + 8DD76F9E0486AA7600D96B5E /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = fmdb; + productInstallPath = "$(HOME)/bin"; + productName = fmdb; + productReference = 8DD76FA10486AA7600D96B5E /* fmdb */; + productType = "com.apple.product-type.tool"; + }; + BF5D041518416BB2008C5AA9 /* Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = BF5D042718416BB2008C5AA9 /* Build configuration list for PBXNativeTarget "Tests" */; + buildPhases = ( + BF5D041218416BB2008C5AA9 /* Sources */, + BF5D041318416BB2008C5AA9 /* Frameworks */, + BF5D041418416BB2008C5AA9 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 83C73F2E1C326D2000FFC730 /* PBXTargetDependency */, + ); + name = Tests; + productName = Tests; + productReference = BF5D041618416BB2008C5AA9 /* Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + EE4290EE12B42F870088BD94 /* FMDB */ = { + isa = PBXNativeTarget; + buildConfigurationList = EE42910012B42FA00088BD94 /* Build configuration list for PBXNativeTarget "FMDB" */; + buildPhases = ( + EE4290EB12B42F870088BD94 /* Headers */, + EE4290EC12B42F870088BD94 /* Sources */, + EE4290ED12B42F870088BD94 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = FMDB; + productName = FMDB; + productReference = EE4290EF12B42F870088BD94 /* libFMDB.a */; + productType = "com.apple.product-type.library.static"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 08FB7793FE84155DC02AAC07 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0710; + TargetAttributes = { + 83C73EFD1C326AB000FFC730 = { + CreatedOnToolsVersion = 7.2; + }; + 83C73F0A1C326ADA00FFC730 = { + CreatedOnToolsVersion = 7.2; + }; + BF5D041518416BB2008C5AA9 = { + TestTargetID = EE4290EE12B42F870088BD94; + }; + }; + }; + buildConfigurationList = 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "fmdb" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + en, + ); + mainGroup = 08FB7794FE84155DC02AAC07 /* fmdb */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 8DD76F960486AA7600D96B5E /* fmdb */, + EE4290EE12B42F870088BD94 /* FMDB */, + BF5D041518416BB2008C5AA9 /* Tests */, + 6290CBB4188FE836009790F8 /* FMDB-IOS */, + 83C73EFD1C326AB000FFC730 /* FMDB iOS */, + 83C73F0A1C326ADA00FFC730 /* FMDB MacOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 83C73EFC1C326AB000FFC730 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73F091C326ADA00FFC730 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BF5D041418416BB2008C5AA9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BF5D041F18416BB2008C5AA9 /* InfoPlist.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 6290CBB1188FE836009790F8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 621721B31892BFE30006691F /* FMResultSet.m in Sources */, + 621721B21892BFE30006691F /* FMDatabase.m in Sources */, + 621721B61892BFE30006691F /* FMDatabasePool.m in Sources */, + 621721B41892BFE30006691F /* FMDatabaseQueue.m in Sources */, + 621721B51892BFE30006691F /* FMDatabaseAdditions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73EF91C326AB000FFC730 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F131C326B9400FFC730 /* FMDatabase.m in Sources */, + 83C73F141C326B9400FFC730 /* FMResultSet.m in Sources */, + 83C73F151C326B9400FFC730 /* FMDatabaseQueue.m in Sources */, + 83C73F161C326B9400FFC730 /* FMDatabaseAdditions.m in Sources */, + 83C73F171C326B9400FFC730 /* FMDatabasePool.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83C73F061C326ADA00FFC730 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 83C73F1E1C326BC100FFC730 /* FMDatabase.m in Sources */, + 83C73F1F1C326BC100FFC730 /* FMResultSet.m in Sources */, + 83C73F201C326BC100FFC730 /* FMDatabaseQueue.m in Sources */, + 83C73F211C326BC100FFC730 /* FMDatabaseAdditions.m in Sources */, + 83C73F221C326BC100FFC730 /* FMDatabasePool.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DD76F990486AA7600D96B5E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + CCC24EC20A13E34D00A6D3E3 /* FMDatabase.m in Sources */, + CCA66A2F19C0CB1900EFDAC1 /* FMTokenizers.m in Sources */, + CCC24EC50A13E34D00A6D3E3 /* main.m in Sources */, + CCC24EC70A13E34D00A6D3E3 /* FMResultSet.m in Sources */, + CC7CE42818F5C04600938264 /* FMDatabase+InMemoryOnDiskIO.m in Sources */, + CC50F2CD0DF9183600E4AAAE /* FMDatabaseAdditions.m in Sources */, + CC9E4EB913B31188005F9210 /* FMDatabasePool.m in Sources */, + CC47A010148581E9002CCDAB /* FMDatabaseQueue.m in Sources */, + CCA66A2D19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BF5D041218416BB2008C5AA9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BFC152B118417F0D00605DF7 /* FMDatabaseAdditions.m in Sources */, + CCA66A3019C0CB1900EFDAC1 /* FMTokenizers.m in Sources */, + BF940F5C18417D490001E077 /* FMDBTempDBTests.m in Sources */, + BF940F5E18417DEA0001E077 /* FMDatabaseAdditionsTests.m in Sources */, + 3354379C19E71096005661F3 /* FMResultSetTests.m in Sources */, + BF5D042118416BB2008C5AA9 /* FMDatabaseTests.m in Sources */, + 67CB1E3019AD27D000A3CA7F /* FMDatabaseFTS3Tests.m in Sources */, + BFE55E131841C9A000CB3A63 /* FMDatabasePoolTests.m in Sources */, + BFE55E151841D38800CB3A63 /* FMDatabaseQueueTests.m in Sources */, + D4A740A21A7046330058EBEE /* FMDatabaseFTS3WithModuleNameTests.m in Sources */, + CCA66A2E19C0CB1900EFDAC1 /* FMDatabase+FTS3.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EE4290EC12B42F870088BD94 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + EE42910812B42FCC0088BD94 /* FMDatabase.m in Sources */, + EE42910512B42FBC0088BD94 /* FMDatabaseAdditions.m in Sources */, + EE42910A12B42FD20088BD94 /* FMResultSet.m in Sources */, + CC9E4EBB13B31188005F9210 /* FMDatabasePool.m in Sources */, + CC47A011148581E9002CCDAB /* FMDatabaseQueue.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 83C73F2E1C326D2000FFC730 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 83C73F0A1C326ADA00FFC730 /* FMDB MacOS */; + targetProxy = 83C73F2D1C326D2000FFC730 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + BF5D041D18416BB2008C5AA9 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + BF5D041E18416BB2008C5AA9 /* en */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 1DEB927508733DD40010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = src/sample/fmdb_Prefix.pch; + GCC_WARN_SHADOW = YES; + INSTALL_PATH = "$(HOME)/bin"; + LIBRARY_SEARCH_PATHS = "$(LIBRARY_SEARCH_PATHS)"; + PRODUCT_NAME = fmdb; + }; + name = Debug; + }; + 1DEB927608733DD40010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_MODEL_TUNING = G5; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = src/sample/fmdb_Prefix.pch; + GCC_WARN_SHADOW = YES; + INSTALL_PATH = "$(HOME)/bin"; + LIBRARY_SEARCH_PATHS = "$(LIBRARY_SEARCH_PATHS)"; + PRODUCT_NAME = fmdb; + }; + name = Release; + }; + 1DEB927908733DD40010E9CD /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_MISSING_PARENTHESES = YES; + GCC_WARN_PEDANTIC = YES; + GCC_WARN_SIGN_COMPARE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + }; + name = Debug; + }; + 1DEB927A08733DD40010E9CD /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_VERSION = com.apple.compilers.llvm.clang.1_0; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + SDKROOT = macosx; + }; + name = Release; + }; + 6290CBD3188FE837009790F8 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + COPY_PHASE_STRIP = NO; + DSTROOT = /tmp/FMDB_IOS.dst; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + }; + name = Debug; + }; + 6290CBD4188FE837009790F8 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + COPY_PHASE_STRIP = YES; + DSTROOT = /tmp/FMDB_IOS.dst; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 83C73F031C326AB000FFC730 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + INFOPLIST_FILE = src/fmdb/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-iOS"; + PRODUCT_NAME = FMDB; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 83C73F041C326AB000FFC730 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + INFOPLIST_FILE = src/fmdb/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-iOS"; + PRODUCT_NAME = FMDB; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 83C73F111C326ADB00FFC730 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CODE_SIGN_IDENTITY = "-"; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + INFOPLIST_FILE = src/fmdb/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-MacOS"; + PRODUCT_NAME = FMDB; + SKIP_INSTALL = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 83C73F121C326ADB00FFC730 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CODE_SIGN_IDENTITY = "-"; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_NS_ASSERTIONS = NO; + FRAMEWORK_VERSION = A; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + INFOPLIST_FILE = src/fmdb/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "com.flyingmeat.FMDB-MacOS"; + PRODUCT_NAME = FMDB; + SKIP_INSTALL = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + BF5D042518416BB2008C5AA9 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(DEVELOPER_FRAMEWORKS_DIR)", + "$(inherited)", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_PEDANTIC = NO; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + INFOPLIST_FILE = "Tests/Tests-Info.plist"; + MACOSX_DEPLOYMENT_TARGET = 10.8; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = "-lsqlite3"; + PRODUCT_BUNDLE_IDENTIFIER = "me.grahamdennis.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + WRAPPER_EXTENSION = xctest; + }; + name = Debug; + }; + BF5D042618416BB2008C5AA9 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(DEVELOPER_FRAMEWORKS_DIR)", + "$(inherited)", + ); + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch"; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + INFOPLIST_FILE = "Tests/Tests-Info.plist"; + MACOSX_DEPLOYMENT_TARGET = 10.8; + OTHER_LDFLAGS = "-lsqlite3"; + PRODUCT_BUNDLE_IDENTIFIER = "me.grahamdennis.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + WRAPPER_EXTENSION = xctest; + }; + name = Release; + }; + EE4290F012B42F880088BD94 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + PRODUCT_NAME = FMDB; + PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; + }; + name = Debug; + }; + EE4290F112B42F880088BD94 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + PRODUCT_NAME = FMDB; + PUBLIC_HEADERS_FOLDER_PATH = include/FMDB; + ZERO_LINK = NO; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1DEB927408733DD40010E9CD /* Build configuration list for PBXNativeTarget "fmdb" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB927508733DD40010E9CD /* Debug */, + 1DEB927608733DD40010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1DEB927808733DD40010E9CD /* Build configuration list for PBXProject "fmdb" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1DEB927908733DD40010E9CD /* Debug */, + 1DEB927A08733DD40010E9CD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6290CBD7188FE837009790F8 /* Build configuration list for PBXNativeTarget "FMDB-IOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6290CBD3188FE837009790F8 /* Debug */, + 6290CBD4188FE837009790F8 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 83C73F051C326AB000FFC730 /* Build configuration list for PBXNativeTarget "FMDB iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 83C73F031C326AB000FFC730 /* Debug */, + 83C73F041C326AB000FFC730 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 83C73F101C326ADB00FFC730 /* Build configuration list for PBXNativeTarget "FMDB MacOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 83C73F111C326ADB00FFC730 /* Debug */, + 83C73F121C326ADB00FFC730 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BF5D042718416BB2008C5AA9 /* Build configuration list for PBXNativeTarget "Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BF5D042518416BB2008C5AA9 /* Debug */, + BF5D042618416BB2008C5AA9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + EE42910012B42FA00088BD94 /* Build configuration list for PBXNativeTarget "FMDB" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EE4290F012B42F880088BD94 /* Debug */, + EE4290F112B42F880088BD94 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 08FB7793FE84155DC02AAC07 /* Project object */; +} diff --git a/Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB MacOS.xcscheme b/Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB MacOS.xcscheme new file mode 100755 index 0000000..a26c49d --- /dev/null +++ b/Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB MacOS.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB iOS.xcscheme b/Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB iOS.xcscheme new file mode 100755 index 0000000..48e8ec1 --- /dev/null +++ b/Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB iOS.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h b/Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h new file mode 100755 index 0000000..84a87c0 --- /dev/null +++ b/Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h @@ -0,0 +1,26 @@ +// +// FMDatabase+InMemoryOnDiskIO.h +// FMDB +// +// Created by Peter Carr on 6/12/12. +// +// I find there is a massive performance hit using an "on-disk" representation when +// constantly reading from or writing to the DB. If your machine has sufficient memory, you +// should get a significant performance boost using an "in-memory" representation. The FMDB +// warpper does not contain methods to load an "on-disk" representation into memory and +// similarly save an "in-memory" representation to disk. However, SQLite3 has built-in +// support for this functionality via its "Backup" API. Here, we extend the FMBD wrapper +// to include this functionality. +// +// http://www.sqlite.org/backup.html + +#import "FMDatabase.h" + +@interface FMDatabase (InMemoryOnDiskIO) + +// Loads an on-disk representation into memory. +- (BOOL)readFromFile:(NSString*)filePath; + +// Saves an in-memory representation to disk +- (BOOL)writeToFile:(NSString *)filePath; +@end diff --git a/Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m b/Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m new file mode 100755 index 0000000..5f91089 --- /dev/null +++ b/Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m @@ -0,0 +1,98 @@ +#import "FMDatabase+InMemoryOnDiskIO.h" +#import + + +// http://www.sqlite.org/backup.html +static +int loadOrSaveDb(sqlite3 *pInMemory, const char *zFilename, int isSave) +{ + int rc; /* Function return code */ + sqlite3 *pFile; /* Database connection opened on zFilename */ + sqlite3_backup *pBackup; /* Backup object used to copy data */ + sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */ + sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */ + + /* Open the database file identified by zFilename. Exit early if this fails + ** for any reason. */ + rc = sqlite3_open(zFilename, &pFile); + if( rc==SQLITE_OK ){ + + /* If this is a 'load' operation (isSave==0), then data is copied + ** from the database file just opened to database pInMemory. + ** Otherwise, if this is a 'save' operation (isSave==1), then data + ** is copied from pInMemory to pFile. Set the variables pFrom and + ** pTo accordingly. */ + pFrom = (isSave ? pInMemory : pFile); + pTo = (isSave ? pFile : pInMemory); + + /* Set up the backup procedure to copy from the "main" database of + ** connection pFile to the main database of connection pInMemory. + ** If something goes wrong, pBackup will be set to NULL and an error + ** code and message left in connection pTo. + ** + ** If the backup object is successfully created, call backup_step() + ** to copy data from pFile to pInMemory. Then call backup_finish() + ** to release resources associated with the pBackup object. If an + ** error occurred, then an error code and message will be left in + ** connection pTo. If no error occurred, then the error code belonging + ** to pTo is set to SQLITE_OK. + */ + pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main"); + if( pBackup ){ + (void)sqlite3_backup_step(pBackup, -1); + (void)sqlite3_backup_finish(pBackup); + } + rc = sqlite3_errcode(pTo); + } + + /* Close the database connection opened on database file zFilename + ** and return the result of this function. */ + (void)sqlite3_close(pFile); + return rc; +} + + + +@implementation FMDatabase (InMemoryOnDiskIO) + +- (BOOL)readFromFile:(NSString*)filePath +{ + // only attempt to load an on-disk representation for an in-memory database + if ( self->_databasePath != nil ) + { + NSLog(@"Database is not an in-memory representation." ); + return NO; + } + + // and only if the database is open + if ( self->_db == nil ) + { + NSLog(@"Invalid database connection." ); + return NO; + } + + return ( SQLITE_OK == loadOrSaveDb( self->_db, [filePath fileSystemRepresentation], false ) ); + +} + +- (BOOL)writeToFile:(NSString *)filePath +{ + // only attempt to save an on-disk representation for an in-memory database + if ( self->_databasePath != nil ) + { + NSLog(@"Database is not an in-memory representation." ); + return NO; + } + + // and only if the database is open + if ( self->_db == nil ) + { + NSLog(@"Invalid database connection." ); + return NO; + } + + // save the in-memory representation + return ( SQLITE_OK == loadOrSaveDb( self->_db, [filePath fileSystemRepresentation], true ) ); +} + +@end diff --git a/Clocker/FMDB/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift b/Clocker/FMDB/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift new file mode 100755 index 0000000..82bc1c2 --- /dev/null +++ b/Clocker/FMDB/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift @@ -0,0 +1,117 @@ +// +// FMDatabaseAdditionsVariadic.swift +// FMDB +// + +import Foundation + +extension FMDatabase { + + /// Private generic function used for the variadic renditions of the FMDatabaseAdditions methods + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The NSArray of the arguments to be bound to the ? placeholders in the SQL. + /// - parameter completionHandler: The closure to be used to call the appropriate FMDatabase method to return the desired value. + /// + /// - returns: This returns the T value if value is found. Returns nil if column is NULL or upon error. + + private func valueForQuery(sql: String, values: [AnyObject]?, completionHandler:(FMResultSet)->(T!)) -> T! { + var result: T! + + if let rs = executeQuery(sql, withArgumentsInArray: values) { + if rs.next() { + let obj: AnyObject! = rs.objectForColumnIndex(0) + if !(obj is NSNull) { + result = completionHandler(rs) + } + } + rs.close() + } + + return result + } + + /// This is a rendition of stringForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns string value if value is found. Returns nil if column is NULL or upon error. + + func stringForQuery(sql: String, _ values: AnyObject...) -> String! { + return valueForQuery(sql, values: values) { $0.stringForColumnIndex(0) } + } + + /// This is a rendition of intForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns integer value if value is found. Returns nil if column is NULL or upon error. + + func intForQuery(sql: String, _ values: AnyObject...) -> Int32! { + return valueForQuery(sql, values: values) { $0.intForColumnIndex(0) } + } + + /// This is a rendition of longForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns long value if value is found. Returns nil if column is NULL or upon error. + + func longForQuery(sql: String, _ values: AnyObject...) -> Int! { + return valueForQuery(sql, values: values) { $0.longForColumnIndex(0) } + } + + /// This is a rendition of boolForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns Bool value if value is found. Returns nil if column is NULL or upon error. + + func boolForQuery(sql: String, _ values: AnyObject...) -> Bool! { + return valueForQuery(sql, values: values) { $0.boolForColumnIndex(0) } + } + + /// This is a rendition of doubleForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns Double value if value is found. Returns nil if column is NULL or upon error. + + func doubleForQuery(sql: String, _ values: AnyObject...) -> Double! { + return valueForQuery(sql, values: values) { $0.doubleForColumnIndex(0) } + } + + /// This is a rendition of dateForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns NSDate value if value is found. Returns nil if column is NULL or upon error. + + func dateForQuery(sql: String, _ values: AnyObject...) -> NSDate! { + return valueForQuery(sql, values: values) { $0.dateForColumnIndex(0) } + } + + /// This is a rendition of dataForQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns NSData value if value is found. Returns nil if column is NULL or upon error. + + func dataForQuery(sql: String, _ values: AnyObject...) -> NSData! { + return valueForQuery(sql, values: values) { $0.dataForColumnIndex(0) } + } +} \ No newline at end of file diff --git a/Clocker/FMDB/src/extra/Swift extensions/FMDatabaseVariadic.swift b/Clocker/FMDB/src/extra/Swift extensions/FMDatabaseVariadic.swift new file mode 100755 index 0000000..edcf055 --- /dev/null +++ b/Clocker/FMDB/src/extra/Swift extensions/FMDatabaseVariadic.swift @@ -0,0 +1,38 @@ +// +// FMDatabaseVariadic.swift +// FMDB +// + + +// This extension inspired by http://stackoverflow.com/a/24187932/1271826 + +import Foundation + +extension FMDatabase { + + /// This is a rendition of executeQuery that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// This throws any error that occurs. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + /// + /// - returns: This returns FMResultSet if successful. If unsuccessful, it throws an error. + + func executeQuery(sql:String, _ values: AnyObject...) throws -> FMResultSet { + return try executeQuery(sql, values: values as [AnyObject]); + } + + /// This is a rendition of executeUpdate that handles Swift variadic parameters + /// for the values to be bound to the ? placeholders in the SQL. + /// + /// This throws any error that occurs. + /// + /// - parameter sql: The SQL statement to be used. + /// - parameter values: The values to be bound to the ? placeholders + + func executeUpdate(sql:String, _ values: AnyObject...) throws { + try executeUpdate(sql, values: values as [AnyObject]); + } +} diff --git a/Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.h b/Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.h new file mode 100755 index 0000000..1b51a1e --- /dev/null +++ b/Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.h @@ -0,0 +1,114 @@ +// +// FMDatabase+FTS3.h +// fmdb +// +// Created by Andrew on 3/27/14. +// Copyright (c) 2014 Andrew Goodale. All rights reserved. +// + +#import + +/** + Names of commands that can be issued against an FTS table. + */ +extern NSString *const kFTSCommandOptimize; // "optimize" +extern NSString *const kFTSCommandRebuild; // "rebuild" +extern NSString *const kFTSCommandIntegrityCheck; // "integrity-check" +extern NSString *const kFTSCommandMerge; // "merge=%u,%u" +extern NSString *const kFTSCommandAutoMerge; // "automerge=%u" + +@protocol FMTokenizerDelegate; + +/** + This category provides methods to access the FTS3 extensions in SQLite. + */ +@interface FMDatabase (FTS3) + +/** + Register a delegate implementation in the global table. This should be used when using a single tokenizer. + */ ++ (void)registerTokenizer:(id)tokenizer; + +/** + Register a delegate implementation in the global table. The key should be used + as a parameter when creating the table. + */ ++ (void)registerTokenizer:(id)tokenizer withKey:(NSString *)key; + +/** + Calls the `fts3_tokenizer()` function on this database, installing tokenizer module with the 'fmdb' name. + */ +- (BOOL)installTokenizerModule; + +/** + Calls the `fts3_tokenizer()` function on this database, installing the tokenizer module with specified name. + */ +- (BOOL)installTokenizerModuleWithName:(NSString *)name; + +/** + Runs a "special command" for FTS3/FTS4 tables. + */ +- (BOOL)issueCommand:(NSString *)command forTable:(NSString *)tableName; + +@end + +#pragma mark + +/* Extend this structure with your own custom cursor data */ +typedef struct FMTokenizerCursor +{ + void *tokenizer; /* Internal SQLite reference */ + CFStringRef inputString; /* The input text being tokenized */ + CFRange currentRange; /* The current range within `inputString` */ + CFStringRef tokenString; /* The contents of the current token */ + CFTypeRef userObject; /* Additional state for the cursor */ + int tokenIndex; /* Index of next token to be returned */ + UInt8 outputBuf[128]; /* Result for SQLite */ + CFRange previousRange; /* Cached range of previous token within `inputString` */ + CFRange previousOffsetRange; /* Cached range of previous token as UTF-8 offset */ +} FMTokenizerCursor; + +@protocol FMTokenizerDelegate + +- (void)openTokenizerCursor:(FMTokenizerCursor *)cursor; + +- (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor; + +- (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor; + +@end + +#pragma mark + +/** + The container of offset information. + */ +@interface FMTextOffsets : NSObject + +- (instancetype)initWithDBOffsets:(const char *)offsets; + +/** + Enumerate each set of offsets in the result. The column number can be turned into a column name + using `[FMResultSet columnNameForIndex:]`. The `matchRange` is in UTF-8 byte positions, so it must be + modified to use with `NSString` data. + */ +- (void)enumerateWithBlock:(void (^)(NSInteger columnNumber, NSInteger termNumber, NSRange matchRange))block; + +@end + +/** + A category that adds support for the encoded data returned by FTS3 functions. + */ +@interface FMResultSet (FTS3) + +/** + Returns a structure containing values from the `offsets()` function. Make sure the column index corresponds + to the column index in the SQL query. + + @param columnIdx Zero-based index for column. + + @return `FMTextOffsets` structure. + */ +- (FMTextOffsets *)offsetsForColumnIndex:(int)columnIdx; + +@end diff --git a/Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.m b/Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.m new file mode 100755 index 0000000..3903e09 --- /dev/null +++ b/Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.m @@ -0,0 +1,300 @@ +// +// FMDatabase+FTS3.m +// fmdb +// +// Created by Andrew on 3/27/14. +// Copyright (c) 2014 Andrew Goodale. All rights reserved. +// + +#import "FMDatabase+FTS3.h" +#import "fts3_tokenizer.h" +#include "sqlite3.h" +NSString *const kFTSCommandOptimize = @"optimize"; +NSString *const kFTSCommandRebuild = @"rebuild"; +NSString *const kFTSCommandIntegrityCheck = @"integrity-check"; +NSString *const kFTSCommandMerge = @"merge=%u,%u"; +NSString *const kFTSCommandAutoMerge = @"automerge=%u"; + +/* I know this is an evil global, but we need to be able to map names to implementations. */ +static NSMapTable *g_delegateMap = nil; + +static NSString *kDefaultTokenizerDelegateKey = @"DefaultTokenizerDelegateKey"; + +/* + ** Class derived from sqlite3_tokenizer + */ +typedef struct FMDBTokenizer +{ + sqlite3_tokenizer base; + id __unsafe_unretained delegate; +} FMDBTokenizer; + +/* + ** Create a new tokenizer instance. + */ +static int FMDBTokenizerCreate(int argc, const char * const *argv, sqlite3_tokenizer **ppTokenizer) +{ + FMDBTokenizer *tokenizer = (FMDBTokenizer *) sqlite3_malloc(sizeof(FMDBTokenizer)); + + if (tokenizer == NULL) { + return SQLITE_NOMEM; + } + + memset(tokenizer, 0, sizeof(*tokenizer)); + + NSString *key = kDefaultTokenizerDelegateKey; + if (argc > 0) { + key = [NSString stringWithUTF8String:argv[0]]; + } + + tokenizer->delegate = [g_delegateMap objectForKey:key]; + + if (!tokenizer->delegate) { + return SQLITE_ERROR; + } + + *ppTokenizer = &tokenizer->base; + return SQLITE_OK; +} + +/* + ** Destroy a tokenizer + */ +static int FMDBTokenizerDestroy(sqlite3_tokenizer *pTokenizer) +{ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* + ** Prepare to begin tokenizing a particular string. The input + ** string to be tokenized is zInput[0..nInput-1]. A cursor + ** used to incrementally tokenize this string is returned in + ** *ppCursor. + */ +static int FMDBTokenizerOpen(sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor) /* OUT: Tokenization cursor */ +{ + FMDBTokenizer *tokenizer = (FMDBTokenizer *)pTokenizer; + FMTokenizerCursor *cursor = (FMTokenizerCursor *)sqlite3_malloc(sizeof(FMTokenizerCursor)); + + if (cursor == NULL) { + return SQLITE_NOMEM; + } + + if (pInput == NULL || pInput[0] == '\0') { + cursor->inputString = CFRetain(CFSTR("")); + } else { + nBytes = (nBytes < 0) ? (int) strlen(pInput) : nBytes; + cursor->inputString = CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)pInput, nBytes, + kCFStringEncodingUTF8, false, kCFAllocatorNull); + } + + cursor->currentRange = CFRangeMake(0, 0); + cursor->tokenIndex = 0; + cursor->tokenString = NULL; + cursor->userObject = NULL; + cursor->outputBuf[0] = '\0'; + cursor->previousRange = CFRangeMake(0, 0); + cursor->previousOffsetRange = CFRangeMake(0, 0); + + [tokenizer->delegate openTokenizerCursor:cursor]; + + *ppCursor = (sqlite3_tokenizer_cursor *)cursor; + return SQLITE_OK; +} + +/* + ** Close a tokenization cursor previously opened by a call to + ** FMDBTokenizerOpen() above. + */ +static int FMDBTokenizerClose(sqlite3_tokenizer_cursor *pCursor) +{ + FMTokenizerCursor *cursor = (FMTokenizerCursor *)pCursor; + FMDBTokenizer *tokenizer = (FMDBTokenizer *)cursor->tokenizer; + + [tokenizer->delegate closeTokenizerCursor:cursor]; + + if (cursor->userObject) { + CFRelease(cursor->userObject); + } + if (cursor->tokenString) { + CFRelease(cursor->tokenString); + } + + CFRelease(cursor->inputString); + sqlite3_free(cursor); + + return SQLITE_OK; +} + + +/* + ** Extract the next token from a tokenization cursor. The cursor must + ** have been opened by a prior call to FMDBTokenizerOpen(). + */ +static int FMDBTokenizerNext(sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by Open */ + const char **pzToken, /* OUT: *pzToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition) /* OUT: Position integer of token */ +{ + FMTokenizerCursor *cursor = (FMTokenizerCursor *)pCursor; + FMDBTokenizer *tokenizer = (FMDBTokenizer *)cursor->tokenizer; + + if ([tokenizer->delegate nextTokenForCursor:cursor]) { + return SQLITE_DONE; + } + + // The range from the tokenizer is in UTF-16 positions, we need give UTF-8 positions to SQLite + // Conversion to bytes is very expensive on longer strings. In order to avoid processing the same data over and over again for each token, we cache the previousRange and previousOffsetRange + // Not all tokenizers may process strings sequentially. Reset the cached ranges if necessary + if (cursor->currentRange.location < cursor->previousRange.location + cursor->previousRange.length) { + cursor->previousRange = CFRangeMake(0, 0); + cursor->previousOffsetRange = CFRangeMake(0, 0); + } + + // First calculate the offset of current token range in original string + CFIndex locationOffset, lengthOffset; + const CFRange rangeToStartToken = CFRangeMake((cursor->previousRange.location + cursor->previousRange.length), cursor->currentRange.location - (cursor->previousRange.location + cursor->previousRange.length)); + + // This will tell us how many UTF-8 bytes there are before the start of the token + CFStringGetBytes(cursor->inputString, rangeToStartToken, kCFStringEncodingUTF8, '?', false, + NULL, 0, &locationOffset); + // and how many UTF-8 bytes there are within the token in the original string + CFStringGetBytes(cursor->inputString, cursor->currentRange, kCFStringEncodingUTF8, '?', false, + NULL, 0, &lengthOffset); + + // Update the location offset + locationOffset += (cursor->previousOffsetRange.location + cursor->previousOffsetRange.length); + + // Cache the data to reuse on next token + cursor->previousRange = cursor->currentRange; + cursor->previousOffsetRange = CFRangeMake(locationOffset, lengthOffset); + + // Determine how many bytes the new token string uses + CFIndex newBytesUsed; + const CFRange newTokenRange = CFRangeMake(0, CFStringGetLength(cursor->tokenString)); + CFStringGetBytes(cursor->tokenString, newTokenRange, kCFStringEncodingUTF8, '?', false, + cursor->outputBuf, sizeof(cursor->outputBuf), &newBytesUsed); + + *pzToken = (char *) cursor->outputBuf; + *pnBytes = (int) newBytesUsed; + *piStartOffset = (int) locationOffset; + *piEndOffset = (int) (locationOffset + lengthOffset); + *piPosition = cursor->tokenIndex++; + + return SQLITE_OK; +} + + +/* + ** The set of routines that bridge to the tokenizer delegate. + */ +static const sqlite3_tokenizer_module FMDBTokenizerModule = +{ + 0, + FMDBTokenizerCreate, + FMDBTokenizerDestroy, + FMDBTokenizerOpen, + FMDBTokenizerClose, + FMDBTokenizerNext +}; + +#pragma mark + +@implementation FMDatabase (FTS3) + ++ (void)registerTokenizer:(id)tokenizer withKey:(NSString *)key +{ + NSParameterAssert(tokenizer); + NSParameterAssert([key length]); + + static dispatch_once_t onceToken; + + dispatch_once(&onceToken, ^{ + g_delegateMap = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsCopyIn + valueOptions:NSPointerFunctionsWeakMemory]; + }); + + [g_delegateMap setObject:tokenizer forKey:key]; +} + ++ (void)registerTokenizer:(id)tokenizer +{ + [self registerTokenizer:tokenizer withKey:kDefaultTokenizerDelegateKey]; +} + +- (BOOL)installTokenizerModuleWithName:(NSString *)name +{ + const sqlite3_tokenizer_module *module = &FMDBTokenizerModule; + NSData *tokenizerData = [NSData dataWithBytes:&module length:sizeof(module)]; + + FMResultSet *results = [self executeQuery:@"SELECT fts3_tokenizer(?, ?)", name, tokenizerData]; + + if ([results next]) { + [results close]; + return YES; + } + + return NO; +} + +- (BOOL)installTokenizerModule +{ + return [self installTokenizerModuleWithName:@"fmdb"]; +} + +- (BOOL)issueCommand:(NSString *)command forTable:(NSString *)tableName +{ + NSString *sql = [NSString stringWithFormat:@"INSERT INTO %1$@(%1$@) VALUES (?)", tableName]; + + return [self executeUpdate:sql, command]; +} + +@end + +#pragma mark + +@implementation FMTextOffsets +{ + NSString *_rawOffsets; +} + +- (instancetype)initWithDBOffsets:(const char *)rawOffsets +{ + if ((self = [super init])) { + _rawOffsets = [NSString stringWithUTF8String:rawOffsets]; + } + return self; +} + +- (void)enumerateWithBlock:(void (^)(NSInteger, NSInteger, NSRange))block +{ + const char *rawOffsets = [_rawOffsets UTF8String]; + uint32_t offsetInt[4]; + int charsRead = 0; + + while (sscanf(rawOffsets, "%u %u %u %u%n", + &offsetInt[0], &offsetInt[1], &offsetInt[2], &offsetInt[3], &charsRead) == 4) { + + block(offsetInt[0], offsetInt[1], NSMakeRange(offsetInt[2], offsetInt[3])); + rawOffsets += charsRead; + } +} + +@end + +@implementation FMResultSet (FTS3) + +- (FMTextOffsets *)offsetsForColumnIndex:(int)columnIdx +{ + // The offsets() value is a space separated groups of 4 integers + const char *rawOffsets = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + return [[FMTextOffsets alloc] initWithDBOffsets:rawOffsets]; +} + +@end diff --git a/Clocker/FMDB/src/extra/fts3/FMTokenizers.h b/Clocker/FMDB/src/extra/fts3/FMTokenizers.h new file mode 100755 index 0000000..59bce9c --- /dev/null +++ b/Clocker/FMDB/src/extra/fts3/FMTokenizers.h @@ -0,0 +1,45 @@ +// +// FMTokenizers.h +// fmdb +// +// Created by Andrew on 4/9/14. +// Copyright (c) 2014 Andrew Goodale. All rights reserved. +// + +#import +#import "FMDatabase+FTS3.h" + +/** + This is the base tokenizer implementation, using a CFStringTokenizer to find words. + */ +@interface FMSimpleTokenizer : NSObject + +/** + Create the tokenizer with a given locale. The locale will be used to initialize the string tokenizer and to lowercase the parsed word. + The locale can be `NULL`, in which case the current locale will be used. + */ +- (instancetype)initWithLocale:(CFLocaleRef)locale; + +@end + +#pragma mark + +/** + This tokenizer extends the simple tokenizer with support for a stop word list. + */ +@interface FMStopWordTokenizer : NSObject + +@property (atomic, copy) NSSet *words; + +/** + Load a stop-word tokenizer using a file containing words delimited by newlines. The file should be encoded in UTF-8. + */ ++ (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL baseTokenizer:(id)tokenizer error:(NSError **)error; + +/** + Initialize an instance of the tokenizer using the set of words. The words should be lowercase if you're using the + `FMSimpleTokenizer` as the base. + */ +- (instancetype)initWithWords:(NSSet *)words baseTokenizer:(id)tokenizer; + +@end diff --git a/Clocker/FMDB/src/extra/fts3/FMTokenizers.m b/Clocker/FMDB/src/extra/fts3/FMTokenizers.m new file mode 100755 index 0000000..ab9339d --- /dev/null +++ b/Clocker/FMDB/src/extra/fts3/FMTokenizers.m @@ -0,0 +1,135 @@ +// +// FMTokenizers.m +// fmdb +// +// Created by Andrew on 4/9/14. +// Copyright (c) 2014 Andrew Goodale. All rights reserved. +// + +#import "FMTokenizers.h" + +@implementation FMSimpleTokenizer +{ + CFLocaleRef m_locale; +} + +- (id)initWithLocale:(CFLocaleRef)locale +{ + if ((self = [super init])) { + m_locale = (locale != NULL) ? CFRetain(locale) : CFLocaleCopyCurrent(); + } + return self; +} + +- (void)dealloc +{ + CFRelease(m_locale); +} + +- (void)openTokenizerCursor:(FMTokenizerCursor *)cursor +{ + cursor->tokenString = CFStringCreateMutable(NULL, 0); + cursor->userObject = CFStringTokenizerCreate(NULL, cursor->inputString, + CFRangeMake(0, CFStringGetLength(cursor->inputString)), + kCFStringTokenizerUnitWord, m_locale); +} + +- (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor +{ + CFStringTokenizerRef tokenizer = (CFStringTokenizerRef) cursor->userObject; + CFMutableStringRef tokenString = (CFMutableStringRef) cursor->tokenString; + + CFStringTokenizerTokenType tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer); + + if (tokenType == kCFStringTokenizerTokenNone) { + // No more tokens, we are finished. + return YES; + } + + // Found a regular word. The token is the lowercase version of the word. + cursor->currentRange = CFStringTokenizerGetCurrentTokenRange(tokenizer); + + // The inline buffer approach is faster and uses less memory than CFStringCreateWithSubstring() + CFStringInlineBuffer inlineBuf; + CFStringInitInlineBuffer(cursor->inputString, &inlineBuf, cursor->currentRange); + CFStringDelete(tokenString, CFRangeMake(0, CFStringGetLength(tokenString))); + + for (int i = 0; i < cursor->currentRange.length; ++i) { + UniChar nextChar = CFStringGetCharacterFromInlineBuffer(&inlineBuf, i); + CFStringAppendCharacters(tokenString, &nextChar, 1); + } + + CFStringLowercase(tokenString, m_locale); + + return NO; +} + +- (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor +{ + // FMDatabase will CFRelease the tokenString and the userObject. +} + +@end + +#pragma mark + +@implementation FMStopWordTokenizer +{ + id m_baseTokenizer; +} + +@synthesize words = m_words; + ++ (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL + baseTokenizer:(id)tokenizer + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(wordFileURL); + + NSString *contents = [NSString stringWithContentsOfURL:wordFileURL encoding:NSUTF8StringEncoding error:error]; + NSArray *stopWords = [contents componentsSeparatedByString:@"\n"]; + + if (contents == nil) { + return nil; + } + return [[self alloc] initWithWords:[NSSet setWithArray:stopWords] baseTokenizer:tokenizer]; +} + +- (instancetype)initWithWords:(NSSet *)words baseTokenizer:(id)tokenizer +{ + NSParameterAssert(tokenizer); + + if ((self = [super init])) { + m_words = [words copy]; + m_baseTokenizer = tokenizer; + } + return self; +} + +- (void)openTokenizerCursor:(FMTokenizerCursor *)cursor +{ + [m_baseTokenizer openTokenizerCursor:cursor]; +} + +- (BOOL)nextTokenForCursor:(FMTokenizerCursor *)cursor +{ + BOOL done = [m_baseTokenizer nextTokenForCursor:cursor]; + + // Don't use stop words for prefix queries since it's fine for the prefix to be in the stop list + if (CFStringHasSuffix(cursor->inputString, CFSTR("*"))) { + return done; + } + + while (!done && [self.words containsObject:(__bridge id)(cursor->tokenString)]) { + done = [m_baseTokenizer nextTokenForCursor:cursor]; + } + + return done; +} + +- (void)closeTokenizerCursor:(FMTokenizerCursor *)cursor +{ + [m_baseTokenizer closeTokenizerCursor:cursor]; +} + +@end \ No newline at end of file diff --git a/Clocker/FMDB/src/extra/fts3/fts3_tokenizer.h b/Clocker/FMDB/src/extra/fts3/fts3_tokenizer.h new file mode 100755 index 0000000..b1abb52 --- /dev/null +++ b/Clocker/FMDB/src/extra/fts3/fts3_tokenizer.h @@ -0,0 +1,160 @@ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0 or 1. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialised by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. *piStartOffset should be set to the index of the first + ** byte of the token in the input buffer. *piEndOffset should be set + ** to the index of the first byte just past the end of the token in + ** the input buffer. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); + + /*********************************************************************** + ** Methods below this point are only available if iVersion>=1. + */ + + /* + ** Configure the language id of a tokenizer cursor. + */ + int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +int fts3_global_term_cnt(int iTerm, int iCol); +int fts3_term_cnt(int iTerm, int iCol); + + +#endif /* _FTS3_TOKENIZER_H_ */ diff --git a/Clocker/FMDB/src/fmdb/FMDB.h b/Clocker/FMDB/src/fmdb/FMDB.h new file mode 100755 index 0000000..1ff5465 --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDB.h @@ -0,0 +1,10 @@ +#import + +FOUNDATION_EXPORT double FMDBVersionNumber; +FOUNDATION_EXPORT const unsigned char FMDBVersionString[]; + +#import "FMDatabase.h" +#import "FMResultSet.h" +#import "FMDatabaseAdditions.h" +#import "FMDatabaseQueue.h" +#import "FMDatabasePool.h" diff --git a/Clocker/FMDB/src/fmdb/FMDatabase.h b/Clocker/FMDB/src/fmdb/FMDatabase.h new file mode 100755 index 0000000..e82b6de --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabase.h @@ -0,0 +1,1187 @@ +#import +#import "FMResultSet.h" +#import "FMDatabasePool.h" + + +#if ! __has_feature(objc_arc) + #define FMDBAutorelease(__v) ([__v autorelease]); + #define FMDBReturnAutoreleased FMDBAutorelease + + #define FMDBRetain(__v) ([__v retain]); + #define FMDBReturnRetained FMDBRetain + + #define FMDBRelease(__v) ([__v release]); + + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); +#else + // -fobjc-arc + #define FMDBAutorelease(__v) + #define FMDBReturnAutoreleased(__v) (__v) + + #define FMDBRetain(__v) + #define FMDBReturnRetained(__v) (__v) + + #define FMDBRelease(__v) + +// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects +// and will participate in ARC. +// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. + #if OS_OBJECT_USE_OBJC + #define FMDBDispatchQueueRelease(__v) + #else + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); + #endif +#endif + +#if !__has_feature(objc_instancetype) + #define instancetype id +#endif + + +typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); + + +/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. + + ### Usage + The three main classes in FMDB are: + + - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. + - `` - Represents the results of executing a query on an `FMDatabase`. + - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. + + ### See also + + - `` - A pool of `FMDatabase` objects. + - `` - A wrapper for `sqlite_stmt`. + + ### External links + + - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation + - [SQLite web site](http://sqlite.org/) + - [FMDB mailing list](http://groups.google.com/group/fmdb) + - [SQLite FAQ](http://www.sqlite.org/faq.html) + + @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. + + */ + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-interface-ivars" + + +@interface FMDatabase : NSObject { + + void* _db; + NSString* _databasePath; + BOOL _logsErrors; + BOOL _crashOnErrors; + BOOL _traceExecution; + BOOL _checkedOut; + BOOL _shouldCacheStatements; + BOOL _isExecutingStatement; + BOOL _inTransaction; + NSTimeInterval _maxBusyRetryTimeInterval; + NSTimeInterval _startBusyRetryTime; + + NSMutableDictionary *_cachedStatements; + NSMutableSet *_openResultSets; + NSMutableSet *_openFunctions; + + NSDateFormatter *_dateFormat; +} + +///----------------- +/// @name Properties +///----------------- + +/** Whether should trace execution */ + +@property (atomic, assign) BOOL traceExecution; + +/** Whether checked out or not */ + +@property (atomic, assign) BOOL checkedOut; + +/** Crash on errors */ + +@property (atomic, assign) BOOL crashOnErrors; + +/** Logs errors */ + +@property (atomic, assign) BOOL logsErrors; + +/** Dictionary of cached statements */ + +@property (atomic, retain) NSMutableDictionary *cachedStatements; + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + ++ (instancetype)databaseWithPath:(NSString*)inPath; + +/** Initialize a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + +- (instancetype)initWithPath:(NSString*)inPath; + + +///----------------------------------- +/// @name Opening and closing database +///----------------------------------- + +/** Opening a new database connection + + The database is opened for reading and writing, and is created if it does not already exist. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open()](http://sqlite.org/c3ref/open.html) + @see openWithFlags: + @see close + */ + +- (BOOL)open; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName; + +/** Closing a database connection + + @return `YES` if success, `NO` on error. + + @see [sqlite3_close()](http://sqlite.org/c3ref/close.html) + @see open + @see openWithFlags: + */ + +- (BOOL)close; + +/** Test to see if we have a good connection to the database. + + This will confirm whether: + + - is database open + - if open, it will try a simple SELECT statement and confirm that it succeeds. + + @return `YES` if everything succeeds, `NO` on failure. + */ + +- (BOOL)goodConnection; + + +///---------------------- +/// @name Perform updates +///---------------------- + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + */ + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...; + +/** Execute single update statement + + @see executeUpdate:withErrorAndBindings: + + @warning **Deprecated**: Please use `` instead. + */ + +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated)); + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (BOOL)executeUpdate:(NSString*)sql, ...; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeUpdate: + @see lastError + @see lastErrorCode + @see lastErrorMessage + + @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command + + [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. + */ + +- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeUpdate:values:error: + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + This is similar to ``, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. + + In Swift 2, this throws errors, as if it were defined as follows: + + `func executeUpdate(sql: String!, values: [AnyObject]!) throws -> Bool` + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A `NSError` object to receive any error object (if any). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage +*/ + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; + + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param args A `va_list` of arguments. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; + +/** Execute multiple SQL statements + + This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. + + @param sql The SQL to be performed + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeStatements:withResultBlock: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql; + +/** Execute multiple SQL statements with callback handler + + This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. + + @param sql The SQL to be performed. + @param block A block that will be called for any result sets returned by any SQL statements. + Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), + non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. + This may be `nil` if you don't care to receive any results. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, + ``, or `` for diagnostic information regarding the failure. + + @see executeStatements: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block; + +/** Last insert rowid + + Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. + + This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. + + @return The rowid of the last inserted row. + + @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) + + */ + +- (int64_t)lastInsertRowId; + +/** The number of rows changed by prior SQL statement. + + This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. + + @return The number of rows changed by prior SQL statement. + + @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) + + */ + +- (int)changes; + + +///------------------------- +/// @name Retrieving results +///------------------------- + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (FMResultSet *)executeQuery:(NSString*)sql, ...; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeQuery: + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + + @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command + + [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. + + */ + +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see -executeQuery:values:error: + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + This is similar to ``, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. + + In Swift 2, this throws errors, as if it were defined as follows: + + `func executeQuery(sql: String!, values: [AnyObject]!) throws -> FMResultSet!` + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A `NSError` object to receive any error object (if any). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + + @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error. + + */ + +- (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments; + + +// Documentation forthcoming. +- (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args; + +///------------------- +/// @name Transactions +///------------------- + +/** Begin a transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginDeferredTransaction + @see inTransaction + */ + +- (BOOL)beginTransaction; + +/** Begin a deferred transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see inTransaction + */ + +- (BOOL)beginDeferredTransaction; + +/** Commit a transaction + + Commit a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see rollback + @see inTransaction + */ + +- (BOOL)commit; + +/** Rollback a transaction + + Rollback a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see inTransaction + */ + +- (BOOL)rollback; + +/** Identify whether currently in a transaction or not + + @return `YES` if currently within transaction; `NO` if not. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see rollback + */ + +- (BOOL)inTransaction; + + +///---------------------------------------- +/// @name Cached statements and result sets +///---------------------------------------- + +/** Clear cached statements */ + +- (void)clearCachedStatements; + +/** Close all open result sets */ + +- (void)closeOpenResultSets; + +/** Whether database has any open result sets + + @return `YES` if there are open result sets; `NO` if not. + */ + +- (BOOL)hasOpenResultSets; + +/** Return whether should cache statements or not + + @return `YES` if should cache statements; `NO` if not. + */ + +- (BOOL)shouldCacheStatements; + +/** Set whether should cache statements or not + + @param value `YES` if should cache statements; `NO` if not. + */ + +- (void)setShouldCacheStatements:(BOOL)value; + +/** Interupt pending database operation + + This method causes any pending database operation to abort and return at its earliest opportunity + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + */ + +- (BOOL)interrupt; + +///------------------------- +/// @name Encryption methods +///------------------------- + +/** Set encryption key. + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKey:(NSString*)key; + +/** Reset encryption key + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekey:(NSString*)key; + +/** Set encryption key using `keyData`. + + @param keyData The `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKeyWithData:(NSData *)keyData; + +/** Reset encryption key using `keyData`. + + @param keyData The `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekeyWithData:(NSData *)keyData; + + +///------------------------------ +/// @name General inquiry methods +///------------------------------ + +/** The path of the database file + + @return path of database. + + */ + +- (NSString *)databasePath; + +/** The underlying SQLite handle + + @return The `sqlite3` pointer. + + */ + +- (void*)sqliteHandle; + + +///----------------------------- +/// @name Retrieving error codes +///----------------------------- + +/** Last error message + + Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return `NSString` of the last error message. + + @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorCode + @see lastError + + */ + +- (NSString*)lastErrorMessage; + +/** Last error code + + Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return Integer value of the last error code. + + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastErrorCode; + +/** Last extended error code + + Returns the numeric extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return Integer value of the last extended error code. + + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) + @see [2. Primary Result Codes versus Extended Result Codes](http://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes) + @see [5. Extended Result Code List](http://sqlite.org/rescode.html#extrc) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastExtendedErrorCode; + +/** Had error + + @return `YES` if there was an error, `NO` if no error. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)hadError; + +/** Last error + + @return `NSError` representing the last error. + + @see lastErrorCode + @see lastErrorMessage + + */ + +- (NSError*)lastError; + + +// description forthcoming +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds; +- (NSTimeInterval)maxBusyRetryTimeInterval; + + +///------------------ +/// @name Save points +///------------------ + +/** Start save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + */ + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr; + +/** Release save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr; + +/** Roll back to save point + + @param name Name of save point. + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + + */ + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr; + +/** Start save point + + @param block Block of code to perform from within save point. + + @return The NSError corresponding to the error, if any. If no error, returns `nil`. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block; + +///---------------------------- +/// @name SQLite library status +///---------------------------- + +/** Test to see if the library is threadsafe + + @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. + + @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) + */ + ++ (BOOL)isSQLiteThreadSafe; + +/** Run-time library version numbers + + @return The sqlite library version string. + + @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) + */ + ++ (NSString*)sqliteLibVersion; + + ++ (NSString*)FMDBUserVersion; + ++ (SInt32)FMDBVersion; + + +///------------------------ +/// @name Make SQL function +///------------------------ + +/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. + + For example: + + [queue inDatabase:^(FMDatabase *adb) { + + [adb executeUpdate:@"create table ftest (foo text)"]; + [adb executeUpdate:@"insert into ftest values ('hello')"]; + [adb executeUpdate:@"insert into ftest values ('hi')"]; + [adb executeUpdate:@"insert into ftest values ('not h!')"]; + [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; + + [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) { + if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { + @autoreleasepool { + const char *c = (const char *)sqlite3_value_text(aargv[0]); + NSString *s = [NSString stringWithUTF8String:c]; + sqlite3_result_int(context, [s hasPrefix:@"h"]); + } + } + else { + NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); + sqlite3_result_null(context); + } + }]; + + int rowCount = 0; + FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; + while ([ars next]) { + rowCount++; + NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); + } + FMDBQuickCheck(rowCount == 2); + }]; + + @param name Name of function + + @param count Maximum number of parameters + + @param block The block of code for the function + + @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) + */ + +- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block; + + +///--------------------- +/// @name Date formatter +///--------------------- + +/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. + + Use this method to generate values to set the dateFormat property. + + Example: + + myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; + + @param format A valid NSDateFormatter format string. + + @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. + + */ + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format; + +/** Test whether the database has a date formatter assigned. + + @return `YES` if there is a date formatter; `NO` if not. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (BOOL)hasDateFormatter; + +/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. + + @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. + */ + +- (void)setDateFormat:(NSDateFormatter *)format; + +/** Convert the supplied NSString to NSDate, using the current database formatter. + + @param s `NSString` to convert to `NSDate`. + + @return The `NSDate` object; or `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSDate *)dateFromString:(NSString *)s; + +/** Convert the supplied NSDate to NSString, using the current database formatter. + + @param date `NSDate` of date to convert to `NSString`. + + @return The `NSString` representation of the date; `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSString *)stringFromDate:(NSDate *)date; + +@end + + +/** Objective-C wrapper for `sqlite3_stmt` + + This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. + + ### See also + + - `` + - `` + - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@interface FMStatement : NSObject { + void *_statement; + NSString *_query; + long _useCount; + BOOL _inUse; +} + +///----------------- +/// @name Properties +///----------------- + +/** Usage count */ + +@property (atomic, assign) long useCount; + +/** SQL statement */ + +@property (atomic, retain) NSString *query; + +/** SQLite sqlite3_stmt + + @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@property (atomic, assign) void *statement; + +/** Indication of whether the statement is in use */ + +@property (atomic, assign) BOOL inUse; + +///---------------------------- +/// @name Closing and Resetting +///---------------------------- + +/** Close statement */ + +- (void)close; + +/** Reset statement */ + +- (void)reset; + +@end + +#pragma clang diagnostic pop + diff --git a/Clocker/FMDB/src/fmdb/FMDatabase.m b/Clocker/FMDB/src/fmdb/FMDatabase.m new file mode 100755 index 0000000..6d3b86c --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabase.m @@ -0,0 +1,1504 @@ +#import "FMDatabase.h" +#import "unistd.h" +#import + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase () + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; + +@end + +@implementation FMDatabase +@synthesize cachedStatements=_cachedStatements; +@synthesize logsErrors=_logsErrors; +@synthesize crashOnErrors=_crashOnErrors; +@synthesize checkedOut=_checkedOut; +@synthesize traceExecution=_traceExecution; + +#pragma mark FMDatabase instantiation and deallocation + ++ (instancetype)databaseWithPath:(NSString*)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + +- (instancetype)initWithPath:(NSString*)aPath { + + assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do. + + self = [super init]; + + if (self) { + _databasePath = [aPath copy]; + _openResultSets = [[NSMutableSet alloc] init]; + _db = nil; + _logsErrors = YES; + _crashOnErrors = NO; + _maxBusyRetryTimeInterval = 2; + } + + return self; +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + FMDBRelease(_openResultSets); + FMDBRelease(_cachedStatements); + FMDBRelease(_dateFormat); + FMDBRelease(_databasePath); + FMDBRelease(_openFunctions); + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (NSString *)databasePath { + return _databasePath; +} + ++ (NSString*)FMDBUserVersion { + return @"2.6.2"; +} + +// returns 0x0240 for version 2.4. This makes it super easy to do things like: +// /* need to make sure to do X with FMDB version 2.4 or later */ +// if ([FMDatabase FMDBVersion] >= 0x0240) { … } + ++ (SInt32)FMDBVersion { + + // we go through these hoops so that we only have to change the version number in a single spot. + static dispatch_once_t once; + static SInt32 FMDBVersionVal = 0; + + dispatch_once(&once, ^{ + NSString *prodVersion = [self FMDBUserVersion]; + + if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { + prodVersion = [prodVersion stringByAppendingString:@".0"]; + } + + NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""]; + + char *e = nil; + FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16); + + }); + + return FMDBVersionVal; +} + +#pragma mark SQLite information + ++ (NSString*)sqliteLibVersion { + return [NSString stringWithFormat:@"%s", sqlite3_libversion()]; +} + ++ (BOOL)isSQLiteThreadSafe { + // make sure to read the sqlite headers on this guy! + return sqlite3_threadsafe() != 0; +} + +- (void*)sqliteHandle { + return _db; +} + +- (const char*)sqlitePath { + + if (!_databasePath) { + return ":memory:"; + } + + if ([_databasePath length] == 0) { + return ""; // this creates a temporary database (it's an sqlite thing). + } + + return [_databasePath fileSystemRepresentation]; + +} + +#pragma mark Open and close database + +- (BOOL)open { + if (_db) { + return YES; + } + + int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + + return YES; +} + +- (BOOL)openWithFlags:(int)flags { + return [self openWithFlags:flags vfs:nil]; +} +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { +#if SQLITE_VERSION_NUMBER >= 3005000 + if (_db) { + return YES; + } + + int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + return YES; +#else + NSLog(@"openWithFlags requires SQLite 3.5"); + return NO; +#endif +} + + +- (BOOL)close { + + [self clearCachedStatements]; + [self closeOpenResultSets]; + + if (!_db) { + return YES; + } + + int rc; + BOOL retry; + BOOL triedFinalizingOpenStatements = NO; + + do { + retry = NO; + rc = sqlite3_close(_db); + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + if (!triedFinalizingOpenStatements) { + triedFinalizingOpenStatements = YES; + sqlite3_stmt *pStmt; + while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { + NSLog(@"Closing leaked statement"); + sqlite3_finalize(pStmt); + retry = YES; + } + } + } + else if (SQLITE_OK != rc) { + NSLog(@"error closing!: %d", rc); + } + } + while (retry); + + _db = nil; + return YES; +} + +#pragma mark Busy handler routines + +// NOTE: appledoc seems to choke on this function for some reason; +// so when generating documentation, you might want to ignore the +// .m files so that it only documents the public interfaces outlined +// in the .h files. +// +// This is a known appledoc bug that it has problems with C functions +// within a class implementation, but for some reason, only this +// C function causes problems; the rest don't. Anyway, ignoring the .m +// files with appledoc will prevent this problem from occurring. + +static int FMDBDatabaseBusyHandler(void *f, int count) { + FMDatabase *self = (__bridge FMDatabase*)f; + + if (count == 0) { + self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate]; + return 1; + } + + NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime); + + if (delta < [self maxBusyRetryTimeInterval]) { + int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50; + int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds); + if (actualSleepInMilliseconds != requestedSleepInMillseconds) { + NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds); + } + return 1; + } + + return 0; +} + +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout { + + _maxBusyRetryTimeInterval = timeout; + + if (!_db) { + return; + } + + if (timeout > 0) { + sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self)); + } + else { + // turn it off otherwise + sqlite3_busy_handler(_db, nil, nil); + } +} + +- (NSTimeInterval)maxBusyRetryTimeInterval { + return _maxBusyRetryTimeInterval; +} + + +// we no longer make busyRetryTimeout public +// but for folks who don't bother noticing that the interface to FMDatabase changed, +// we'll still implement the method so they don't get suprise crashes +- (int)busyRetryTimeout { + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval"); + return -1; +} + +- (void)setBusyRetryTimeout:(int)i { +#pragma unused(i) + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:"); +} + +#pragma mark Result set functions + +- (BOOL)hasOpenResultSets { + return [_openResultSets count] > 0; +} + +- (void)closeOpenResultSets { + + //Copy the set so we don't get mutation errors + NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + + [rs setParentDB:nil]; + [rs close]; + + [_openResultSets removeObject:rsInWrappedInATastyValueMeal]; + } +} + +- (void)resultSetDidClose:(FMResultSet *)resultSet { + NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet]; + + [_openResultSets removeObject:setValue]; +} + +#pragma mark Cached statements + +- (void)clearCachedStatements { + + for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) { + for (FMStatement *statement in [statements allObjects]) { + [statement close]; + } + } + + [_cachedStatements removeAllObjects]; +} + +- (FMStatement*)cachedStatementForQuery:(NSString*)query { + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + + return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) { + + *stop = ![statement inUse]; + return *stop; + + }] anyObject]; +} + + +- (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query { + + query = [query copy]; // in case we got handed in a mutable string... + [statement setQuery:query]; + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + if (!statements) { + statements = [NSMutableSet set]; + } + + [statements addObject:statement]; + + [_cachedStatements setObject:statements forKey:query]; + + FMDBRelease(query); +} + +#pragma mark Key routines + +- (BOOL)rekey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self rekeyWithData:keyData]; +} + +- (BOOL)rekeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]); + + if (rc != SQLITE_OK) { + NSLog(@"error on rekey: %d", rc); + NSLog(@"%@", [self lastErrorMessage]); + } + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +- (BOOL)setKey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self setKeyWithData:keyData]; +} + +- (BOOL)setKeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]); + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +#pragma mark Date routines + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format { + + NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]); + result.dateFormat = format; + result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]); + return result; +} + + +- (BOOL)hasDateFormatter { + return _dateFormat != nil; +} + +- (void)setDateFormat:(NSDateFormatter *)format { + FMDBAutorelease(_dateFormat); + _dateFormat = FMDBReturnRetained(format); +} + +- (NSDate *)dateFromString:(NSString *)s { + return [_dateFormat dateFromString:s]; +} + +- (NSString *)stringFromDate:(NSDate *)date { + return [_dateFormat stringFromDate:date]; +} + +#pragma mark State of database + +- (BOOL)goodConnection { + + if (!_db) { + return NO; + } + + FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; + + if (rs) { + [rs close]; + return YES; + } + + return NO; +} + +- (void)warnInUse { + NSLog(@"The FMDatabase %@ is currently in use.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The FMDatabase %@ is currently in use.", self); + abort(); + } +#endif +} + +- (BOOL)databaseExists { + + if (!_db) { + + NSLog(@"The FMDatabase %@ is not open.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The FMDatabase %@ is not open.", self); + abort(); + } +#endif + + return NO; + } + + return YES; +} + +#pragma mark Error routines + +- (NSString*)lastErrorMessage { + return [NSString stringWithUTF8String:sqlite3_errmsg(_db)]; +} + +- (BOOL)hadError { + int lastErrCode = [self lastErrorCode]; + + return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW); +} + +- (int)lastErrorCode { + return sqlite3_errcode(_db); +} + +- (int)lastExtendedErrorCode { + return sqlite3_extended_errcode(_db); +} + +- (NSError*)errorWithMessage:(NSString*)message { + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey]; + + return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage]; +} + +- (NSError*)lastError { + return [self errorWithMessage:[self lastErrorMessage]]; +} + +#pragma mark Update information routines + +- (sqlite_int64)lastInsertRowId { + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + sqlite_int64 ret = sqlite3_last_insert_rowid(_db); + + _isExecutingStatement = NO; + + return ret; +} + +- (int)changes { + if (_isExecutingStatement) { + [self warnInUse]; + return 0; + } + + _isExecutingStatement = YES; + + int ret = sqlite3_changes(_db); + + _isExecutingStatement = NO; + + return ret; +} + +#pragma mark SQL manipulation + +- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { + + if ((!obj) || ((NSNull *)obj == [NSNull null])) { + sqlite3_bind_null(pStmt, idx); + } + + // FIXME - someday check the return codes on these binds. + else if ([obj isKindOfClass:[NSData class]]) { + const void *bytes = [obj bytes]; + if (!bytes) { + // it's an empty NSData object, aka [NSData data]. + // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob. + bytes = ""; + } + sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC); + } + else if ([obj isKindOfClass:[NSDate class]]) { + if (self.hasDateFormatter) + sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC); + else + sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); + } + else if ([obj isKindOfClass:[NSNumber class]]) { + + if (strcmp([obj objCType], @encode(char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj charValue]); + } + else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); + } + else if (strcmp([obj objCType], @encode(short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj shortValue]); + } + else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); + } + else if (strcmp([obj objCType], @encode(int)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj intValue]); + } + else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); + } + else if (strcmp([obj objCType], @encode(long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); + } + else if (strcmp([obj objCType], @encode(long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); + } + else if (strcmp([obj objCType], @encode(float)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj floatValue]); + } + else if (strcmp([obj objCType], @encode(double)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj doubleValue]); + } + else if (strcmp([obj objCType], @encode(BOOL)) == 0) { + sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } +} + +- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments { + + NSUInteger length = [sql length]; + unichar last = '\0'; + for (NSUInteger i = 0; i < length; ++i) { + id arg = nil; + unichar current = [sql characterAtIndex:i]; + unichar add = current; + if (last == '%') { + switch (current) { + case '@': + arg = va_arg(args, id); + break; + case 'c': + // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; + break; + case 's': + arg = [NSString stringWithUTF8String:va_arg(args, char*)]; + break; + case 'd': + case 'D': + case 'i': + arg = [NSNumber numberWithInt:va_arg(args, int)]; + break; + case 'u': + case 'U': + arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; + break; + case 'h': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithShort:(short)(va_arg(args, int))]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))]; + } + else { + i--; + } + break; + case 'q': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + break; + case 'f': + arg = [NSNumber numberWithDouble:va_arg(args, double)]; + break; + case 'g': + // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double' + arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))]; + break; + case 'l': + i++; + if (i < length) { + unichar next = [sql characterAtIndex:i]; + if (next == 'l') { + i++; + if (i < length && [sql characterAtIndex:i] == 'd') { + //%lld + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + //%llu + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + } + else if (next == 'd') { + //%ld + arg = [NSNumber numberWithLong:va_arg(args, long)]; + } + else if (next == 'u') { + //%lu + arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)]; + } + else { + i--; + } + } + else { + i--; + } + break; + default: + // something else that we can't interpret. just pass it on through like normal + break; + } + } + else if (current == '%') { + // percent sign; skip this character + add = '\0'; + } + + if (arg != nil) { + [cleanedSQL appendString:@"?"]; + [arguments addObject:arg]; + } + else if (add == (unichar)'@' && last == (unichar) '%') { + [cleanedSQL appendFormat:@"NULL"]; + } + else if (add != '\0') { + [cleanedSQL appendFormat:@"%C", add]; + } + last = current; + } +} + +#pragma mark Execute queries + +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return 0x00; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return 0x00; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *statement = 0x00; + FMResultSet *rs = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeQuery: %@", self, sql); + } + + if (_shouldCacheStatements) { + statement = [self cachedStatementForQuery:sql]; + pStmt = statement ? [statement statement] : 0x00; + [statement reset]; + } + + if (!pStmt) { + + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return nil; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!) + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + FMDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + // increment the binding count, so our check below works out + idx++; + } + else { + NSLog(@"Could not find index for %@", dictionaryKey); + } + } + } + else { + + while (idx < queryCount) { + + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + if (idx != queryCount) { + NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return nil; + } + + FMDBRetain(statement); // to balance the release below + + if (!statement) { + statement = [[FMStatement alloc] init]; + [statement setStatement:pStmt]; + + if (_shouldCacheStatements && sql) { + [self setCachedStatement:statement forQuery:sql]; + } + } + + // the statement gets closed in rs's dealloc or [rs close]; + rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self]; + [rs setQuery:sql]; + + NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; + [_openResultSets addObject:openResultSet]; + + [statement setUseCount:[statement useCount] + 1]; + + FMDBRelease(statement); + + _isExecutingStatement = NO; + + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeQuery:sql withArgumentsInArray:arguments]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil]; + if (!rs && error) { + *error = [self lastError]; + } + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +#pragma mark Execute updates + +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return NO; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *cachedStmt = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeUpdate: %@", self, sql); + } + + if (_shouldCacheStatements) { + cachedStmt = [self cachedStatementForQuery:sql]; + pStmt = cachedStmt ? [cachedStmt statement] : 0x00; + [cachedStmt reset]; + } + + if (!pStmt) { + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + sqlite3_finalize(pStmt); + + _isExecutingStatement = NO; + return NO; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + FMDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + + // increment the binding count, so our check below works out + idx++; + } + else { + NSString *message = [NSString stringWithFormat:@"Could not find index for %@", dictionaryKey]; + + if (_logsErrors) { + NSLog(@"%@", message); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + } + } + } + else { + + while (idx < queryCount) { + + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + + if (idx != queryCount) { + NSString *message = [NSString stringWithFormat:@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql]; + if (_logsErrors) { + NSLog(@"%@", message); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return NO; + } + + /* Call sqlite3_step() to run the virtual machine. Since the SQL being + ** executed is not a SELECT statement, we assume no data will be returned. + */ + + rc = sqlite3_step(pStmt); + + if (SQLITE_DONE == rc) { + // all is well, let's return. + } + else if (SQLITE_INTERRUPT == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step. Query was interrupted (%d: %s) SQLITE_INTERRUPT", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (rc == SQLITE_ROW) { + NSString *message = [NSString stringWithFormat:@"A executeUpdate is being called with a query string '%@'", sql]; + if (_logsErrors) { + NSLog(@"%@", message); + NSLog(@"DB Query: %@", sql); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + } + else { + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + if (SQLITE_ERROR == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else { + // wtf? + if (_logsErrors) { + NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + } + + if (_shouldCacheStatements && !cachedStmt) { + cachedStmt = [[FMStatement alloc] init]; + + [cachedStmt setStatement:pStmt]; + + [self setCachedStatement:cachedStmt forQuery:sql]; + + FMDBRelease(cachedStmt); + } + + int closeErrorCode; + + if (cachedStmt) { + [cachedStmt setUseCount:[cachedStmt useCount] + 1]; + closeErrorCode = sqlite3_reset(pStmt); + } + else { + /* Finalize the virtual machine. This releases all memory and other + ** resources allocated by the sqlite3_prepare() call above. + */ + closeErrorCode = sqlite3_finalize(pStmt); + } + + if (closeErrorCode != SQLITE_OK) { + if (_logsErrors) { + NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + + _isExecutingStatement = NO; + return (rc == SQLITE_DONE || rc == SQLITE_OK); +} + + +- (BOOL)executeUpdate:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +- (BOOL)executeUpdateWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeUpdate:sql withArgumentsInArray:arguments]; +} + + +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang. +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) { + + if (!theBlockAsVoid) { + return SQLITE_OK; + } + + int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid); + + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns]; + + for (NSInteger i = 0; i < columns; i++) { + NSString *key = [NSString stringWithUTF8String:names[i]]; + id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null]; + [dictionary setObject:value forKey:key]; + } + + return execCallbackBlock(dictionary); +} + +- (BOOL)executeStatements:(NSString *)sql { + return [self executeStatements:sql withResultBlock:nil]; +} + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block { + + int rc; + char *errmsg = nil; + + rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg); + + if (errmsg && [self logsErrors]) { + NSLog(@"Error inserting batch: %s", errmsg); + sqlite3_free(errmsg); + } + + return (rc == SQLITE_OK); +} + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { + + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +#pragma clang diagnostic pop + +#pragma mark Transactions + +- (BOOL)rollback { + BOOL b = [self executeUpdate:@"rollback transaction"]; + + if (b) { + _inTransaction = NO; + } + + return b; +} + +- (BOOL)commit { + BOOL b = [self executeUpdate:@"commit transaction"]; + + if (b) { + _inTransaction = NO; + } + + return b; +} + +- (BOOL)beginDeferredTransaction { + + BOOL b = [self executeUpdate:@"begin deferred transaction"]; + if (b) { + _inTransaction = YES; + } + + return b; +} + +- (BOOL)beginTransaction { + + BOOL b = [self executeUpdate:@"begin exclusive transaction"]; + if (b) { + _inTransaction = YES; + } + + return b; +} + +- (BOOL)inTransaction { + return _inTransaction; +} + +- (BOOL)interrupt +{ + if (_db) { + sqlite3_interrupt([self sqliteHandle]); + return YES; + } + return NO; +} + +static NSString *FMDBEscapeSavePointName(NSString *savepointName) { + return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; +} + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + NSError *err = 0x00; + + if (![self startSavePointWithName:name error:&err]) { + return err; + } + + if (block) { + block(&shouldRollback); + } + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [self rollbackToSavePointWithName:name error:&err]; + } + [self releaseSavePointWithName:name error:&err]; + + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + + +#pragma mark Cache statements + +- (BOOL)shouldCacheStatements { + return _shouldCacheStatements; +} + +- (void)setShouldCacheStatements:(BOOL)value { + + _shouldCacheStatements = value; + + if (_shouldCacheStatements && !_cachedStatements) { + [self setCachedStatements:[NSMutableDictionary dictionary]]; + } + + if (!_shouldCacheStatements) { + [self setCachedStatements:nil]; + } +} + +#pragma mark Callback function + +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) { +#if ! __has_feature(objc_arc) + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context); +#else + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context); +#endif + if (block) { + block(context, argc, argv); + } +} + + +- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void **argv))block { + + if (!_openFunctions) { + _openFunctions = [NSMutableSet new]; + } + + id b = FMDBReturnAutoreleased([block copy]); + + [_openFunctions addObject:b]; + + /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */ +#if ! __has_feature(objc_arc) + sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#else + sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#endif +} + +@end + + + +@implementation FMStatement +@synthesize statement=_statement; +@synthesize query=_query; +@synthesize useCount=_useCount; +@synthesize inUse=_inUse; + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + FMDBRelease(_query); +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + if (_statement) { + sqlite3_finalize(_statement); + _statement = 0x00; + } + + _inUse = NO; +} + +- (void)reset { + if (_statement) { + sqlite3_reset(_statement); + } + + _inUse = NO; +} + +- (NSString*)description { + return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query]; +} + + +@end + diff --git a/Clocker/FMDB/src/fmdb/FMDatabaseAdditions.h b/Clocker/FMDB/src/fmdb/FMDatabaseAdditions.h new file mode 100755 index 0000000..9dd0b62 --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabaseAdditions.h @@ -0,0 +1,278 @@ +// +// FMDatabaseAdditions.h +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import +#import "FMDatabase.h" + + +/** Category of additions for `` class. + + ### See also + + - `` + */ + +@interface FMDatabase (FMDatabaseAdditions) + +///---------------------------------------- +/// @name Return results of SQL to variable +///---------------------------------------- + +/** Return `int` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `int` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (int)intForQuery:(NSString*)query, ...; + +/** Return `long` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `long` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (long)longForQuery:(NSString*)query, ...; + +/** Return `BOOL` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `BOOL` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (BOOL)boolForQuery:(NSString*)query, ...; + +/** Return `double` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `double` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (double)doubleForQuery:(NSString*)query, ...; + +/** Return `NSString` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSString` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (NSString*)stringForQuery:(NSString*)query, ...; + +/** Return `NSData` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSData` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (NSData*)dataForQuery:(NSString*)query, ...; + +/** Return `NSDate` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSDate` value. + + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project. + */ + +- (NSDate*)dateForQuery:(NSString*)query, ...; + + +// Notice that there's no dataNoCopyForQuery:. +// That would be a bad idea, because we close out the result set, and then what +// happens to the data that we just didn't copy? Who knows, not I. + + +///-------------------------------- +/// @name Schema related operations +///-------------------------------- + +/** Does table exist in database? + + @param tableName The name of the table being looked for. + + @return `YES` if table found; `NO` if not found. + */ + +- (BOOL)tableExists:(NSString*)tableName; + +/** The schema of the database. + + This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: + + - `type` - The type of entity (e.g. table, index, view, or trigger) + - `name` - The name of the object + - `tbl_name` - The name of the table to which the object references + - `rootpage` - The page number of the root b-tree page for tables and indices + - `sql` - The SQL that created the entity + + @return `FMResultSet` of schema; `nil` on error. + + @see [SQLite File Format](http://www.sqlite.org/fileformat.html) + */ + +- (FMResultSet*)getSchema; + +/** The schema of the database. + + This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: + + PRAGMA table_info('employees') + + This will report: + + - `cid` - The column ID number + - `name` - The name of the column + - `type` - The data type specified for the column + - `notnull` - whether the field is defined as NOT NULL (i.e. values required) + - `dflt_value` - The default value for the column + - `pk` - Whether the field is part of the primary key of the table + + @param tableName The name of the table for whom the schema will be returned. + + @return `FMResultSet` of schema; `nil` on error. + + @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) + */ + +- (FMResultSet*)getTableSchema:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return `YES` if column exists in table in question; `NO` otherwise. + */ + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return `YES` if column exists in table in question; `NO` otherwise. + + @see columnExists:inTableWithName: + + @warning Deprecated - use `` instead. + */ + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)); + + +/** Validate SQL statement + + This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. + + @param sql The SQL statement being validated. + + @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. + + @return `YES` if validation succeeded without incident; `NO` otherwise. + + */ + +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error; + + +///----------------------------------- +/// @name Application identifier tasks +///----------------------------------- + +/** Retrieve application ID + + @return The `uint32_t` numeric value of the application ID. + + @see setApplicationID: + */ + +- (uint32_t)applicationID; + +/** Set the application ID + + @param appID The `uint32_t` numeric value of the application ID. + + @see applicationID + */ + +- (void)setApplicationID:(uint32_t)appID; + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE +/** Retrieve application ID string + + @return The `NSString` value of the application ID. + + @see setApplicationIDString: + */ + + +- (NSString*)applicationIDString; + +/** Set the application ID string + + @param string The `NSString` value of the application ID. + + @see applicationIDString + */ + +- (void)setApplicationIDString:(NSString*)string; + +#endif + +///----------------------------------- +/// @name user version identifier tasks +///----------------------------------- + +/** Retrieve user version + + @return The `uint32_t` numeric value of the user version. + + @see setUserVersion: + */ + +- (uint32_t)userVersion; + +/** Set the user-version + + @param version The `uint32_t` numeric value of the user version. + + @see userVersion + */ + +- (void)setUserVersion:(uint32_t)version; + +@end diff --git a/Clocker/FMDB/src/fmdb/FMDatabaseAdditions.m b/Clocker/FMDB/src/fmdb/FMDatabaseAdditions.m new file mode 100755 index 0000000..61fa747 --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabaseAdditions.m @@ -0,0 +1,246 @@ +// +// FMDatabaseAdditions.m +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import "FMDatabase.h" +#import "FMDatabaseAdditions.h" +#import "TargetConditionals.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase (PrivateStuff) +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args; +@end + +@implementation FMDatabase (FMDatabaseAdditions) + +#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ +va_list args; \ +va_start(args, query); \ +FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ +va_end(args); \ +if (![resultSet next]) { return (type)0; } \ +type ret = [resultSet sel:0]; \ +[resultSet close]; \ +[resultSet setParentDB:nil]; \ +return ret; + + +- (NSString*)stringForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); +} + +- (int)intForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); +} + +- (long)longForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); +} + +- (BOOL)boolForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); +} + +- (double)doubleForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); +} + +- (NSData*)dataForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); +} + +- (NSDate*)dateForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); +} + + +- (BOOL)tableExists:(NSString*)tableName { + + tableName = [tableName lowercaseString]; + + FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; + + //if at least one next exists, table exists + BOOL returnBool = [rs next]; + + //close and free object + [rs close]; + + return returnBool; +} + +/* + get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + check if table exist in database (patch from OZLB) +*/ +- (FMResultSet*)getSchema { + + //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; + + return rs; +} + +/* + get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] +*/ +- (FMResultSet*)getTableSchema:(NSString*)tableName { + + //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] + FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; + + return rs; +} + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { + + BOOL returnBool = NO; + + tableName = [tableName lowercaseString]; + columnName = [columnName lowercaseString]; + + FMResultSet *rs = [self getTableSchema:tableName]; + + //check if column is present in table schema + while ([rs next]) { + if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { + returnBool = YES; + break; + } + } + + //If this is not done FMDatabase instance stays out of pool + [rs close]; + + return returnBool; +} + + + +- (uint32_t)applicationID { +#if SQLITE_VERSION_NUMBER >= 3007017 + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma application_id"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + + return r; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return 0; +#endif +} + +- (void)setApplicationID:(uint32_t)appID { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +- (NSString*)applicationIDString { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); + + assert([s length] == 6); + + s = [s substringWithRange:NSMakeRange(1, 4)]; + + + return s; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return nil; +#endif +} + +- (void)setApplicationIDString:(NSString*)s { +#if SQLITE_VERSION_NUMBER >= 3007017 + if ([s length] != 4) { + NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); + } + + [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + +#endif + +- (uint32_t)userVersion { + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma user_version"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + return r; +} + +- (void)setUserVersion:(uint32_t)version { + NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { + return [self columnExists:columnName inTableWithName:tableName]; +} + +#pragma clang diagnostic pop + + +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { + sqlite3_stmt *pStmt = NULL; + BOOL validationSucceeded = YES; + + int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + if (rc != SQLITE_OK) { + validationSucceeded = NO; + if (error) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain + code:[self lastErrorCode] + userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] + forKey:NSLocalizedDescriptionKey]]; + } + } + + sqlite3_finalize(pStmt); + + return validationSucceeded; +} + +@end diff --git a/Clocker/FMDB/src/fmdb/FMDatabasePool.h b/Clocker/FMDB/src/fmdb/FMDatabasePool.h new file mode 100755 index 0000000..a748a93 --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabasePool.h @@ -0,0 +1,225 @@ +// +// FMDatabasePool.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import + +@class FMDatabase; + +/** Pool of `` objects. + + ### See also + + - `` + - `` + + @warning Before using `FMDatabasePool`, please consider using `` instead. + + If you really really really know what you're doing and `FMDatabasePool` is what + you really really need (ie, you're using a read only database), OK you can use + it. But just be careful not to deadlock! + + For an example on deadlocking, search for: + `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` + in the main.m file. + */ + +@interface FMDatabasePool : NSObject { + NSString *_path; + + dispatch_queue_t _lockQueue; + + NSMutableArray *_databaseInPool; + NSMutableArray *_databaseOutPool; + + __unsafe_unretained id _delegate; + + NSUInteger _maximumNumberOfDatabasesToCreate; + int _openFlags; + NSString *_vfsName; +} + +/** Database path */ + +@property (atomic, retain) NSString *path; + +/** Delegate object */ + +@property (atomic, assign) id delegate; + +/** Maximum number of databases to create */ + +@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy) NSString *vfsName; + + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString*)aPath; + +/** Create pool using path and specified flags + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags; + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath; + +/** Create pool using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; + +/** Create pool using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName; + +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'FMDatabase' subclass. + + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +///------------------------------------------------ +/// @name Keeping track of checked in/out databases +///------------------------------------------------ + +/** Number of checked-in databases in pool + + @returns Number of databases + */ + +- (NSUInteger)countOfCheckedInDatabases; + +/** Number of checked-out databases in pool + + @returns Number of databases + */ + +- (NSUInteger)countOfCheckedOutDatabases; + +/** Total number of databases in pool + + @returns Number of databases + */ + +- (NSUInteger)countOfOpenDatabases; + +/** Release all databases in pool */ + +- (void)releaseAllDatabases; + +///------------------------------------------ +/// @name Perform database operations in pool +///------------------------------------------ + +/** Synchronously perform database operations in pool. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDatabase:(void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations in pool using transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using deferred transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using save point. + + @param block The code to be run on the `FMDatabasePool` pool. + + @return `NSError` object if error; `nil` if successful. + + @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. +*/ + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; + +@end + + +/** FMDatabasePool delegate category + + This is a category that defines the protocol for the FMDatabasePool delegate + */ + +@interface NSObject (FMDatabasePoolDelegate) + +/** Asks the delegate whether database should be added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + @return `YES` if it should add database to pool; `NO` if not. + + */ + +- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; + +/** Tells the delegate that database was added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + */ + +- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; + +@end + diff --git a/Clocker/FMDB/src/fmdb/FMDatabasePool.m b/Clocker/FMDB/src/fmdb/FMDatabasePool.m new file mode 100755 index 0000000..c7fdc19 --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabasePool.m @@ -0,0 +1,291 @@ +// +// FMDatabasePool.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +#import "FMDatabasePool.h" +#import "FMDatabase.h" + +@interface FMDatabasePool() + +- (void)pushDatabaseBackInPool:(FMDatabase*)db; +- (FMDatabase*)db; + +@end + + +@implementation FMDatabasePool +@synthesize path=_path; +@synthesize delegate=_delegate; +@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; +@synthesize openFlags=_openFlags; + + ++ (instancetype)databasePoolWithPath:(NSString*)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + ++ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + + self = [super init]; + + if (self != nil) { + _path = [aPath copy]; + _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + _databaseInPool = FMDBReturnRetained([NSMutableArray array]); + _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithPath:(NSString*)aPath +{ + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (void)dealloc { + + _delegate = 0x00; + FMDBRelease(_path); + FMDBRelease(_databaseInPool); + FMDBRelease(_databaseOutPool); + + if (_lockQueue) { + FMDBDispatchQueueRelease(_lockQueue); + _lockQueue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + + +- (void)executeLocked:(void (^)(void))aBlock { + dispatch_sync(_lockQueue, aBlock); +} + +- (void)pushDatabaseBackInPool:(FMDatabase*)db { + + if (!db) { // db can be null if we set an upper bound on the # of databases to create. + return; + } + + [self executeLocked:^() { + + if ([self->_databaseInPool containsObject:db]) { + [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; + } + + [self->_databaseInPool addObject:db]; + [self->_databaseOutPool removeObject:db]; + + }]; +} + +- (FMDatabase*)db { + + __block FMDatabase *db; + + + [self executeLocked:^() { + db = [self->_databaseInPool lastObject]; + + BOOL shouldNotifyDelegate = NO; + + if (db) { + [self->_databaseOutPool addObject:db]; + [self->_databaseInPool removeLastObject]; + } + else { + + if (self->_maximumNumberOfDatabasesToCreate) { + NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; + + if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { + NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); + return; + } + } + + db = [[[self class] databaseClass] databaseWithPath:self->_path]; + shouldNotifyDelegate = YES; + } + + //This ensures that the db is opened before returning +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName]; +#else + BOOL success = [db open]; +#endif + if (success) { + if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { + [db close]; + db = 0x00; + } + else { + //It should not get added in the pool twice if lastObject was found + if (![self->_databaseOutPool containsObject:db]) { + [self->_databaseOutPool addObject:db]; + + if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { + [self->_delegate databasePool:self didAddDatabase:db]; + } + } + } + } + else { + NSLog(@"Could not open up the database at path %@", self->_path); + db = 0x00; + } + }]; + + return db; +} + +- (NSUInteger)countOfCheckedInDatabases { + + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseInPool count]; + }]; + + return count; +} + +- (NSUInteger)countOfCheckedOutDatabases { + + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseOutPool count]; + }]; + + return count; +} + +- (NSUInteger)countOfOpenDatabases { + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseOutPool count] + [self->_databaseInPool count]; + }]; + + return count; +} + +- (void)releaseAllDatabases { + [self executeLocked:^() { + [self->_databaseOutPool removeAllObjects]; + [self->_databaseInPool removeAllObjects]; + }]; +} + +- (void)inDatabase:(void (^)(FMDatabase *db))block { + + FMDatabase *db = [self db]; + + block(db); + + [self pushDatabaseBackInPool:db]; +} + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + if (useDeferred) { + [db beginDeferredTransaction]; + } + else { + [db beginTransaction]; + } + + + block(db, &shouldRollback); + + if (shouldRollback) { + [db rollback]; + } + else { + [db commit]; + } + + [self pushDatabaseBackInPool:db]; +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + NSError *err = 0x00; + + if (![db startSavePointWithName:name error:&err]) { + [self pushDatabaseBackInPool:db]; + return err; + } + + block(db, &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [db rollbackToSavePointWithName:name error:&err]; + } + [db releaseSavePointWithName:name error:&err]; + + [self pushDatabaseBackInPool:db]; + + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +@end diff --git a/Clocker/FMDB/src/fmdb/FMDatabaseQueue.h b/Clocker/FMDB/src/fmdb/FMDatabaseQueue.h new file mode 100755 index 0000000..816031e --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabaseQueue.h @@ -0,0 +1,191 @@ +// +// FMDatabaseQueue.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import + +@class FMDatabase; + +/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. + + Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. + + Instead, use `FMDatabaseQueue`. Here's how to use it: + + First, make your queue. + + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; + + Then use it like so: + + [queue inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + FMResultSet *rs = [db executeQuery:@"select * from foo"]; + while ([rs next]) { + //… + } + }]; + + An easy way to wrap things up in a transaction can be done like this: + + [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + if (whoopsSomethingWrongHappened) { + *rollback = YES; + return; + } + // etc… + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; + }]; + + `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. + + ### See also + + - `` + + @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. + + @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + + */ + +@interface FMDatabaseQueue : NSObject { + NSString *_path; + dispatch_queue_t _queue; + FMDatabase *_db; + int _openFlags; + NSString *_vfsName; +} + +/** Path of database */ + +@property (atomic, retain) NSString *path; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy) NSString *vfsName; + +///---------------------------------------------------- +/// @name Initialization, opening, and closing of queue +///---------------------------------------------------- + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + ++ (instancetype)databaseQueueWithPath:(NSString*)aPath; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabaseQueue` object. `nil` on error. + */ ++ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags; + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName; + +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'FMDatabase' subclass. + + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +/** Close database used by queue. */ + +- (void)close; + +/** Interupt pending database operation. */ + +- (void)interrupt; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations on queue. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDatabase:(void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations on queue, using transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations on queue, using deferred transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations using save point. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. +// If you need to nest, use FMDatabase's startSavePointWithName:error: instead. +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block; + +@end + diff --git a/Clocker/FMDB/src/fmdb/FMDatabaseQueue.m b/Clocker/FMDB/src/fmdb/FMDatabaseQueue.m new file mode 100755 index 0000000..6e45549 --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMDatabaseQueue.m @@ -0,0 +1,254 @@ +// +// FMDatabaseQueue.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import "FMDatabaseQueue.h" +#import "FMDatabase.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +/* + + Note: we call [self retain]; before using dispatch_sync, just incase + FMDatabaseQueue is released on another thread and we're in the middle of doing + something in dispatch_sync + + */ + +/* + * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. + * This in turn is used for deadlock detection by seeing if inDatabase: is called on + * the queue's dispatch queue, which should not happen and causes a deadlock. + */ +static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; + +@implementation FMDatabaseQueue + +@synthesize path = _path; +@synthesize openFlags = _openFlags; +@synthesize vfsName = _vfsName; + ++ (instancetype)databaseQueueWithPath:(NSString*)aPath { + + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; + + FMDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags { + + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; + + FMDBAutorelease(q); + + return q; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + + self = [super init]; + + if (self != nil) { + + _db = [[[self class] databaseClass] databaseWithPath:aPath]; + FMDBRetain(_db); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:openFlags vfs:vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"Could not create database queue for path %@", aPath); + FMDBRelease(self); + return 0x00; + } + + _path = FMDBReturnRetained(aPath); + + _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithPath:(NSString*)aPath { + + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + + +- (void)dealloc { + + FMDBRelease(_db); + FMDBRelease(_path); + + if (_queue) { + FMDBDispatchQueueRelease(_queue); + _queue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + [self->_db close]; + FMDBRelease(_db); + self->_db = 0x00; + }); + FMDBRelease(self); +} + +- (void)interrupt +{ + [[self database] interrupt]; +} + +- (FMDatabase*)database { + if (!_db) { + _db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); + FMDBRelease(_db); + _db = 0x00; + return 0x00; + } + } + + return _db; +} + +- (void)inDatabase:(void (^)(FMDatabase *db))block { +#ifndef NDEBUG + /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue + * and then check it against self to make sure we're not about to deadlock. */ + FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); + assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); +#endif + + FMDBRetain(self); + + dispatch_sync(_queue, ^() { + + FMDatabase *db = [self database]; + block(db); + + if ([db hasOpenResultSets]) { + NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); + +#if defined(DEBUG) && DEBUG + NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + NSLog(@"query: '%@'", [rs query]); + } +#endif + } + }); + + FMDBRelease(self); +} + + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + BOOL shouldRollback = NO; + + if (useDeferred) { + [[self database] beginDeferredTransaction]; + } + else { + [[self database] beginTransaction]; + } + + block([self database], &shouldRollback); + + if (shouldRollback) { + [[self database] rollback]; + } + else { + [[self database] commit]; + } + }); + + FMDBRelease(self); +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + __block NSError *err = 0x00; + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + if ([[self database] startSavePointWithName:name error:&err]) { + + block([self database], &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [[self database] rollbackToSavePointWithName:name error:&err]; + } + [[self database] releaseSavePointWithName:name error:&err]; + + } + }); + FMDBRelease(self); + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +@end diff --git a/Clocker/FMDB/src/fmdb/FMResultSet.h b/Clocker/FMDB/src/fmdb/FMResultSet.h new file mode 100755 index 0000000..af0433b --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMResultSet.h @@ -0,0 +1,468 @@ +#import + +#ifndef __has_feature // Optional. +#define __has_feature(x) 0 // Compatibility with non-clang compilers. +#endif + +#ifndef NS_RETURNS_NOT_RETAINED +#if __has_feature(attribute_ns_returns_not_retained) +#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) +#else +#define NS_RETURNS_NOT_RETAINED +#endif +#endif + +@class FMDatabase; +@class FMStatement; + +/** Represents the results of executing a query on an ``. + + ### See also + + - `` + */ + +@interface FMResultSet : NSObject { + FMDatabase *_parentDB; + FMStatement *_statement; + + NSString *_query; + NSMutableDictionary *_columnNameToIndexMap; +} + +///----------------- +/// @name Properties +///----------------- + +/** Executed query */ + +@property (atomic, retain) NSString *query; + +/** `NSMutableDictionary` mapping column names to numeric index */ + +@property (readonly) NSMutableDictionary *columnNameToIndexMap; + +/** `FMStatement` used by result set. */ + +@property (atomic, retain) FMStatement *statement; + +///------------------------------------ +/// @name Creating and closing database +///------------------------------------ + +/** Create result set from `` + + @param statement A `` to be performed + + @param aDB A `` to be used + + @return A `FMResultSet` on success; `nil` on failure + */ + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; + +/** Close result set */ + +- (void)close; + +- (void)setParentDB:(FMDatabase *)newDb; + +///--------------------------------------- +/// @name Iterating through the result set +///--------------------------------------- + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @return `YES` if row successfully retrieved; `NO` if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)next; + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @param outErr A 'NSError' object to receive any error object (if any). + + @return 'YES' if row successfully retrieved; 'NO' if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)nextWithError:(NSError **)outErr; + +/** Did the last call to `` succeed in retrieving another row? + + @return `YES` if the last call to `` succeeded in retrieving another record; `NO` if not. + + @see next + + @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. + */ + +- (BOOL)hasAnotherRow; + +///--------------------------------------------- +/// @name Retrieving information from result set +///--------------------------------------------- + +/** How many columns in result set + + @return Integer value of the number of columns. + */ + +- (int)columnCount; + +/** Column index for column name + + @param columnName `NSString` value of the name of the column. + + @return Zero-based index for column. + */ + +- (int)columnIndexForName:(NSString*)columnName; + +/** Column name for column index + + @param columnIdx Zero-based index for column. + + @return columnName `NSString` value of the name of the column. + */ + +- (NSString*)columnNameForIndex:(int)columnIdx; + +/** Result set integer value for column. + + @param columnName `NSString` value of the name of the column. + + @return `int` value of the result set's column. + */ + +- (int)intForColumn:(NSString*)columnName; + +/** Result set integer value for column. + + @param columnIdx Zero-based index for column. + + @return `int` value of the result set's column. + */ + +- (int)intForColumnIndex:(int)columnIdx; + +/** Result set `long` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `long` value of the result set's column. + */ + +- (long)longForColumn:(NSString*)columnName; + +/** Result set long value for column. + + @param columnIdx Zero-based index for column. + + @return `long` value of the result set's column. + */ + +- (long)longForColumnIndex:(int)columnIdx; + +/** Result set `long long int` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumn:(NSString*)columnName; + +/** Result set `long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumnIndex:(int)columnIdx; + +/** Result set `unsigned long long int` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; + +/** Result set `unsigned long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; + +/** Result set `BOOL` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumn:(NSString*)columnName; + +/** Result set `BOOL` value for column. + + @param columnIdx Zero-based index for column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumnIndex:(int)columnIdx; + +/** Result set `double` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumn:(NSString*)columnName; + +/** Result set `double` value for column. + + @param columnIdx Zero-based index for column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumnIndex:(int)columnIdx; + +/** Result set `NSString` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `NSString` value of the result set's column. + + */ + +- (NSString*)stringForColumn:(NSString*)columnName; + +/** Result set `NSString` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSString` value of the result set's column. + */ + +- (NSString*)stringForColumnIndex:(int)columnIdx; + +/** Result set `NSDate` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `NSDate` value of the result set's column. + */ + +- (NSDate*)dateForColumn:(NSString*)columnName; + +/** Result set `NSDate` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSDate` value of the result set's column. + + */ + +- (NSDate*)dateForColumnIndex:(int)columnIdx; + +/** Result set `NSData` value for column. + + This is useful when storing binary data in table (such as image or the like). + + @param columnName `NSString` value of the name of the column. + + @return `NSData` value of the result set's column. + + */ + +- (NSData*)dataForColumn:(NSString*)columnName; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSData` value of the result set's column. + */ + +- (NSData*)dataForColumnIndex:(int)columnIdx; + +/** Result set `(const unsigned char *)` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName; + +/** Result set `(const unsigned char *)` value for column. + + @param columnIdx Zero-based index for column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + @param columnName `NSString` value of the name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectForKeyedSubscript: + */ + +- (id)objectForColumnName:(NSString*)columnName; + +/** Result set object for column. + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectAtIndexedSubscript: + */ + +- (id)objectForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + + id result = rs[@"employee_name"]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:@"employee_name"]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:@"employee_name"]; + + @param columnName `NSString` value of the name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id)objectForKeyedSubscript:(NSString *)columnName; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + + id result = rs[0]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:0]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:0]; + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id)objectAtIndexedSubscript:(int)columnIdx; + +/** Result set `NSData` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `NSData` value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the +result set, make sure to make a copy of the data first (or just use ``/``) +If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return `NSData` value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the + result set, make sure to make a copy of the data first (or just use ``/``) + If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; + +/** Is the column `NULL`? + + @param columnIdx Zero-based index for column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIndexIsNull:(int)columnIdx; + +/** Is the column `NULL`? + + @param columnName `NSString` value of the name of the column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIsNull:(NSString*)columnName; + + +/** Returns a dictionary of the row results mapped to case sensitive keys of the column names. + + @returns `NSDictionary` of the row results. + + @warning The keys to the dictionary are case sensitive of the column names. + */ + +- (NSDictionary*)resultDictionary; + +/** Returns a dictionary of the row results + + @see resultDictionary + + @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! + */ + +- (NSDictionary*)resultDict __attribute__ ((deprecated)); + +///----------------------------- +/// @name Key value coding magic +///----------------------------- + +/** Performs `setValue` to yield support for key value observing. + + @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. + + */ + +- (void)kvcMagic:(id)object; + + +@end + diff --git a/Clocker/FMDB/src/fmdb/FMResultSet.m b/Clocker/FMDB/src/fmdb/FMResultSet.m new file mode 100755 index 0000000..6cb926d --- /dev/null +++ b/Clocker/FMDB/src/fmdb/FMResultSet.m @@ -0,0 +1,424 @@ +#import "FMResultSet.h" +#import "FMDatabase.h" +#import "unistd.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase () +- (void)resultSetDidClose:(FMResultSet *)resultSet; +@end + + +@implementation FMResultSet +@synthesize query=_query; +@synthesize statement=_statement; + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { + + FMResultSet *rs = [[FMResultSet alloc] init]; + + [rs setStatement:statement]; + [rs setParentDB:aDB]; + + NSParameterAssert(![statement inUse]); + [statement setInUse:YES]; // weak reference + + return FMDBReturnAutoreleased(rs); +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + + FMDBRelease(_query); + _query = nil; + + FMDBRelease(_columnNameToIndexMap); + _columnNameToIndexMap = nil; + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + [_statement reset]; + FMDBRelease(_statement); + _statement = nil; + + // we don't need this anymore... (i think) + //[_parentDB setInUse:NO]; + [_parentDB resultSetDidClose:self]; + _parentDB = nil; +} + +- (int)columnCount { + return sqlite3_column_count([_statement statement]); +} + +- (NSMutableDictionary *)columnNameToIndexMap { + if (!_columnNameToIndexMap) { + int columnCount = sqlite3_column_count([_statement statement]); + _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] + forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; + } + } + return _columnNameToIndexMap; +} + +- (void)kvcMagic:(id)object { + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + // check for a null row + if (c) { + NSString *s = [NSString stringWithUTF8String:c]; + + [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; + } + } +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (NSDictionary*)resultDict { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; + NSString *columnName = nil; + while ((columnName = [columnNames nextObject])) { + id objectValue = [self objectForColumnName:columnName]; + [dict setObject:objectValue forKey:columnName]; + } + + return FMDBReturnAutoreleased([dict copy]); + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + +#pragma clang diagnostic pop + +- (NSDictionary*)resultDictionary { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; + id objectValue = [self objectForColumnIndex:columnIdx]; + [dict setObject:objectValue forKey:columnName]; + } + + return dict; + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + + + + +- (BOOL)next { + return [self nextWithError:nil]; +} + +- (BOOL)nextWithError:(NSError **)outErr { + + int rc = sqlite3_step([_statement statement]); + + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); + NSLog(@"Database busy"); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { + // all is well, let's return. + } + else if (SQLITE_ERROR == rc) { + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + if (_parentDB) { + *outErr = [_parentDB lastError]; + } + else { + // If 'next' or 'nextWithError' is called after the result set is closed, + // we need to return the appropriate error. + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; + *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; + } + + } + } + else { + // wtf? + NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + + + if (rc != SQLITE_ROW) { + [self close]; + } + + return (rc == SQLITE_ROW); +} + +- (BOOL)hasAnotherRow { + return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; +} + +- (int)columnIndexForName:(NSString*)columnName { + columnName = [columnName lowercaseString]; + + NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; + + if (n) { + return [n intValue]; + } + + NSLog(@"Warning: I could not find the column named '%@'.", columnName); + + return -1; +} + + + +- (int)intForColumn:(NSString*)columnName { + return [self intForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (int)intForColumnIndex:(int)columnIdx { + return sqlite3_column_int([_statement statement], columnIdx); +} + +- (long)longForColumn:(NSString*)columnName { + return [self longForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long)longForColumnIndex:(int)columnIdx { + return (long)sqlite3_column_int64([_statement statement], columnIdx); +} + +- (long long int)longLongIntForColumn:(NSString*)columnName { + return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long long int)longLongIntForColumnIndex:(int)columnIdx { + return sqlite3_column_int64([_statement statement], columnIdx); +} + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { + return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { + return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; +} + +- (BOOL)boolForColumn:(NSString*)columnName { + return [self boolForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (BOOL)boolForColumnIndex:(int)columnIdx { + return ([self intForColumnIndex:columnIdx] != 0); +} + +- (double)doubleForColumn:(NSString*)columnName { + return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (double)doubleForColumnIndex:(int)columnIdx { + return sqlite3_column_double([_statement statement], columnIdx); +} + +- (NSString*)stringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + if (!c) { + // null row. + return nil; + } + + return [NSString stringWithUTF8String:c]; +} + +- (NSString*)stringForColumn:(NSString*)columnName { + return [self stringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumn:(NSString*)columnName { + return [self dateForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; +} + + +- (NSData*)dataForColumn:(NSString*)columnName { + return [self dataForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + if (dataBuffer == NULL) { + return nil; + } + + return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; +} + + +- (NSData*)dataNoCopyForColumn:(NSString*)columnName { + return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; + + return data; +} + + +- (BOOL)columnIndexIsNull:(int)columnIdx { + return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; +} + +- (BOOL)columnIsNull:(NSString*)columnName { + return [self columnIndexIsNull:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) { + return nil; + } + + return sqlite3_column_text([_statement statement], columnIdx); +} + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { + return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (id)objectForColumnIndex:(int)columnIdx { + int columnType = sqlite3_column_type([_statement statement], columnIdx); + + id returnValue = nil; + + if (columnType == SQLITE_INTEGER) { + returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_FLOAT) { + returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_BLOB) { + returnValue = [self dataForColumnIndex:columnIdx]; + } + else { + //default to a string for everything else + returnValue = [self stringForColumnIndex:columnIdx]; + } + + if (returnValue == nil) { + returnValue = [NSNull null]; + } + + return returnValue; +} + +- (id)objectForColumnName:(NSString*)columnName { + return [self objectForColumnIndex:[self columnIndexForName:columnName]]; +} + +// returns autoreleased NSString containing the name of the column in the result set +- (NSString*)columnNameForIndex:(int)columnIdx { + return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; +} + +- (void)setParentDB:(FMDatabase *)newDb { + _parentDB = newDb; +} + +- (id)objectAtIndexedSubscript:(int)columnIdx { + return [self objectForColumnIndex:columnIdx]; +} + +- (id)objectForKeyedSubscript:(NSString *)columnName { + return [self objectForColumnName:columnName]; +} + + +@end diff --git a/Clocker/FMDB/src/fmdb/Info.plist b/Clocker/FMDB/src/fmdb/Info.plist new file mode 100755 index 0000000..35cb69f --- /dev/null +++ b/Clocker/FMDB/src/fmdb/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.6.2 + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/Clocker/FMDB/src/sample/fmdb_Prefix.pch b/Clocker/FMDB/src/sample/fmdb_Prefix.pch new file mode 100755 index 0000000..b8c83c3 --- /dev/null +++ b/Clocker/FMDB/src/sample/fmdb_Prefix.pch @@ -0,0 +1,7 @@ +// +// Prefix header for all source files of the 'fmdb' target in the 'fmdb' project. +// + +#ifdef __OBJC__ + #import +#endif diff --git a/Clocker/FMDB/src/sample/main.m b/Clocker/FMDB/src/sample/main.m new file mode 100755 index 0000000..ea9b3d3 --- /dev/null +++ b/Clocker/FMDB/src/sample/main.m @@ -0,0 +1,1538 @@ +/* main.m + * + * Sample code to illustrate some of the basic FMDB classes and run them through their paces for illustrative purposes. + */ + +#import +#import "FMDB.h" +#import + +#define FMDBQuickCheck(SomeBool) { if (!(SomeBool)) { NSLog(@"Failure on line %d", __LINE__); abort(); } } + +void testPool(NSString *dbPath); +void testDateFormat(); +void FMDBReportABugFunction(); +void testStatementCaching(); + +int main (int argc, const char * argv[]) { + +@autoreleasepool { + + FMDBReportABugFunction(); + + NSString *dbPath = @"/tmp/tmp.db"; + + // delete the old db. + NSFileManager *fileManager = [NSFileManager defaultManager]; + [fileManager removeItemAtPath:dbPath error:nil]; + + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + NSLog(@"Is SQLite compiled with it's thread safe options turned on? %@!", [FMDatabase isSQLiteThreadSafe] ? @"Yes" : @"No"); + + { + // ------------------------------------------------------------------------------- + // Un-opened database check. + FMDBQuickCheck([db executeQuery:@"select * from table"] == nil); + NSLog(@"%d: %@", [db lastErrorCode], [db lastErrorMessage]); + } + + + if (![db open]) { + NSLog(@"Could not open db."); + + return 0; + } + + // kind of experimentalish. + [db setShouldCacheStatements:YES]; + + // create a bad statement, just to test the error code. + [db executeUpdate:@"blah blah blah"]; + + FMDBQuickCheck([db hadError]); + + if ([db hadError]) { + NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); + } + + NSError *err = 0x00; + FMDBQuickCheck(![db executeUpdate:@"blah blah blah" withErrorAndBindings:&err]); + FMDBQuickCheck(err != nil); + FMDBQuickCheck([err code] == SQLITE_ERROR); + NSLog(@"err: '%@'", err); + + + + // empty strings should still return a value. + FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", @""])); + + // same with empty bits o' mutable data + FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", [NSMutableData data]])); + + // same with empty bits o' data + FMDBQuickCheck(([db boolForQuery:@"SELECT ? not null", [NSData data]])); + + + + // how do we do pragmas? Like so: + FMResultSet *ps = [db executeQuery:@"pragma journal_mode=delete"]; + FMDBQuickCheck(![db hadError]); + FMDBQuickCheck(ps); + FMDBQuickCheck([ps next]); + [ps close]; + + // oh, but some pragmas require updates? + [db executeUpdate:@"pragma page_size=2048"]; + FMDBQuickCheck(![db hadError]); + + // what about a vacuum? + [db executeUpdate:@"vacuum"]; + FMDBQuickCheck(![db hadError]); + + // but of course, I don't bother checking the error codes below. + // Bad programmer, no cookie. + + [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; + + + [db beginTransaction]; + int i = 0; + while (i++ < 20) { + [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , + @"hi'", // look! I put in a ', and I'm not escaping it! + [NSString stringWithFormat:@"number %d", i], + [NSNumber numberWithInt:i], + [NSDate date], + [NSNumber numberWithFloat:2.2f]]; + } + [db commit]; + + + + // do it again, just because + [db beginTransaction]; + i = 0; + while (i++ < 20) { + [db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , + @"hi again'", // look! I put in a ', and I'm not escaping it! + [NSString stringWithFormat:@"number %d", i], + [NSNumber numberWithInt:i], + [NSDate date], + [NSNumber numberWithFloat:2.2f]]; + } + [db commit]; + + + + + + FMResultSet *rs = [db executeQuery:@"select rowid,* from test where a = ?", @"hi'"]; + while ([rs next]) { + // just print out what we've got in a number of formats. + NSLog(@"%d %@ %@ %@ %@ %f %f", + [rs intForColumn:@"c"], + [rs stringForColumn:@"b"], + [rs stringForColumn:@"a"], + [rs stringForColumn:@"rowid"], + [rs dateForColumn:@"d"], + [rs doubleForColumn:@"d"], + [rs doubleForColumn:@"e"]); + + + if (!([[rs columnNameForIndex:0] isEqualToString:@"rowid"] && + [[rs columnNameForIndex:1] isEqualToString:@"a"]) + ) { + NSLog(@"WHOA THERE BUDDY, columnNameForIndex ISN'T WORKING!"); + return 7; + } + } + // close the result set. + // it'll also close when it's dealloc'd, but we're closing the database before + // the autorelease pool closes, so sqlite will complain about it. + [rs close]; + + FMDBQuickCheck(![db hasOpenResultSets]); + + + + rs = [db executeQuery:@"select rowid, a, b, c from test"]; + while ([rs next]) { + + FMDBQuickCheck([rs[0] isEqual:rs[@"rowid"]]); + FMDBQuickCheck([rs[1] isEqual:rs[@"a"]]); + FMDBQuickCheck([rs[2] isEqual:rs[@"b"]]); + FMDBQuickCheck([rs[3] isEqual:rs[@"c"]]); + } + [rs close]; + + + + + + [db executeUpdate:@"create table ull (a integer)"]; + + [db executeUpdate:@"insert into ull (a) values (?)" , [NSNumber numberWithUnsignedLongLong:ULLONG_MAX]]; + + rs = [db executeQuery:@"select a from ull"]; + while ([rs next]) { + unsigned long long a = [rs unsignedLongLongIntForColumnIndex:0]; + unsigned long long b = [rs unsignedLongLongIntForColumn:@"a"]; + + FMDBQuickCheck(a == ULLONG_MAX); + FMDBQuickCheck(b == ULLONG_MAX); + } + + + // check case sensitive result dictionary. + [db executeUpdate:@"create table cs (aRowName integer, bRowName text)"]; + FMDBQuickCheck(![db hadError]); + [db executeUpdate:@"insert into cs (aRowName, bRowName) values (?, ?)" , [NSNumber numberWithBool:1], @"hello"]; + FMDBQuickCheck(![db hadError]); + + rs = [db executeQuery:@"select * from cs"]; + while ([rs next]) { + NSDictionary *d = [rs resultDictionary]; + + FMDBQuickCheck([d objectForKey:@"aRowName"]); + FMDBQuickCheck(![d objectForKey:@"arowname"]); + FMDBQuickCheck([d objectForKey:@"bRowName"]); + FMDBQuickCheck(![d objectForKey:@"browname"]); + } + + + // check funky table names + getTableSchema + [db executeUpdate:@"create table '234 fds' (foo text)"]; + FMDBQuickCheck(![db hadError]); + rs = [db getTableSchema:@"234 fds"]; + FMDBQuickCheck([rs next]); + [rs close]; + + +#if SQLITE_VERSION_NUMBER >= 3007017 + { + uint32_t appID = NSHFSTypeCodeFromFileType(NSFileTypeForHFSTypeCode('fmdb')); + + [db setApplicationID:appID]; + + uint32_t rAppID = [db applicationID]; + + NSLog(@"rAppID: %d", rAppID); + + FMDBQuickCheck(rAppID == appID); + + [db setApplicationIDString:@"acrn"]; + + NSString *s = [db applicationIDString]; + + NSLog(@"s: '%@'", s); + + FMDBQuickCheck([s isEqualToString:@"acrn"]); + + } + +#endif + + + { + // ------------------------------------------------------------------------------- + // Named parameters count test. + + FMDBQuickCheck([db executeUpdate:@"create table namedparamcounttest (a text, b text, c integer, d double)"]); + NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; + [dictionaryArgs setObject:@"Text1" forKey:@"a"]; + [dictionaryArgs setObject:@"Text2" forKey:@"b"]; + [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; + [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; + FMDBQuickCheck([db executeUpdate:@"insert into namedparamcounttest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); + + rs = [db executeQuery:@"select * from namedparamcounttest"]; + + FMDBQuickCheck((rs != nil)); + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"Text1"]); + FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]); + FMDBQuickCheck([rs intForColumn:@"c"] == 1); + FMDBQuickCheck([rs doubleForColumn:@"d"] == 2.0); + + [rs close]; + + // note that at this point, dictionaryArgs has way more values than we need, but the query should still work since + // a is in there, and that's all we need. + rs = [db executeQuery:@"select * from namedparamcounttest where a = :a" withParameterDictionary:dictionaryArgs]; + + FMDBQuickCheck((rs != nil)); + FMDBQuickCheck([rs next]); + [rs close]; + + + + // ***** Please note the following codes ***** + + dictionaryArgs = [NSMutableDictionary dictionary]; + + [dictionaryArgs setObject:@"NewText1" forKey:@"a"]; + [dictionaryArgs setObject:@"NewText2" forKey:@"b"]; + [dictionaryArgs setObject:@"OneMoreText" forKey:@"OneMore"]; + + BOOL rc = [db executeUpdate:@"update namedparamcounttest set a = :a, b = :b where b = 'Text2'" withParameterDictionary:dictionaryArgs]; + + FMDBQuickCheck(rc); + + if (!rc) { + NSLog(@"ERROR: %d - %@", db.lastErrorCode, db.lastErrorMessage); + } + + + } + + + + + + + + + + + // ---------------------------------------------------------------------------------------- + // blob support. + [db executeUpdate:@"create table blobTable (a text, b blob)"]; + + // let's read in an image from safari's app bundle. + NSData *safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"]; + if (safariCompass) { + [db executeUpdate:@"insert into blobTable (a, b) values (?,?)", @"safari's compass", safariCompass]; + + rs = [db executeQuery:@"select b from blobTable where a = ?", @"safari's compass"]; + if ([rs next]) { + safariCompass = [rs dataForColumn:@"b"]; + [safariCompass writeToFile:@"/tmp/compass.icns" atomically:NO]; + + // let's look at our fancy image that we just wrote out.. + system("/usr/bin/open /tmp/compass.icns"); + + // ye shall read the header for this function, or suffer the consequences. + safariCompass = [rs dataNoCopyForColumn:@"b"]; + [safariCompass writeToFile:@"/tmp/compass_data_no_copy.icns" atomically:NO]; + system("/usr/bin/open /tmp/compass_data_no_copy.icns"); + } + else { + NSLog(@"Could not select image."); + } + + [rs close]; + + } + else { + NSLog(@"Can't find compass image.."); + } + + + // test out the convenience methods in +Additions + [db executeUpdate:@"create table t1 (a integer)"]; + [db executeUpdate:@"insert into t1 values (?)", [NSNumber numberWithInt:5]]; + + NSLog(@"Count of changes (should be 1): %d", [db changes]); + FMDBQuickCheck([db changes] == 1); + + int ia = [db intForQuery:@"select a from t1 where a = ?", [NSNumber numberWithInt:5]]; + if (ia != 5) { + NSLog(@"intForQuery didn't work (a != 5)"); + } + + // test the busy rety timeout schtuff. + + [db setMaxBusyRetryTimeInterval:5]; + + FMDatabase *newDb = [FMDatabase databaseWithPath:dbPath]; + [newDb open]; + + rs = [newDb executeQuery:@"select rowid,* from test where a = ?", @"hi'"]; + [rs next]; // just grab one... which will keep the db locked. + + NSLog(@"Testing the busy timeout"); + + NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]; + + BOOL success = [db executeUpdate:@"insert into t1 values (5)"]; + + if (success) { + NSLog(@"Whoa- the database didn't stay locked!"); + return 7; + } + else { + NSLog(@"Hurray, our timeout worked"); + } + + [rs close]; + [newDb close]; + + success = [db executeUpdate:@"insert into t1 values (5)"]; + if (!success) { + NSLog(@"Whoa- the database shouldn't be locked!"); + return 8; + } + else { + NSLog(@"Hurray, we can insert again!"); + } + + NSTimeInterval end = [NSDate timeIntervalSinceReferenceDate] - startTime; + + NSLog(@"Took %f seconds for the timeout.", end); + + // test some nullness. + [db executeUpdate:@"create table t2 (a integer, b integer)"]; + + if (![db executeUpdate:@"insert into t2 values (?, ?)", nil, [NSNumber numberWithInt:5]]) { + NSLog(@"UH OH, can't insert a nil value for some reason..."); + } + + + + + rs = [db executeQuery:@"select * from t2"]; + while ([rs next]) { + NSString *aa = [rs stringForColumnIndex:0]; + NSString *b = [rs stringForColumnIndex:1]; + + if (aa != nil) { + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"OH OH, PROBLEMO!"); + return 10; + } + else { + NSLog(@"YAY, NULL VALUES"); + } + + if (![b isEqualToString:@"5"]) { + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"OH OH, PROBLEMO!"); + return 10; + } + } + + + + + + + + + + + // test some inner loop funkness. + [db executeUpdate:@"create table t3 (a somevalue)"]; + + + // do it again, just because + [db beginTransaction]; + i = 0; + while (i++ < 20) { + [db executeUpdate:@"insert into t3 (a) values (?)" , [NSNumber numberWithInt:i]]; + } + [db commit]; + + + + + rs = [db executeQuery:@"select * from t3"]; + while ([rs next]) { + int foo = [rs intForColumnIndex:0]; + + int newVal = foo + 100; + + [db executeUpdate:@"update t3 set a = ? where a = ?" , [NSNumber numberWithInt:newVal], [NSNumber numberWithInt:foo]]; + + + FMResultSet *rs2 = [db executeQuery:@"select a from t3 where a = ?", [NSNumber numberWithInt:newVal]]; + [rs2 next]; + + if ([rs2 intForColumnIndex:0] != newVal) { + NSLog(@"Oh crap, our update didn't work out!"); + return 9; + } + + [rs2 close]; + } + + + // NSNull tests + [db executeUpdate:@"create table nulltest (a text, b text)"]; + + [db executeUpdate:@"insert into nulltest (a, b) values (?, ?)" , [NSNull null], @"a"]; + [db executeUpdate:@"insert into nulltest (a, b) values (?, ?)" , nil, @"b"]; + + rs = [db executeQuery:@"select * from nulltest"]; + + while ([rs next]) { + + NSString *a = [rs stringForColumnIndex:0]; + NSString *b = [rs stringForColumnIndex:1]; + + if (!b) { + NSLog(@"Oh crap, the nil / null inserts didn't work!"); + return 10; + } + + if (a) { + NSLog(@"Oh crap, the nil / null inserts didn't work (son of error message)!"); + return 11; + } + else { + NSLog(@"HURRAH FOR NSNULL (and nil)!"); + } + } + + + FMDBQuickCheck([db columnExists:@"a" inTableWithName:@"nulltest"]); + FMDBQuickCheck([db columnExists:@"b" inTableWithName:@"nulltest"]); + FMDBQuickCheck(![db columnExists:@"c" inTableWithName:@"nulltest"]); + + + // null dates + + NSDate *date = [NSDate date]; + [db executeUpdate:@"create table datetest (a double, b double, c double)"]; + [db executeUpdate:@"insert into datetest (a, b, c) values (?, ?, 0)" , [NSNull null], date]; + + rs = [db executeQuery:@"select * from datetest"]; + + while ([rs next]) { + + NSDate *a = [rs dateForColumnIndex:0]; + NSDate *b = [rs dateForColumnIndex:1]; + NSDate *c = [rs dateForColumnIndex:2]; + + if (a) { + NSLog(@"Oh crap, the null date insert didn't work!"); + return 12; + } + + if (!c) { + NSLog(@"Oh crap, the 0 date insert didn't work!"); + return 12; + } + + NSTimeInterval dti = fabs([b timeIntervalSinceDate:date]); + + if (floor(dti) > 0.0) { + NSLog(@"Date matches didn't really happen... time difference of %f", dti); + return 13; + } + + + dti = fabs([c timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:0]]); + + if (floor(dti) > 0.0) { + NSLog(@"Date matches didn't really happen... time difference of %f", dti); + return 13; + } + } + + NSDate *foo = [db dateForQuery:@"select b from datetest where c = 0"]; + assert(foo); + NSTimeInterval dti = fabs([foo timeIntervalSinceDate:date]); + if (floor(dti) > 0.0) { + NSLog(@"Date matches didn't really happen... time difference of %f", dti); + return 14; + } + + [db executeUpdate:@"create table nulltest2 (s text, d data, i integer, f double, b integer)"]; + + // grab the data for this again, since we overwrote it with some memory that has since disapeared. + safariCompass = [NSData dataWithContentsOfFile:@"/Applications/Safari.app/Contents/Resources/compass.icns"]; + + [db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , @"Hi", safariCompass, [NSNumber numberWithInt:12], [NSNumber numberWithFloat:4.4f], [NSNumber numberWithBool:YES]]; + [db executeUpdate:@"insert into nulltest2 (s, d, i, f, b) values (?, ?, ?, ?, ?)" , nil, nil, nil, nil, [NSNull null]]; + + rs = [db executeQuery:@"select * from nulltest2"]; + + while ([rs next]) { + + i = [rs intForColumnIndex:2]; + + if (i == 12) { + // it's the first row we inserted. + FMDBQuickCheck(![rs columnIndexIsNull:0]); + FMDBQuickCheck(![rs columnIndexIsNull:1]); + FMDBQuickCheck(![rs columnIndexIsNull:2]); + FMDBQuickCheck(![rs columnIndexIsNull:3]); + FMDBQuickCheck(![rs columnIndexIsNull:4]); + FMDBQuickCheck( [rs columnIndexIsNull:5]); + + FMDBQuickCheck([[rs dataForColumn:@"d"] length] == [safariCompass length]); + FMDBQuickCheck(![rs dataForColumn:@"notthere"]); + FMDBQuickCheck(![rs stringForColumnIndex:-2]); + FMDBQuickCheck([rs boolForColumnIndex:4]); + FMDBQuickCheck([rs boolForColumn:@"b"]); + + FMDBQuickCheck(fabs(4.4 - [rs doubleForColumn:@"f"]) < 0.0000001); + + FMDBQuickCheck(12 == [rs intForColumn:@"i"]); + FMDBQuickCheck(12 == [rs intForColumnIndex:2]); + + FMDBQuickCheck(0 == [rs intForColumnIndex:12]); // there is no 12 + FMDBQuickCheck(0 == [rs intForColumn:@"notthere"]); + + FMDBQuickCheck(12 == [rs longForColumn:@"i"]); + FMDBQuickCheck(12 == [rs longLongIntForColumn:@"i"]); + } + else { + // let's test various null things. + + FMDBQuickCheck([rs columnIndexIsNull:0]); + FMDBQuickCheck([rs columnIndexIsNull:1]); + FMDBQuickCheck([rs columnIndexIsNull:2]); + FMDBQuickCheck([rs columnIndexIsNull:3]); + FMDBQuickCheck([rs columnIndexIsNull:4]); + FMDBQuickCheck([rs columnIndexIsNull:5]); + + + FMDBQuickCheck(![rs dataForColumn:@"d"]); + + } + } + + + + { + + [db executeUpdate:@"create table utest (a text)"]; + [db executeUpdate:@"insert into utest values (?)", @"/übertest"]; + + rs = [db executeQuery:@"select * from utest where a = ?", @"/übertest"]; + FMDBQuickCheck([rs next]); + [rs close]; + } + + + { + [db executeUpdate:@"create table testOneHundredTwelvePointTwo (a text, b integer)"]; + [db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:2], nil]]; + [db executeUpdate:@"insert into testOneHundredTwelvePointTwo values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", [NSNumber numberWithInteger:3], nil]]; + + + rs = [db executeQuery:@"select * from testOneHundredTwelvePointTwo where b > ?" withArgumentsInArray:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]]]; + + FMDBQuickCheck([rs next]); + + FMDBQuickCheck([rs hasAnotherRow]); + FMDBQuickCheck(![db hadError]); + + FMDBQuickCheck([[rs stringForColumnIndex:0] isEqualToString:@"one"]); + FMDBQuickCheck([rs intForColumnIndex:1] == 2); + + FMDBQuickCheck([rs next]); + + FMDBQuickCheck([rs intForColumnIndex:1] == 3); + + FMDBQuickCheck(![rs next]); + FMDBQuickCheck(![rs hasAnotherRow]); + + } + + { + + FMDBQuickCheck([db executeUpdate:@"create table t4 (a text, b text)"]); + FMDBQuickCheck(([db executeUpdate:@"insert into t4 (a, b) values (?, ?)", @"one", @"two"])); + + rs = [db executeQuery:@"select t4.a as 't4.a', t4.b from t4;"]; + + FMDBQuickCheck((rs != nil)); + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"t4.a"] isEqualToString:@"one"]); + FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"two"]); + + FMDBQuickCheck(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two") == 0); + + [rs close]; + + // let's try these again, with the withArgumentsInArray: variation + FMDBQuickCheck([db executeUpdate:@"drop table t4;" withArgumentsInArray:[NSArray array]]); + FMDBQuickCheck([db executeUpdate:@"create table t4 (a text, b text)" withArgumentsInArray:[NSArray array]]); + FMDBQuickCheck(([db executeUpdate:@"insert into t4 (a, b) values (?, ?)" withArgumentsInArray:[NSArray arrayWithObjects:@"one", @"two", nil]])); + + rs = [db executeQuery:@"select t4.a as 't4.a', t4.b from t4;" withArgumentsInArray:[NSArray array]]; + + FMDBQuickCheck((rs != nil)); + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"t4.a"] isEqualToString:@"one"]); + FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"two"]); + + FMDBQuickCheck(strcmp((const char*)[rs UTF8StringForColumnName:@"b"], "two") == 0); + + [rs close]; + } + + + + + { + FMDBQuickCheck([db tableExists:@"t4"]); + FMDBQuickCheck(![db tableExists:@"thisdoesntexist"]); + + rs = [db getSchema]; + while ([rs next]) { + FMDBQuickCheck([[rs stringForColumn:@"type"] isEqualToString:@"table"]); + } + } + + + { + FMDBQuickCheck([db executeUpdate:@"create table t5 (a text, b int, c blob, d text, e text)"]); + FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t5 values (%s, %d, %@, %c, %lld)", "text", 42, @"BLOB", 'd', 12345678901234ll])); + + rs = [db executeQueryWithFormat:@"select * from t5 where a = %s and a = %@ and b = %d", "text", @"text", 42]; + FMDBQuickCheck((rs != nil)); + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"text"]); + FMDBQuickCheck(([rs intForColumn:@"b"] == 42)); + FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"BLOB"]); + FMDBQuickCheck([[rs stringForColumn:@"d"] isEqualToString:@"d"]); + FMDBQuickCheck(([rs longLongIntForColumn:@"e"] == 12345678901234)); + + [rs close]; + } + + + + { + FMDBQuickCheck([db executeUpdate:@"create table t55 (a text, b int, c float)"]); + short testShort = -4; + float testFloat = 5.5; + FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t55 values (%c, %hi, %g)", 'a', testShort, testFloat])); + + unsigned short testUShort = 6; + FMDBQuickCheck(([db executeUpdateWithFormat:@"insert into t55 values (%c, %hu, %g)", 'a', testUShort, testFloat])); + + + rs = [db executeQueryWithFormat:@"select * from t55 where a = %s order by 2", "a"]; + FMDBQuickCheck((rs != nil)); + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"a"]); + FMDBQuickCheck(([rs intForColumn:@"b"] == -4)); + FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"5.5"]); + + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"a"]); + FMDBQuickCheck(([rs intForColumn:@"b"] == 6)); + FMDBQuickCheck([[rs stringForColumn:@"c"] isEqualToString:@"5.5"]); + + [rs close]; + + } + + { + FMDBQuickCheck([db executeUpdate:@"create table tatwhat (a text)"]); + + BOOL worked = [db executeUpdateWithFormat:@"insert into tatwhat values(%@)", nil]; + + FMDBQuickCheck(worked); + + rs = [db executeQueryWithFormat:@"select * from tatwhat"]; + FMDBQuickCheck((rs != nil)); + FMDBQuickCheck(([rs next])); + FMDBQuickCheck([rs columnIndexIsNull:0]); + + FMDBQuickCheck((![rs next])); + + } + + + { + FMDBQuickCheck(([db executeUpdate:@"insert into t5 values (?, ?, ?, ?, ?)" withErrorAndBindings:&err, @"text", [NSNumber numberWithInt:42], @"BLOB", @"d", [NSNumber numberWithInt:0]])); + + } + + { + rs = [db executeQuery:@"select * from t5 where a=?" withArgumentsInArray:@[]]; + FMDBQuickCheck((![rs next])); + } + + // test attach for the heck of it. + { + + //FMDatabase *dbA = [FMDatabase databaseWithPath:dbPath]; + [fileManager removeItemAtPath:@"/tmp/attachme.db" error:nil]; + FMDatabase *dbB = [FMDatabase databaseWithPath:@"/tmp/attachme.db"]; + FMDBQuickCheck([dbB open]); + FMDBQuickCheck([dbB executeUpdate:@"create table attached (a text)"]); + FMDBQuickCheck(([dbB executeUpdate:@"insert into attached values (?)", @"test"])); + FMDBQuickCheck([dbB close]); + + [db executeUpdate:@"attach database '/tmp/attachme.db' as attack"]; + + rs = [db executeQuery:@"select * from attack.attached"]; + FMDBQuickCheck([rs next]); + [rs close]; + + } + + + + { + // ------------------------------------------------------------------------------- + // Named parameters. + FMDBQuickCheck([db executeUpdate:@"create table namedparamtest (a text, b text, c integer, d double)"]); + NSMutableDictionary *dictionaryArgs = [NSMutableDictionary dictionary]; + [dictionaryArgs setObject:@"Text1" forKey:@"a"]; + [dictionaryArgs setObject:@"Text2" forKey:@"b"]; + [dictionaryArgs setObject:[NSNumber numberWithInt:1] forKey:@"c"]; + [dictionaryArgs setObject:[NSNumber numberWithDouble:2.0] forKey:@"d"]; + FMDBQuickCheck([db executeUpdate:@"insert into namedparamtest values (:a, :b, :c, :d)" withParameterDictionary:dictionaryArgs]); + + rs = [db executeQuery:@"select * from namedparamtest"]; + + FMDBQuickCheck((rs != nil)); + + [rs next]; + + FMDBQuickCheck([[rs stringForColumn:@"a"] isEqualToString:@"Text1"]); + FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]); + FMDBQuickCheck([rs intForColumn:@"c"] == 1); + FMDBQuickCheck([rs doubleForColumn:@"d"] == 2.0); + + [rs close]; + + + dictionaryArgs = [NSMutableDictionary dictionary]; + + [dictionaryArgs setObject:@"Text2" forKey:@"blah"]; + + rs = [db executeQuery:@"select * from namedparamtest where b = :blah" withParameterDictionary:dictionaryArgs]; + + FMDBQuickCheck((rs != nil)); + FMDBQuickCheck([rs next]); + FMDBQuickCheck([[rs stringForColumn:@"b"] isEqualToString:@"Text2"]); + + [rs close]; + + + + + } + + // just for fun. + rs = [db executeQuery:@"pragma database_list"]; + while ([rs next]) { + NSString *file = [rs stringForColumn:@"file"]; + NSLog(@"database_list: %@", file); + } + + + // print out some stats if we are using cached statements. + if ([db shouldCacheStatements]) { + + NSEnumerator *e = [[db cachedStatements] objectEnumerator];; + FMStatement *statement; + + while ((statement = [e nextObject])) { + NSLog(@"%@", statement); + } + } + + + [db setShouldCacheStatements:true]; + + [db executeUpdate:@"CREATE TABLE testCacheStatements(key INTEGER PRIMARY KEY, value INTEGER)"]; + [db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (1, 2)"]; + [db executeUpdate:@"INSERT INTO testCacheStatements (key, value) VALUES (2, 4)"]; + + FMDBQuickCheck([[db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); + FMDBQuickCheck([[db executeQuery:@"SELECT * FROM testCacheStatements WHERE key=1"] next]); + + [db close]; + + + testPool(dbPath); + testDateFormat(); + + + + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath]; + + FMDBQuickCheck(queue); + + { + [queue inDatabase:^(FMDatabase *adb) { + + + + [adb executeUpdate:@"create table qfoo (foo text)"]; + [adb executeUpdate:@"insert into qfoo values ('hi')"]; + [adb executeUpdate:@"insert into qfoo values ('hello')"]; + [adb executeUpdate:@"insert into qfoo values ('not')"]; + + + + int count = 0; + FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; + while ([rsl next]) { + count++; + } + + FMDBQuickCheck(count == 2); + + count = 0; + rsl = [adb executeQuery:@"select * from qfoo where foo like ?", @"h%"]; + while ([rsl next]) { + count++; + } + + FMDBQuickCheck(count == 2); + }]; + + } + + FMDatabaseQueue *queue2 = [FMDatabaseQueue databaseQueueWithPath:dbPath flags:SQLITE_OPEN_READONLY]; + + FMDBQuickCheck(queue2); + { + [queue2 inDatabase:^(FMDatabase *db2) { + FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"]; + FMDBQuickCheck(rs1 != nil); + [rs1 close]; + + BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; + FMDBQuickCheck(!ok); + }]; + + [queue2 close]; + + [queue2 inDatabase:^(FMDatabase *db2) { + FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"]; + FMDBQuickCheck(rs1 != nil); + [rs1 close]; + + BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; + FMDBQuickCheck(!ok); + }]; + } + + { + // You should see pairs of numbers show up in stdout for this stuff: + size_t ops = 16; + + dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(ops, dqueue, ^(size_t nby) { + + // just mix things up a bit for demonstration purposes. + if (nby % 2 == 1) { + [NSThread sleepForTimeInterval:.1]; + + [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { + NSLog(@"Starting query %ld", nby); + + FMResultSet *rsl = [adb executeQuery:@"select * from qfoo where foo like 'h%'"]; + while ([rsl next]) { + ;// whatever. + } + + NSLog(@"Ending query %ld", nby); + }]; + + } + + if (nby % 3 == 1) { + [NSThread sleepForTimeInterval:.1]; + } + + [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { + NSLog(@"Starting update %ld", nby); + [adb executeUpdate:@"insert into qfoo values ('1')"]; + [adb executeUpdate:@"insert into qfoo values ('2')"]; + [adb executeUpdate:@"insert into qfoo values ('3')"]; + NSLog(@"Ending update %ld", nby); + }]; + }); + + [queue close]; + + [queue inDatabase:^(FMDatabase *adb) { + FMDBQuickCheck([adb executeUpdate:@"insert into qfoo values ('1')"]); + }]; + } + + { + + + [queue inDatabase:^(FMDatabase *adb) { + [adb executeUpdate:@"create table colNameTest (a, b, c, d)"]; + FMDBQuickCheck([adb executeUpdate:@"insert into colNameTest values (1, 2, 3, 4)"]); + + FMResultSet *ars = [adb executeQuery:@"select * from colNameTest"]; + + NSDictionary *d = [ars columnNameToIndexMap]; + FMDBQuickCheck([d count] == 4); + + FMDBQuickCheck([[d objectForKey:@"a"] intValue] == 0); + FMDBQuickCheck([[d objectForKey:@"b"] intValue] == 1); + FMDBQuickCheck([[d objectForKey:@"c"] intValue] == 2); + FMDBQuickCheck([[d objectForKey:@"d"] intValue] == 3); + + [ars close]; + + }]; + + } + + + { + [queue inDatabase:^(FMDatabase *adb) { + [adb executeUpdate:@"create table transtest (a integer)"]; + FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (1)"]); + FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (2)"]); + + int rowCount = 0; + FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; + while ([ars next]) { + rowCount++; + } + + FMDBQuickCheck(rowCount == 2); + }]; + + + + [queue inTransaction:^(FMDatabase *adb, BOOL *rollback) { + FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (3)"]); + + if (YES) { + // uh oh!, something went wrong (not really, this is just a test + *rollback = YES; + return; + } + + FMDBQuickCheck([adb executeUpdate:@"insert into transtest values (4)"]); + }]; + + [queue inDatabase:^(FMDatabase *adb) { + + int rowCount = 0; + FMResultSet *ars = [adb executeQuery:@"select * from transtest"]; + while ([ars next]) { + rowCount++; + } + + FMDBQuickCheck(![adb hasOpenResultSets]); + + NSLog(@"after rollback, rowCount is %d (should be 2)", rowCount); + + FMDBQuickCheck(rowCount == 2); + }]; + } + + // hey, let's make a custom function! + + [queue inDatabase:^(FMDatabase *adb) { + + [adb executeUpdate:@"create table ftest (foo text)"]; + [adb executeUpdate:@"insert into ftest values ('hello')"]; + [adb executeUpdate:@"insert into ftest values ('hi')"]; + [adb executeUpdate:@"insert into ftest values ('not h!')"]; + [adb executeUpdate:@"insert into ftest values ('definitely not h!')"]; + + [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(/*sqlite3_context*/ void *context, int aargc, /*sqlite3_value*/ void **aargv) { + if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) { + + @autoreleasepool { + + const char *c = (const char *)sqlite3_value_text(aargv[0]); + + NSString *s = [NSString stringWithUTF8String:c]; + + sqlite3_result_int(context, [s hasPrefix:@"h"]); + } + } + else { + NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__); + sqlite3_result_null(context); + } + }]; + + int rowCount = 0; + FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"]; + while ([ars next]) { + rowCount++; + + NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]); + + } + FMDBQuickCheck(rowCount == 2); + + testStatementCaching(); + + }]; + + NSLog(@"That was version %@ of sqlite", [FMDatabase sqliteLibVersion]); + + +}// this is the end of our @autorelease pool. + + + return 0; +} +/* + Test statement caching + This test checks the fixes that address https://github.com/ccgus/fmdb/issues/6 + */ + +void testStatementCaching() { + + FMDatabase *db = [FMDatabase databaseWithPath:nil]; // use in-memory DB + [db open]; + + [db executeUpdate:@"DROP TABLE IF EXISTS testStatementCaching"]; + [db executeUpdate:@"CREATE TABLE testStatementCaching ( value INTEGER )"]; + [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; + [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (1)"]; + [db executeUpdate:@"INSERT INTO testStatementCaching( value ) VALUES (2)"]; + + [db setShouldCacheStatements:YES]; + + // two iterations. + // the first time through no statements will be from the cache. + // the second time through all statements come from the cache. + for (int i = 1; i <= 2; i++ ) { + + FMResultSet* rs1 = [db executeQuery: @"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @1]; // results in 2 rows... + FMDBQuickCheck([rs1 next]); + + // confirm that we're seeing the benefits of caching. + FMDBQuickCheck([[rs1 statement] useCount] == i); + + FMResultSet* rs2 = [db executeQuery:@"SELECT rowid, * FROM testStatementCaching WHERE value = ?", @2]; // results in 1 row + FMDBQuickCheck([rs2 next]); + FMDBQuickCheck([[rs2 statement] useCount] == i); + + // This is the primary check - with the old implementation of statement caching, rs2 would have rejiggered the (cached) statement used by rs1, making this test fail to return the 2nd row in rs1. + FMDBQuickCheck([rs1 next]); + + [rs1 close]; + [rs2 close]; + } + + [db close]; +} + +/* + Test the various FMDatabasePool things. +*/ + +void testPool(NSString *dbPath) { + + FMDatabasePool *dbPool = [FMDatabasePool databasePoolWithPath:dbPath]; + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 0); + + __block FMDatabase *db1; + + [dbPool inDatabase:^(FMDatabase *db) { + + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + + FMDBQuickCheck([db tableExists:@"t4"]); + + db1 = db; + + }]; + + [dbPool inDatabase:^(FMDatabase *db) { + FMDBQuickCheck(db1 == db); + + [dbPool inDatabase:^(FMDatabase *db2) { + FMDBQuickCheck(db2 != db); + }]; + + }]; + + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 2); + + + [dbPool inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"create table easy (a text)"]; + [db executeUpdate:@"create table easy2 (a text)"]; + + }]; + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 2); + + [dbPool releaseAllDatabases]; + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 0); + + [dbPool inDatabase:^(FMDatabase *aDb) { + + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); + + FMDBQuickCheck([aDb tableExists:@"t4"]); + + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); + + FMDBQuickCheck(([aDb executeUpdate:@"insert into easy (a) values (?)", @"hi"])); + + // just for fun. + FMResultSet *rs2 = [aDb executeQuery:@"select * from easy"]; + FMDBQuickCheck([rs2 next]); + while ([rs2 next]) { ; } // whatevers. + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); + }]; + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + + + { + + [dbPool inDatabase:^(FMDatabase *db) { + + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; + + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); + }]; + } + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + + [dbPool setMaximumNumberOfDatabasesToCreate:2]; + + + [dbPool inDatabase:^(FMDatabase *db) { + [dbPool inDatabase:^(FMDatabase *db2) { + [dbPool inDatabase:^(FMDatabase *db3) { + FMDBQuickCheck([dbPool countOfOpenDatabases] == 2); + FMDBQuickCheck(!db3); + }]; + + }]; + }]; + + [dbPool setMaximumNumberOfDatabasesToCreate:0]; + + [dbPool releaseAllDatabases]; + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 0); + + [dbPool inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; + }]; + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + + + [dbPool inTransaction:^(FMDatabase *adb, BOOL *rollback) { + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1001]]; + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1002]]; + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1003]]; + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 0); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 1); + }]; + + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 1); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 0); + + + [dbPool inDatabase:^(FMDatabase *db) { + FMResultSet *rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1001]]; + FMDBQuickCheck([rs2 next]); + FMDBQuickCheck(![rs2 next]); + }]; + + + + [dbPool inDeferredTransaction:^(FMDatabase *adb, BOOL *rollback) { + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1004]]; + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1005]]; + + *rollback = YES; + }]; + + FMDBQuickCheck([dbPool countOfOpenDatabases] == 1); + FMDBQuickCheck([dbPool countOfCheckedInDatabases] == 1); + FMDBQuickCheck([dbPool countOfCheckedOutDatabases] == 0); + + NSError *err = [dbPool inSavePoint:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1006]]; + }]; + + FMDBQuickCheck(!err); + + { + + err = [dbPool inSavePoint:^(FMDatabase *adb, BOOL *rollback) { + FMDBQuickCheck(![adb hadError]); + [adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1009]]; + + [adb inSavePoint:^(BOOL *arollback) { + FMDBQuickCheck(([adb executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:1010]])); + *arollback = YES; + }]; + }]; + + + FMDBQuickCheck(!err); + + [dbPool inDatabase:^(FMDatabase *db) { + + + FMResultSet *rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1009]]; + FMDBQuickCheck([rs2 next]); + FMDBQuickCheck(![rs2 next]); // close it out. + + rs2 = [db executeQuery:@"select * from easy where a = ?", [NSNumber numberWithInt:1010]]; + FMDBQuickCheck(![rs2 next]); + }]; + + + } + + { + + [dbPool inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"create table likefoo (foo text)"]; + [db executeUpdate:@"insert into likefoo values ('hi')"]; + [db executeUpdate:@"insert into likefoo values ('hello')"]; + [db executeUpdate:@"insert into likefoo values ('not')"]; + + int count = 0; + FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; + while ([rsl next]) { + count++; + } + + FMDBQuickCheck(count == 2); + + count = 0; + rsl = [db executeQuery:@"select * from likefoo where foo like ?", @"h%"]; + while ([rsl next]) { + count++; + } + + FMDBQuickCheck(count == 2); + + }]; + } + + + { + + size_t ops = 128; + + dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(ops, dqueue, ^(size_t nby) { + + // just mix things up a bit for demonstration purposes. + if (nby % 2 == 1) { + + [NSThread sleepForTimeInterval:.1]; + } + + [dbPool inDatabase:^(FMDatabase *db) { + NSLog(@"Starting query %ld", nby); + + FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; + while ([rsl next]) { + if (nby % 3 == 1) { + [NSThread sleepForTimeInterval:.05]; + } + } + + NSLog(@"Ending query %ld", nby); + }]; + }); + + NSLog(@"Number of open databases after crazy gcd stuff: %ld", [dbPool countOfOpenDatabases]); + } + + FMDatabasePool *dbPool2 = [FMDatabasePool databasePoolWithPath:dbPath flags:SQLITE_OPEN_READONLY]; + + FMDBQuickCheck(dbPool2); + { + [dbPool2 inDatabase:^(FMDatabase *db2) { + FMResultSet *rs1 = [db2 executeQuery:@"SELECT * FROM test"]; + FMDBQuickCheck(rs1 != nil); + [rs1 close]; + + BOOL ok = [db2 executeUpdate:@"insert into easy values (?)", [NSNumber numberWithInt:3]]; + FMDBQuickCheck(!ok); + }]; + } + + + // if you want to see a deadlock, just uncomment this line and run: + //#define ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD 1 +#ifdef ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD + { + + int ops = 16; + + dispatch_queue_t dqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(ops, dqueue, ^(size_t nby) { + + // just mix things up a bit for demonstration purposes. + if (nby % 2 == 1) { + [NSThread sleepForTimeInterval:.1]; + + [dbPool inTransaction:^(FMDatabase *db, BOOL *rollback) { + NSLog(@"Starting query %ld", nby); + + FMResultSet *rsl = [db executeQuery:@"select * from likefoo where foo like 'h%'"]; + while ([rsl next]) { + ;// whatever. + } + + NSLog(@"Ending query %ld", nby); + }]; + + } + + if (nby % 3 == 1) { + [NSThread sleepForTimeInterval:.1]; + } + + [dbPool inTransaction:^(FMDatabase *db, BOOL *rollback) { + NSLog(@"Starting update %ld", nby); + [db executeUpdate:@"insert into likefoo values ('1')"]; + [db executeUpdate:@"insert into likefoo values ('2')"]; + [db executeUpdate:@"insert into likefoo values ('3')"]; + NSLog(@"Ending update %ld", nby); + }]; + }); + + [dbPool releaseAllDatabases]; + + [dbPool inDatabase:^(FMDatabase *db) { + FMDBQuickCheck([db executeUpdate:@"insert into likefoo values ('1')"]); + }]; + } +#endif + +} + + +/* + Test the date format + */ + +void testOneDateFormat( FMDatabase *db, NSDate *testDate ) { + [db executeUpdate:@"DROP TABLE IF EXISTS test_format"]; + [db executeUpdate:@"CREATE TABLE test_format ( test TEXT )"]; + [db executeUpdate:@"INSERT INTO test_format(test) VALUES (?)", testDate]; + FMResultSet *rs = [db executeQuery:@"SELECT test FROM test_format"]; + if ([rs next]) { + NSDate *found = [rs dateForColumnIndex:0]; + if (NSOrderedSame != [testDate compare:found]) { + NSLog(@"Did not get back what we stored."); + } + } + else { + NSLog(@"Insertion borked"); + } + [rs close]; +} + +void testDateFormat() { + + FMDatabase *db = [FMDatabase databaseWithPath:nil]; // use in-memory DB + [db open]; + + NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; + + NSDate *testDate = [fmt dateFromString:@"2013-02-20 12:00:00"]; + + // test timestamp dates (ensuring our change does not break those) + testOneDateFormat(db,testDate); + + // now test the string-based timestamp + [db setDateFormat:fmt]; + testOneDateFormat(db, testDate); + + [db close]; +} + + +/* + What is this function for? Think of it as a template which a developer can use + to report bugs. + + If you have a bug, make it reproduce in this function and then let the + developer(s) know either via the github bug reporter or the mailing list. + */ + +void FMDBReportABugFunction() { + + NSString *dbPath = @"/tmp/bugreportsample.db"; + + // delete the old db if it exists + NSFileManager *fileManager = [NSFileManager defaultManager]; + [fileManager removeItemAtPath:dbPath error:nil]; + + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbPath]; + + [queue inDatabase:^(FMDatabase *db) { + + /* + Change the contents of this block to suit your needs. + */ + + BOOL worked = [db executeUpdate:@"create table test (a text, b text, c integer, d double, e double)"]; + FMDBQuickCheck(worked); + + + worked = [db executeUpdate:@"insert into test values ('a', 'b', 1, 2.2, 2.3)"]; + FMDBQuickCheck(worked); + + FMResultSet *rs = [db executeQuery:@"select * from test"]; + FMDBQuickCheck([rs next]); + [rs close]; + + }]; + + + [queue close]; + + + // uncomment the following line if you don't want to run through all the other tests. + //exit(0); + +} + + + + +