Browse Source

FMDB move.

v1.4.1
Abhishek Banthia 8 years ago
parent
commit
3222ad72a5
  1. 134
      Clocker.xcodeproj/project.pbxproj
  2. BIN
      Clocker.xcodeproj/project.xcworkspace/xcuserdata/abhishekbanthia.xcuserdatad/UserInterfaceState.xcuserstate
  3. 2
      Clocker/Appearance Tab/CLAppearanceViewController.m
  4. 135
      Clocker/ApplicationDelegate.m
  5. 8
      Clocker/FMDB/.gitignore
  6. 28
      Clocker/FMDB/LICENSE.txt
  7. 437
      Clocker/FMDB/README.markdown
  8. 24
      Clocker/FMDB/Tests/FMDBTempDBTests.h
  9. 63
      Clocker/FMDB/Tests/FMDBTempDBTests.m
  10. 132
      Clocker/FMDB/Tests/FMDatabaseAdditionsTests.m
  11. 157
      Clocker/FMDB/Tests/FMDatabaseFTS3Tests.m
  12. 83
      Clocker/FMDB/Tests/FMDatabaseFTS3WithModuleNameTests.m
  13. 303
      Clocker/FMDB/Tests/FMDatabasePoolTests.m
  14. 182
      Clocker/FMDB/Tests/FMDatabaseQueueTests.m
  15. 1183
      Clocker/FMDB/Tests/FMDatabaseTests.m
  16. 97
      Clocker/FMDB/Tests/FMResultSetTests.m
  17. 83
      Clocker/FMDB/Tests/Schemes/Tests.xcscheme
  18. 22
      Clocker/FMDB/Tests/Tests-Info.plist
  19. 11
      Clocker/FMDB/Tests/Tests-Prefix.pch
  20. 2
      Clocker/FMDB/Tests/en.lproj/InfoPlist.strings
  21. 79
      Clocker/FMDB/fmdb.1
  22. 1218
      Clocker/FMDB/fmdb.xcodeproj/project.pbxproj
  23. 80
      Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB MacOS.xcscheme
  24. 80
      Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB iOS.xcscheme
  25. 26
      Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.h
  26. 98
      Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m
  27. 117
      Clocker/FMDB/src/extra/Swift extensions/FMDatabaseAdditionsVariadic.swift
  28. 38
      Clocker/FMDB/src/extra/Swift extensions/FMDatabaseVariadic.swift
  29. 114
      Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.h
  30. 300
      Clocker/FMDB/src/extra/fts3/FMDatabase+FTS3.m
  31. 45
      Clocker/FMDB/src/extra/fts3/FMTokenizers.h
  32. 135
      Clocker/FMDB/src/extra/fts3/FMTokenizers.m
  33. 160
      Clocker/FMDB/src/extra/fts3/fts3_tokenizer.h
  34. 10
      Clocker/FMDB/src/fmdb/FMDB.h
  35. 1187
      Clocker/FMDB/src/fmdb/FMDatabase.h
  36. 1504
      Clocker/FMDB/src/fmdb/FMDatabase.m
  37. 278
      Clocker/FMDB/src/fmdb/FMDatabaseAdditions.h
  38. 246
      Clocker/FMDB/src/fmdb/FMDatabaseAdditions.m
  39. 225
      Clocker/FMDB/src/fmdb/FMDatabasePool.h
  40. 291
      Clocker/FMDB/src/fmdb/FMDatabasePool.m
  41. 191
      Clocker/FMDB/src/fmdb/FMDatabaseQueue.h
  42. 254
      Clocker/FMDB/src/fmdb/FMDatabaseQueue.m
  43. 468
      Clocker/FMDB/src/fmdb/FMResultSet.h
  44. 424
      Clocker/FMDB/src/fmdb/FMResultSet.m
  45. 26
      Clocker/FMDB/src/fmdb/Info.plist
  46. 7
      Clocker/FMDB/src/sample/fmdb_Prefix.pch
  47. 1538
      Clocker/FMDB/src/sample/main.m

134
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 = "<group>"; };
9A5951FC1C1D592D009C17AA /* iVersion.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; name = iVersion.bundle; path = "Clocker/Updated Version/iVersion.bundle"; sourceTree = "<group>"; };
9A5B1A8D1BECDFB700A77C68 /* Clocker.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = Clocker.entitlements; path = Clocker/Clocker.entitlements; sourceTree = "<group>"; };
9A5B3D391E3C3588006E8DD2 /* MoLoginItem.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MoLoginItem.framework; path = Frameworks/MoLoginItem.framework; sourceTree = "<group>"; };
9A5B6C6C1D3DF6E4000EAAF1 /* CLParentViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CLParentViewController.h; path = Clocker/CLParentViewController.h; sourceTree = "<group>"; };
9A5B6C6D1D3DF6E4000EAAF1 /* CLParentViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CLParentViewController.m; path = Clocker/CLParentViewController.m; sourceTree = "<group>"; };
9A5B6C6F1D4087A5000EAAF1 /* NSString+CLStringAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+CLStringAdditions.h"; path = "Clocker/Utilities/NSString+CLStringAdditions.h"; sourceTree = "<group>"; };
@ -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 = "<group>"; };
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 = "<group>"; };
9AF9A1691C250AB300EE7C2A /* Reachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Reachability.h; path = Clocker/Reachability/Reachability.h; sourceTree = "<group>"; };
9AF9A16A1C250AB300EE7C2A /* Reachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Reachability.m; path = Clocker/Reachability/Reachability.m; sourceTree = "<group>"; };
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 = "<group>";
};
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 = "<group>";
};
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";

BIN
Clocker.xcodeproj/project.xcworkspace/xcuserdata/abhishekbanthia.xcuserdatad/UserInterfaceState.xcuserstate generated

Binary file not shown.

2
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"}];
}

135
Clocker/ApplicationDelegate.m

@ -32,6 +32,10 @@
#import "CommonStrings.h"
#import "iVersion.h"
#import "CLOnboardingWindowController.h"
#import <FMDB/FMDB.h>
#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)
{

8
Clocker/FMDB/.gitignore vendored

@ -0,0 +1,8 @@
.DS_Store
build
*.xcodeproj/*.pbxuser
*.xcodeproj/*.perspectivev3
*.xcodeproj/xcuserdata
fmdb.xcodeproj/*.mode1v3
*.xcodeproj/project.xcworkspace/xcuserdata/
fmdb.xcodeproj/project.xcworkspace

28
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.

437
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).
<h2 id="threads">Using FMDatabaseQueue and Thread Safety.</h2>
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.)

24
Clocker/FMDB/Tests/FMDBTempDBTests.h

@ -0,0 +1,24 @@
//
// FMDBTempDBTests.h
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
#import "FMDatabase.h"
@protocol FMDBTempDBTests <NSObject>
@optional
+ (void)populateDatabase:(FMDatabase *)database;
@end
@interface FMDBTempDBTests : XCTestCase <FMDBTempDBTests>
@property FMDatabase *db;
@property (readonly) NSString *databasePath;
@end

63
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

132
Clocker/FMDB/Tests/FMDatabaseAdditionsTests.m

@ -0,0 +1,132 @@
//
// FMDatabaseAdditionsTests.m
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
#import "FMDatabaseAdditions.h"
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

157
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 <FMTokenizerDelegate>
+ (instancetype)tokenizerWithBaseTokenizer:(id<FMTokenizerDelegate>)tokenizer;
@property (nonatomic, strong) id<FMTokenizerDelegate> m_baseTokenizer;
@end
static id<FMTokenizerDelegate> g_simpleTok = nil;
static id<FMTokenizerDelegate> 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<FMTokenizerDelegate>)tokenizer
{
return [[self alloc] initWithBaseTokenizer:tokenizer];
}
- (instancetype)initWithBaseTokenizer:(id<FMTokenizerDelegate>)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

83
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<FMTokenizerDelegate> 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

303
Clocker/FMDB/Tests/FMDatabasePoolTests.m

@ -0,0 +1,303 @@
//
// FMDatabasePoolTests.m
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
@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

182
Clocker/FMDB/Tests/FMDatabaseQueueTests.m

@ -0,0 +1,182 @@
//
// FMDatabaseQueueTests.m
// fmdb
//
// Created by Graham Dennis on 24/11/2013.
//
//
#import <XCTest/XCTest.h>
#import "FMDatabaseQueue.h"
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

1183
Clocker/FMDB/Tests/FMDatabaseTests.m

File diff suppressed because it is too large Load Diff

97
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 <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

83
Clocker/FMDB/Tests/Schemes/Tests.xcscheme

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0500"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EE4290EE12B42F870088BD94"
BuildableName = "libFMDB.a"
BlueprintName = "FMDB"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5D041518416BB2008C5AA9"
BuildableName = "Tests.xctest"
BlueprintName = "Tests"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

22
Clocker/FMDB/Tests/Tests-Info.plist

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

11
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 <Cocoa/Cocoa.h>
#import <XCTest/XCTest.h>
#import "FMDBTempDBTests.h"
#endif

2
Clocker/FMDB/Tests/en.lproj/InfoPlist.strings

@ -0,0 +1,2 @@
/* Localized versions of Info.plist keys */

79
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

1218
Clocker/FMDB/fmdb.xcodeproj/project.pbxproj

File diff suppressed because it is too large Load Diff

80
Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB MacOS.xcscheme

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0810"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83C73F0A1C326ADA00FFC730"
BuildableName = "FMDB.framework"
BlueprintName = "FMDB MacOS"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83C73F0A1C326ADA00FFC730"
BuildableName = "FMDB.framework"
BlueprintName = "FMDB MacOS"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83C73F0A1C326ADA00FFC730"
BuildableName = "FMDB.framework"
BlueprintName = "FMDB MacOS"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

80
Clocker/FMDB/fmdb.xcodeproj/xcshareddata/xcschemes/FMDB iOS.xcscheme

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0810"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83C73EFD1C326AB000FFC730"
BuildableName = "FMDB.framework"
BlueprintName = "FMDB iOS"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83C73EFD1C326AB000FFC730"
BuildableName = "FMDB.framework"
BlueprintName = "FMDB iOS"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "83C73EFD1C326AB000FFC730"
BuildableName = "FMDB.framework"
BlueprintName = "FMDB iOS"
ReferencedContainer = "container:fmdb.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

26
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

98
Clocker/FMDB/src/extra/InMemoryOnDiskIO/FMDatabase+InMemoryOnDiskIO.m

@ -0,0 +1,98 @@
#import "FMDatabase+InMemoryOnDiskIO.h"
#import <sqlite3.h>
// 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

117
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<T>(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) }
}
}

38
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]);
}
}

114
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 <FMDB/FMDatabase.h>
/**
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<FMTokenizerDelegate>)tokenizer;
/**
Register a delegate implementation in the global table. The key should be used
as a parameter when creating the table.
*/
+ (void)registerTokenizer:(id<FMTokenizerDelegate>)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

300
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<FMTokenizerDelegate> __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<FMTokenizerDelegate>)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<FMTokenizerDelegate>)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

45
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 <Foundation/Foundation.h>
#import "FMDatabase+FTS3.h"
/**
This is the base tokenizer implementation, using a CFStringTokenizer to find words.
*/
@interface FMSimpleTokenizer : NSObject <FMTokenizerDelegate>
/**
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 <FMTokenizerDelegate>
@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<FMTokenizerDelegate>)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<FMTokenizerDelegate>)tokenizer;
@end

135
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<FMTokenizerDelegate> m_baseTokenizer;
}
@synthesize words = m_words;
+ (instancetype)tokenizerWithFileURL:(NSURL *)wordFileURL
baseTokenizer:(id<FMTokenizerDelegate>)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<FMTokenizerDelegate>)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

160
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 <tokenizer-name> 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_ */

10
Clocker/FMDB/src/fmdb/FMDB.h

@ -0,0 +1,10 @@
#import <Foundation/Foundation.h>
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"

1187
Clocker/FMDB/src/fmdb/FMDatabase.h

File diff suppressed because it is too large Load Diff

1504
Clocker/FMDB/src/fmdb/FMDatabase.m

File diff suppressed because it is too large Load Diff

278
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 <Foundation/Foundation.h>
#import "FMDatabase.h"
/** Category of additions for `<FMDatabase>` class.
### See also
- `<FMDatabase>`
*/
@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 `<columnExists:inTableWithName:>` 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

246
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 <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

225
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 <Foundation/Foundation.h>
@class FMDatabase;
/** Pool of `<FMDatabase>` objects.
### See also
- `<FMDatabaseQueue>`
- `<FMDatabase>`
@warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` 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

291
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 <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

191
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 <Foundation/Foundation.h>
@class FMDatabase;
/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`.
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.
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
- `<FMDatabase>`
@warning Do not instantiate a single `<FMDatabase>` 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

254
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 <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

468
Clocker/FMDB/src/fmdb/FMResultSet.h

@ -0,0 +1,468 @@
#import <Foundation/Foundation.h>
#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 `<FMDatabase>`.
### See also
- `<FMDatabase>`
*/
@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 `<FMStatement>`
@param statement A `<FMStatement>` to be performed
@param aDB A `<FMDatabase>` 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 `<next>` succeed in retrieving another row?
@return `YES` if the last call to `<next>` succeeded in retrieving another record; `NO` if not.
@see next
@warning The `hasAnotherRow` method must follow a call to `<next>`. 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 `<dataForColumn:>`/`<dataForColumnIndex:>`)
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 `<dataForColumn:>`/`<dataForColumnIndex:>`)
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 `<resultDictionary>` instead. Also, beware that `<resultDictionary>` 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

424
Clocker/FMDB/src/fmdb/FMResultSet.m

@ -0,0 +1,424 @@
#import "FMResultSet.h"
#import "FMDatabase.h"
#import "unistd.h"
#if FMDB_SQLITE_STANDALONE
#import <sqlite3/sqlite3.h>
#else
#import <sqlite3.h>
#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

26
Clocker/FMDB/src/fmdb/Info.plist

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.6.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>

7
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 <Foundation/Foundation.h>
#endif

1538
Clocker/FMDB/src/sample/main.m

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save