diff --git a/Example/.gitignore b/Example/.gitignore new file mode 100644 index 0000000..bd1a02d --- /dev/null +++ b/Example/.gitignore @@ -0,0 +1,30 @@ +### Unity ### +[Ll]ibrary/ +/[Tt]emp/ +[Oo]bj/ +/[Bb]uild/ +[Bb]in/ +ProjectSettings/ + +# Autogenerated VS/MD solution and project files +*.csproj +*.unityproj +*.sln +*.suo +*.tmp +*.user +*.userprefs +*.pidb +*.booproj + +# Unity3D generated meta files +*.pidb.meta + +# Unity3D Generated File On Crash Reports +sysinfo.txt + +# Unity3d Generated files when building +*.pfx +*.pfx.meta +UWP/ +!Assets/Plugin/**/*.dll \ No newline at end of file diff --git a/Example_unity5/Assets/Plugins.meta b/Example/Assets/Plugins.meta similarity index 67% rename from Example_unity5/Assets/Plugins.meta rename to Example/Assets/Plugins.meta index 6a537b8..1ef7e1f 100644 --- a/Example_unity5/Assets/Plugins.meta +++ b/Example/Assets/Plugins.meta @@ -1,7 +1,7 @@ fileFormatVersion: 2 -guid: bc89bc61e2dc66d46aae1056255cf946 +guid: 6672b8bdaedd568468bd6e5a724edba2 folderAsset: yes -timeCreated: 1445131378 +timeCreated: 1453576960 licenseType: Free DefaultImporter: userData: diff --git a/Example_unity5/Assets/Plugins/Android.meta b/Example/Assets/Plugins/Android.meta similarity index 100% rename from Example_unity5/Assets/Plugins/Android.meta rename to Example/Assets/Plugins/Android.meta diff --git a/Example_unity5/Assets/Plugins/Android/libs.meta b/Example/Assets/Plugins/Android/libs.meta similarity index 100% rename from Example_unity5/Assets/Plugins/Android/libs.meta rename to Example/Assets/Plugins/Android/libs.meta diff --git a/Example/Assets/Plugins/Android/libs/arm64-v8a/libsqlite3.so b/Example/Assets/Plugins/Android/libs/arm64-v8a/libsqlite3.so new file mode 100644 index 0000000..1e2ce2d Binary files /dev/null and b/Example/Assets/Plugins/Android/libs/arm64-v8a/libsqlite3.so differ diff --git a/Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a.meta b/Example/Assets/Plugins/Android/libs/armeabi-v7a.meta similarity index 100% rename from Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a.meta rename to Example/Assets/Plugins/Android/libs/armeabi-v7a.meta diff --git a/Example/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so b/Example/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so new file mode 100644 index 0000000..2c6e2bf Binary files /dev/null and b/Example/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so differ diff --git a/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta b/Example/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta similarity index 100% rename from Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta rename to Example/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta diff --git a/Example_unity5/Assets/Plugins/Android/libs/x86.meta b/Example/Assets/Plugins/Android/libs/x86.meta similarity index 100% rename from Example_unity5/Assets/Plugins/Android/libs/x86.meta rename to Example/Assets/Plugins/Android/libs/x86.meta diff --git a/Example/Assets/Plugins/Android/libs/x86/libsqlite3.so b/Example/Assets/Plugins/Android/libs/x86/libsqlite3.so new file mode 100644 index 0000000..9d08844 Binary files /dev/null and b/Example/Assets/Plugins/Android/libs/x86/libsqlite3.so differ diff --git a/Example_unity5/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta b/Example/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta similarity index 100% rename from Example_unity5/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta rename to Example/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta diff --git a/Example_unity5/Assets/Plugins/WP8.meta b/Example/Assets/Plugins/WSA.meta similarity index 57% rename from Example_unity5/Assets/Plugins/WP8.meta rename to Example/Assets/Plugins/WSA.meta index dceb419..474c5be 100644 --- a/Example_unity5/Assets/Plugins/WP8.meta +++ b/Example/Assets/Plugins/WSA.meta @@ -1,8 +1,8 @@ fileFormatVersion: 2 -guid: c333c2b657470c94d9fc5d92a639393d +guid: 3e1310ff5b122f347a943bad24333d4f folderAsset: yes -timeCreated: 1445131378 -licenseType: Free +timeCreated: 1507670483 +licenseType: Pro DefaultImporter: userData: assetBundleName: diff --git a/Example_unity5/Assets/Plugins/WP8/ARM.meta b/Example/Assets/Plugins/WSA/ARM.meta similarity index 57% rename from Example_unity5/Assets/Plugins/WP8/ARM.meta rename to Example/Assets/Plugins/WSA/ARM.meta index 770d44a..925ac45 100644 --- a/Example_unity5/Assets/Plugins/WP8/ARM.meta +++ b/Example/Assets/Plugins/WSA/ARM.meta @@ -1,8 +1,8 @@ fileFormatVersion: 2 -guid: 9e182245f94284645b5ea2d1d93d5aab +guid: d5a4eb770a3e85941bd12132039ab956 folderAsset: yes -timeCreated: 1445131378 -licenseType: Free +timeCreated: 1507670500 +licenseType: Pro DefaultImporter: userData: assetBundleName: diff --git a/Example/Assets/Plugins/WSA/ARM/sqlite3.dll b/Example/Assets/Plugins/WSA/ARM/sqlite3.dll new file mode 100644 index 0000000..53aea09 Binary files /dev/null and b/Example/Assets/Plugins/WSA/ARM/sqlite3.dll differ diff --git a/Example/Assets/Plugins/WSA/ARM/sqlite3.dll.meta b/Example/Assets/Plugins/WSA/ARM/sqlite3.dll.meta new file mode 100644 index 0000000..af757b5 --- /dev/null +++ b/Example/Assets/Plugins/WSA/ARM/sqlite3.dll.meta @@ -0,0 +1,126 @@ +fileFormatVersion: 2 +guid: 0268b9f97df6a83468be4b296cf6af28 +timeCreated: 1507670500 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 0 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 1 + settings: + CPU: ARM + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + userData: + assetBundleName: + assetBundleVariant: diff --git a/Example/Assets/Plugins/WSA/x64.meta b/Example/Assets/Plugins/WSA/x64.meta new file mode 100644 index 0000000..83b0b9d --- /dev/null +++ b/Example/Assets/Plugins/WSA/x64.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e14810dc75ddd4e4f9bb7b92989cb58b +folderAsset: yes +timeCreated: 1507670500 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Example/Assets/Plugins/WSA/x64/sqlite3.dll b/Example/Assets/Plugins/WSA/x64/sqlite3.dll new file mode 100644 index 0000000..63096c1 Binary files /dev/null and b/Example/Assets/Plugins/WSA/x64/sqlite3.dll differ diff --git a/Example/Assets/Plugins/WSA/x64/sqlite3.dll.meta b/Example/Assets/Plugins/WSA/x64/sqlite3.dll.meta new file mode 100644 index 0000000..51ab767 --- /dev/null +++ b/Example/Assets/Plugins/WSA/x64/sqlite3.dll.meta @@ -0,0 +1,126 @@ +fileFormatVersion: 2 +guid: 1e46d058e8bdac745970fdfabe7e67ce +timeCreated: 1507670500 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 0 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 1 + settings: + CPU: X64 + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + userData: + assetBundleName: + assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/x86.meta b/Example/Assets/Plugins/WSA/x86.meta similarity index 57% rename from Example_unity5/Assets/Plugins/WP8/x86.meta rename to Example/Assets/Plugins/WSA/x86.meta index 2193627..7587a2b 100644 --- a/Example_unity5/Assets/Plugins/WP8/x86.meta +++ b/Example/Assets/Plugins/WSA/x86.meta @@ -1,8 +1,8 @@ fileFormatVersion: 2 -guid: 730307c32c78a1d47af69464cf2fc372 +guid: 9f579691124bfd24a81afafa4c8a09c1 folderAsset: yes -timeCreated: 1445131378 -licenseType: Free +timeCreated: 1507670500 +licenseType: Pro DefaultImporter: userData: assetBundleName: diff --git a/Example/Assets/Plugins/WSA/x86/sqlite3.dll b/Example/Assets/Plugins/WSA/x86/sqlite3.dll new file mode 100644 index 0000000..6667321 Binary files /dev/null and b/Example/Assets/Plugins/WSA/x86/sqlite3.dll differ diff --git a/Example/Assets/Plugins/WSA/x86/sqlite3.dll.meta b/Example/Assets/Plugins/WSA/x86/sqlite3.dll.meta new file mode 100644 index 0000000..963467f --- /dev/null +++ b/Example/Assets/Plugins/WSA/x86/sqlite3.dll.meta @@ -0,0 +1,126 @@ +fileFormatVersion: 2 +guid: a0bb909f5b8441e48a1632aef3d543a4 +timeCreated: 1507670500 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 0 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 1 + settings: + CPU: X86 + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + userData: + assetBundleName: + assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/x64.meta b/Example/Assets/Plugins/x64.meta similarity index 100% rename from Example_unity5/Assets/Plugins/x64.meta rename to Example/Assets/Plugins/x64.meta diff --git a/Example_unity4x/Assets/Plugins/iOS/x64/sqlite3.dll b/Example/Assets/Plugins/x64/sqlite3.dll old mode 100644 new mode 100755 similarity index 100% rename from Example_unity4x/Assets/Plugins/iOS/x64/sqlite3.dll rename to Example/Assets/Plugins/x64/sqlite3.dll diff --git a/Example/Assets/Plugins/x64/sqlite3.dll.meta b/Example/Assets/Plugins/x64/sqlite3.dll.meta new file mode 100644 index 0000000..e30f156 --- /dev/null +++ b/Example/Assets/Plugins/x64/sqlite3.dll.meta @@ -0,0 +1,75 @@ +fileFormatVersion: 2 +guid: a3fee75616c5ab0449e841e6fc8a5172 +timeCreated: 1445131383 +licenseType: Free +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 0 + settings: + CPU: AnyCPU + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: AnyOS + Linux: + enabled: 1 + settings: + CPU: None + Linux64: + enabled: 1 + settings: + CPU: x86_64 + LinuxUniversal: + enabled: 1 + settings: + CPU: AnyCPU + OSXIntel: + enabled: 1 + settings: + CPU: None + OSXIntel64: + enabled: 1 + settings: + CPU: AnyCPU + OSXUniversal: + enabled: 1 + settings: + CPU: AnyCPU + SamsungTV: + enabled: 0 + settings: + STV_MODEL: STANDARD_13 + Win: + enabled: 1 + settings: + CPU: None + Win64: + enabled: 1 + settings: + CPU: AnyCPU + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + iOS: + enabled: 1 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/x86.meta b/Example/Assets/Plugins/x86.meta similarity index 100% rename from Example_unity5/Assets/Plugins/x86.meta rename to Example/Assets/Plugins/x86.meta diff --git a/Example/Assets/Plugins/x86/sqlite3.dll b/Example/Assets/Plugins/x86/sqlite3.dll new file mode 100755 index 0000000..d48a7ef Binary files /dev/null and b/Example/Assets/Plugins/x86/sqlite3.dll differ diff --git a/Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta b/Example/Assets/Plugins/x86/sqlite3.dll.meta similarity index 76% rename from Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta rename to Example/Assets/Plugins/x86/sqlite3.dll.meta index db7f4be..67dc6cd 100644 --- a/Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so.meta +++ b/Example/Assets/Plugins/x86/sqlite3.dll.meta @@ -1,5 +1,7 @@ fileFormatVersion: 2 -guid: a00620409803a41f598cabed0c2ecf9f +guid: 34afd3dfc3051f3438965ecf7bd8c8df +timeCreated: 1445131383 +licenseType: Free PluginImporter: serializedVersion: 1 iconMap: {} @@ -7,16 +9,16 @@ PluginImporter: isPreloaded: 0 platformData: Android: - enabled: 1 + enabled: 0 settings: - CPU: ARMv7 + CPU: AnyCPU Any: enabled: 0 settings: {} Editor: enabled: 0 settings: - CPU: AnyCPU + CPU: x86 DefaultValueInitialized: true OS: AnyOS Linux: @@ -26,7 +28,11 @@ PluginImporter: Linux64: enabled: 0 settings: - CPU: x86_64 + CPU: None + LinuxUniversal: + enabled: 0 + settings: + CPU: None OSXIntel: enabled: 0 settings: @@ -34,17 +40,15 @@ PluginImporter: OSXIntel64: enabled: 0 settings: - CPU: AnyCPU - SamsungTV: + CPU: None + OSXUniversal: enabled: 0 settings: - STV_MODEL: STANDARD_13 - WP8: + CPU: None + SamsungTV: enabled: 0 settings: - CPU: AnyCPU - DontProcess: False - PlaceholderPath: + STV_MODEL: STANDARD_13 Win: enabled: 0 settings: @@ -52,7 +56,7 @@ PluginImporter: Win64: enabled: 0 settings: - CPU: AnyCPU + CPU: None WindowsStoreApps: enabled: 0 settings: @@ -60,6 +64,7 @@ PluginImporter: DontProcess: False PlaceholderPath: SDK: AnySDK + ScriptingBackend: AnyScriptingBackend iOS: enabled: 0 settings: diff --git a/Example_unity5/Assets/Scenes.meta b/Example/Assets/Scenes.meta similarity index 67% rename from Example_unity5/Assets/Scenes.meta rename to Example/Assets/Scenes.meta index 003b019..df90c30 100644 --- a/Example_unity5/Assets/Scenes.meta +++ b/Example/Assets/Scenes.meta @@ -1,7 +1,7 @@ fileFormatVersion: 2 -guid: 3ad83ecfc4b5e2a4783139ed0e77b957 +guid: b8ab4eabea1d94b49808216caa3ed5d0 folderAsset: yes -timeCreated: 1445131378 +timeCreated: 1453576960 licenseType: Free DefaultImporter: userData: diff --git a/Example_unity5/Assets/Scenes/CreateDBFromScript.unity b/Example/Assets/Scenes/CreateDBFromScript.unity similarity index 100% rename from Example_unity5/Assets/Scenes/CreateDBFromScript.unity rename to Example/Assets/Scenes/CreateDBFromScript.unity diff --git a/Example_unity5/Assets/Scenes/CreateDBFromScript.unity.meta b/Example/Assets/Scenes/CreateDBFromScript.unity.meta similarity index 100% rename from Example_unity5/Assets/Scenes/CreateDBFromScript.unity.meta rename to Example/Assets/Scenes/CreateDBFromScript.unity.meta diff --git a/Example_unity5/Assets/Scenes/ExistingDBScript.unity b/Example/Assets/Scenes/ExistingDBScript.unity similarity index 57% rename from Example_unity5/Assets/Scenes/ExistingDBScript.unity rename to Example/Assets/Scenes/ExistingDBScript.unity index 1bc3bda..565fc47 100644 Binary files a/Example_unity5/Assets/Scenes/ExistingDBScript.unity and b/Example/Assets/Scenes/ExistingDBScript.unity differ diff --git a/Example_unity5/Assets/Scenes/ExistingDBScript.unity.meta b/Example/Assets/Scenes/ExistingDBScript.unity.meta similarity index 100% rename from Example_unity5/Assets/Scenes/ExistingDBScript.unity.meta rename to Example/Assets/Scenes/ExistingDBScript.unity.meta diff --git a/Example_unity5/Assets/Scripts.meta b/Example/Assets/Scripts.meta similarity index 67% rename from Example_unity5/Assets/Scripts.meta rename to Example/Assets/Scripts.meta index 7812f69..314d30e 100644 --- a/Example_unity5/Assets/Scripts.meta +++ b/Example/Assets/Scripts.meta @@ -1,7 +1,7 @@ fileFormatVersion: 2 -guid: 3679c41ee95457c4caa539f1340f715b +guid: 817994a91ac197e42baaef83a9db4e19 folderAsset: yes -timeCreated: 1445131378 +timeCreated: 1453576960 licenseType: Free DefaultImporter: userData: diff --git a/Example_unity5/Assets/Scripts/CreateDBScript.cs b/Example/Assets/Scripts/CreateDBScript.cs similarity index 100% rename from Example_unity5/Assets/Scripts/CreateDBScript.cs rename to Example/Assets/Scripts/CreateDBScript.cs diff --git a/Example_unity5/Assets/Scripts/CreateDBScript.cs.meta b/Example/Assets/Scripts/CreateDBScript.cs.meta similarity index 100% rename from Example_unity5/Assets/Scripts/CreateDBScript.cs.meta rename to Example/Assets/Scripts/CreateDBScript.cs.meta diff --git a/Example_unity5/Assets/Scripts/DataService.cs b/Example/Assets/Scripts/DataService.cs similarity index 81% rename from Example_unity5/Assets/Scripts/DataService.cs rename to Example/Assets/Scripts/DataService.cs index c287dda..558ada1 100644 --- a/Example_unity5/Assets/Scripts/DataService.cs +++ b/Example/Assets/Scripts/DataService.cs @@ -39,9 +39,19 @@ public DataService(string DatabaseName){ File.Copy(loadDb, filepath); #elif UNITY_WINRT - var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS - // then save to Application.persistentDataPath - File.Copy(loadDb, filepath); + var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS + // then save to Application.persistentDataPath + File.Copy(loadDb, filepath); + +#elif UNITY_STANDALONE_OSX + var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS + // then save to Application.persistentDataPath + File.Copy(loadDb, filepath); +#else + var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS + // then save to Application.persistentDataPath + File.Copy(loadDb, filepath); + #endif Debug.Log("Database written"); diff --git a/Example_unity5/Assets/Scripts/DataService.cs.meta b/Example/Assets/Scripts/DataService.cs.meta similarity index 100% rename from Example_unity5/Assets/Scripts/DataService.cs.meta rename to Example/Assets/Scripts/DataService.cs.meta diff --git a/Example_unity5/Assets/Scripts/ExistingDBScript.cs b/Example/Assets/Scripts/ExistingDBScript.cs similarity index 100% rename from Example_unity5/Assets/Scripts/ExistingDBScript.cs rename to Example/Assets/Scripts/ExistingDBScript.cs diff --git a/Example_unity5/Assets/Scripts/ExistingDBScript.cs.meta b/Example/Assets/Scripts/ExistingDBScript.cs.meta similarity index 100% rename from Example_unity5/Assets/Scripts/ExistingDBScript.cs.meta rename to Example/Assets/Scripts/ExistingDBScript.cs.meta diff --git a/Example_unity5/Assets/Scripts/Person.cs b/Example/Assets/Scripts/Person.cs similarity index 100% rename from Example_unity5/Assets/Scripts/Person.cs rename to Example/Assets/Scripts/Person.cs diff --git a/Example_unity5/Assets/Scripts/Person.cs.meta b/Example/Assets/Scripts/Person.cs.meta similarity index 100% rename from Example_unity5/Assets/Scripts/Person.cs.meta rename to Example/Assets/Scripts/Person.cs.meta diff --git a/SQLite4Unity3d/SQLite4Unity3d/SQLite.cs b/Example/Assets/Scripts/SQLite.cs similarity index 87% rename from SQLite4Unity3d/SQLite4Unity3d/SQLite.cs rename to Example/Assets/Scripts/SQLite.cs index 098d53e..18ce6c3 100644 --- a/SQLite4Unity3d/SQLite4Unity3d/SQLite.cs +++ b/Example/Assets/Scripts/SQLite.cs @@ -109,16 +109,16 @@ public enum SQLiteOpenFlags { ProtectionNone = 0x00400000 } - [Flags] - public enum CreateFlags - { - None = 0, - ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName) - ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix) - AllImplicit = 3, // do both above + [Flags] + public enum CreateFlags + { + None = 0, + ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName) + ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix) + AllImplicit = 3, // do both above - AutoIncPK = 4 // force PK field to be auto inc - } + AutoIncPK = 4 // force PK field to be auto inc + } /// /// Represents an open connection to a SQLite database. @@ -130,7 +130,7 @@ public partial class SQLiteConnection : IDisposable private Dictionary _mappings = null; private Dictionary _tables = null; private System.Diagnostics.Stopwatch _sw; - private long _elapsedMilliseconds = 0; + private TimeSpan _elapsed = default(TimeSpan); private int _transactionDepth = 0; private Random _rand = new Random (); @@ -145,7 +145,7 @@ public partial class SQLiteConnection : IDisposable // To prevent database disruption, a database file must be accessed *synchronously*. // For the purpose we create synchronous objects for each database file and store in the // static dictionary to share it among all connections. - // The key of the dictionary is database file path and its value is an object to be used + // The key of the dictionary is database file path and its value is an object to be used // by lock() statement. // // Use case: @@ -155,11 +155,10 @@ public partial class SQLiteConnection : IDisposable // - RunInDatabaseLock(Action) similarly locks the database but no transaction (for query) private static Dictionary syncObjects = new Dictionary(); - public bool TimeExecution { get; set; } - #region debug tracing public bool Trace { get; set; } + public bool TimeExecution { get; set; } public delegate void TraceHandler (string message); public event TraceHandler TraceEvent; @@ -171,6 +170,16 @@ internal void InvokeTrace (string message) } } + public delegate void TimeExecutionHandler (TimeSpan executionTime, TimeSpan totalExecutionTime); + public event TimeExecutionHandler TimeExecutionEvent; + + internal void InvokeTimeExecution(TimeSpan executionTime, TimeSpan totalExecutionTime) + { + if (TimeExecutionEvent != null) { + TimeExecutionEvent(executionTime, totalExecutionTime); + } + } + #endregion public bool StoreDateTimeAsTicks { get; private set; } @@ -219,7 +228,7 @@ public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool st Sqlite3DatabaseHandle handle; #if SILVERLIGHT || USE_CSHARP_SQLITE - var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero); + var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero); #else // open using the byte[] // in the case where the path may include Unicode @@ -260,14 +269,14 @@ void mayCreateSyncObject(string databasePath) /// The sync object. public object SyncObject { get { return syncObjects[DatabasePath];} } - public void EnableLoadExtension(int onoff) - { - SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff); + public void EnableLoadExtension(int onoff) + { + SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff); if (r != SQLite3.Result.OK) { string msg = SQLite3.GetErrmsg (Handle); throw SQLiteException.New (r, msg); } - } + } static byte[] GetNullTerminatedUtf8 (string s) { @@ -315,14 +324,14 @@ public IEnumerable TableMappings { /// /// The type whose mapping to the database is returned. /// - /// + /// /// Optional flags allowing implicit PK and indexes based on naming conventions /// /// /// The mapping represents the schema of the columns of the database and contains /// methods to set and get properties of objects. /// - public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) + public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) { if (_mappings == null) { _mappings = new Dictionary (); @@ -394,11 +403,11 @@ public int CreateTable(CreateFlags createFlags = CreateFlags.None) /// later access this schema by calling GetMapping. /// /// Type to reflect to a database table. - /// Optional flags allowing implicit PK and indexes based on naming conventions. + /// Optional flags allowing implicit PK and indexes based on naming conventions. /// /// The number of entries added to the database schema. /// - public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) + public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) { if (_tables == null) { _tables = new Dictionary (); @@ -466,85 +475,85 @@ public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) return count; } - /// - /// Creates an index for the specified table and columns. - /// - /// Name of the index to create - /// Name of the database table - /// An array of column names to index - /// Whether the index should be unique - public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false) - { - const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; - var sql = String.Format(sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName); - return Execute(sql); - } - - /// - /// Creates an index for the specified table and column. - /// - /// Name of the index to create - /// Name of the database table - /// Name of the column to index - /// Whether the index should be unique - public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) - { - return CreateIndex(indexName, tableName, new string[] { columnName }, unique); - } - - /// - /// Creates an index for the specified table and column. - /// - /// Name of the database table - /// Name of the column to index - /// Whether the index should be unique - public int CreateIndex(string tableName, string columnName, bool unique = false) - { - return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique); - } - - /// - /// Creates an index for the specified table and columns. - /// - /// Name of the database table - /// An array of column names to index - /// Whether the index should be unique - public int CreateIndex(string tableName, string[] columnNames, bool unique = false) - { - return CreateIndex(tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique); - } - - /// - /// Creates an index for the specified object property. - /// e.g. CreateIndex(c => c.Name); - /// - /// Type to reflect to a database table. - /// Property to index - /// Whether the index should be unique - public void CreateIndex(Expression> property, bool unique = false) - { - MemberExpression mx; - if (property.Body.NodeType == ExpressionType.Convert) - { - mx = ((UnaryExpression)property.Body).Operand as MemberExpression; - } - else - { - mx= (property.Body as MemberExpression); - } - var propertyInfo = mx.Member as PropertyInfo; - if (propertyInfo == null) - { - throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); - } - - var propName = propertyInfo.Name; - - var map = GetMapping(); - var colName = map.FindColumnWithPropertyName(propName).Name; - - CreateIndex(map.TableName, colName, unique); - } + /// + /// Creates an index for the specified table and columns. + /// + /// Name of the index to create + /// Name of the database table + /// An array of column names to index + /// Whether the index should be unique + public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false) + { + const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; + var sql = String.Format(sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName); + return Execute(sql); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the index to create + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) + { + return CreateIndex(indexName, tableName, new string[] { columnName }, unique); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public int CreateIndex(string tableName, string columnName, bool unique = false) + { + return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique); + } + + /// + /// Creates an index for the specified table and columns. + /// + /// Name of the database table + /// An array of column names to index + /// Whether the index should be unique + public int CreateIndex(string tableName, string[] columnNames, bool unique = false) + { + return CreateIndex(tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique); + } + + /// + /// Creates an index for the specified object property. + /// e.g. CreateIndex(c => c.Name); + /// + /// Type to reflect to a database table. + /// Property to index + /// Whether the index should be unique + public void CreateIndex(Expression> property, bool unique = false) + { + MemberExpression mx; + if (property.Body.NodeType == ExpressionType.Convert) + { + mx = ((UnaryExpression)property.Body).Operand as MemberExpression; + } + else + { + mx= (property.Body as MemberExpression); + } + var propertyInfo = mx.Member as PropertyInfo; + if (propertyInfo == null) + { + throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); + } + + var propName = propertyInfo.Name; + + var map = GetMapping(); + var colName = map.FindColumnWithPropertyName(propName).Name; + + CreateIndex(map.TableName, colName, unique); + } public class ColumnInfo { @@ -666,8 +675,8 @@ public int Execute (string query, params object[] args) if (TimeExecution) { _sw.Stop (); - _elapsedMilliseconds += _sw.ElapsedMilliseconds; - Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); + _elapsed += _sw.Elapsed; + this.InvokeTimeExecution (_sw.Elapsed, _elapsed); } return r; @@ -689,8 +698,8 @@ public T ExecuteScalar (string query, params object[] args) if (TimeExecution) { _sw.Stop (); - _elapsedMilliseconds += _sw.ElapsedMilliseconds; - Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); + _elapsed += _sw.Elapsed; + this.InvokeTimeExecution (_sw.Elapsed, _elapsed); } return r; @@ -824,21 +833,21 @@ public IEnumerable DeferredQuery(TableMapping map, string query, params return Query (map.GetByPrimaryKeySql, pk).First (); } - /// - /// Attempts to retrieve the first object that matches the predicate from the table - /// associated with the specified type. - /// - /// - /// A predicate for which object to find. - /// - /// - /// The object that matches the given predicate. Throws a not found exception - /// if the object is not found. - /// - public T Get (Expression> predicate) where T : new() - { - return Table ().Where (predicate).First (); - } + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate. Throws a not found exception + /// if the object is not found. + /// + public T Get (Expression> predicate) where T : new() + { + return Table ().Where (predicate).First (); + } /// /// Attempts to retrieve an object with the given primary key from the table @@ -879,20 +888,20 @@ public object Find (object pk, TableMapping map) } /// - /// Attempts to retrieve the first object that matches the predicate from the table - /// associated with the specified type. - /// - /// - /// A predicate for which object to find. - /// - /// - /// The object that matches the given predicate or null - /// if the object is not found. - /// - public T Find (Expression> predicate) where T : new() - { - return Table ().Where (predicate).FirstOrDefault (); - } + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public T Find (Expression> predicate) where T : new() + { + return Table ().Where (predicate).FirstOrDefault (); + } /// /// Whether has been called and the database is waiting for a . @@ -1022,7 +1031,7 @@ void RollbackTo (string savepoint, bool noThrow) } catch (SQLiteException) { if (!noThrow) throw; - + } // No need to rollback if there are no transactions open. } @@ -1050,13 +1059,13 @@ void DoSavePointExecute (string savepoint, string cmd) // TODO: Mild race here, but inescapable without locking almost everywhere. if (0 <= depth && depth < _transactionDepth) { #if NETFX_CORE - Volatile.Write (ref _transactionDepth, depth); + Volatile.Write (ref _transactionDepth, depth); #elif SILVERLIGHT _transactionDepth = depth; #else - Thread.VolatileWrite (ref _transactionDepth, depth); + Thread.VolatileWrite (ref _transactionDepth, depth); #endif - Execute (cmd + savepoint); + Execute (cmd + savepoint); return; } } @@ -1278,63 +1287,63 @@ public int Insert (object obj, string extra) return Insert (obj, extra, obj.GetType ()); } - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, string extra, Type objType) + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, string extra, Type objType) { if (obj == null || objType == null) { return 0; } - + var map = GetMapping (objType); #if NETFX_CORE - if (map.PK != null && map.PK.IsAutoGuid) - { - // no GetProperty so search our way up the inheritance chain till we find it - PropertyInfo prop; - while (objType != null) - { - var info = objType.GetTypeInfo(); - prop = info.GetDeclaredProperty(map.PK.PropertyName); - if (prop != null) - { - if (prop.GetValue(obj, null).Equals(Guid.Empty)) - { - prop.SetValue(obj, Guid.NewGuid(), null); - } - break; - } - - objType = info.BaseType; - } - } + if (map.PK != null && map.PK.IsAutoGuid) + { + // no GetProperty so search our way up the inheritance chain till we find it + PropertyInfo prop; + while (objType != null) + { + var info = objType.GetTypeInfo(); + prop = info.GetDeclaredProperty(map.PK.PropertyName); + if (prop != null) + { + if (prop.GetValue(obj, null).Equals(Guid.Empty)) + { + prop.SetValue(obj, Guid.NewGuid(), null); + } + break; + } + + objType = info.BaseType; + } + } #else - if (map.PK != null && map.PK.IsAutoGuid) { - var prop = objType.GetProperty(map.PK.PropertyName); - if (prop != null) { - //if (prop.GetValue(obj, null).Equals(Guid.Empty)) { - if (prop.GetGetMethod().Invoke(obj, null).Equals(Guid.Empty)) - { - prop.SetValue(obj, Guid.NewGuid(), null); - } - } - } + if (map.PK != null && map.PK.IsAutoGuid) { + var prop = objType.GetProperty(map.PK.PropertyName); + if (prop != null) { + //if (prop.GetValue(obj, null).Equals(Guid.Empty)) { + if (prop.GetGetMethod().Invoke(obj, null).Equals(Guid.Empty)) + { + prop.SetValue(obj, Guid.NewGuid(), null); + } + } + } #endif @@ -1360,8 +1369,8 @@ public int Insert (object obj, string extra, Type objType) throw; } - if (map.HasAutoIncPK) - { + if (map.HasAutoIncPK) + { var id = SQLite3.LastInsertRowid (Handle); map.SetAutoIncPK (obj, id); } @@ -1588,7 +1597,7 @@ public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks) } } - [AttributeUsage (AttributeTargets.Class)] + [AttributeUsage (AttributeTargets.Class)] public class TableAttribute : Attribute { public string Name { get; set; } @@ -1650,6 +1659,14 @@ public override bool Unique { get { return true; } set { /* throw? */ } } + + public UniqueAttribute() : base() + { + } + + public UniqueAttribute(string name, int order) : base(name, order) + { + } } [AttributeUsage (AttributeTargets.Property)] @@ -1695,13 +1712,13 @@ public class TableMapping Column[] _insertColumns; Column[] _insertOrReplaceColumns; - public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None) + public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None) { MappedType = type; #if NETFX_CORE var tableAttr = (TableAttribute)System.Reflection.CustomAttributeExtensions - .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true); + .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true); #else var tableAttr = (TableAttribute)type.GetCustomAttributes (typeof (TableAttribute), true).FirstOrDefault (); #endif @@ -1806,26 +1823,26 @@ public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, stri PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra) { var cols = InsertColumns; - string insertSql; - if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) - { - insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra); - } - else - { + string insertSql; + if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) + { + insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra); + } + else + { var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; if (replacing) { cols = InsertOrReplaceColumns; } - insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName, - string.Join(",", (from c in cols - select "\"" + c.Name + "\"").ToArray()), - string.Join(",", (from c in cols - select "?").ToArray()), extra); - - } + insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName, + string.Join(",", (from c in cols + select "\"" + c.Name + "\"").ToArray()), + string.Join(",", (from c in cols + select "?").ToArray()), extra); + + } var insertCommand = new PreparedSqlLiteInsertCommand(conn); insertCommand.CommandText = insertSql; @@ -1852,8 +1869,8 @@ public class Column public string Collation { get; private set; } - public bool IsAutoInc { get; private set; } - public bool IsAutoGuid { get; private set; } + public bool IsAutoInc { get; private set; } + public bool IsAutoGuid { get; private set; } public bool IsPK { get; private set; } @@ -1863,36 +1880,36 @@ public class Column public int? MaxStringLength { get; private set; } - public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) - { - var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); + public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) + { + var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); - _prop = prop; - Name = colAttr == null ? prop.Name : colAttr.Name; - //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead - ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; - Collation = Orm.Collation(prop); + _prop = prop; + Name = colAttr == null ? prop.Name : colAttr.Name; + //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead + ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; + Collation = Orm.Collation(prop); - IsPK = Orm.IsPK(prop) || + IsPK = Orm.IsPK(prop) || (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) && - string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); - - var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); - IsAutoGuid = isAuto && ColumnType == typeof(Guid); - IsAutoInc = isAuto && !IsAutoGuid; - - Indices = Orm.GetIndices(prop); - if (!Indices.Any() - && !IsPK - && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) - && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) - ) - { - Indices = new IndexedAttribute[] { new IndexedAttribute() }; - } - IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop)); - MaxStringLength = Orm.MaxStringLength(prop); - } + string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); + + var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); + IsAutoGuid = isAuto && ColumnType == typeof(Guid); + IsAutoInc = isAuto && !IsAutoGuid; + + Indices = Orm.GetIndices(prop); + if (!Indices.Any() + && !IsPK + && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) + && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) + ) + { + Indices = new IndexedAttribute[] { new IndexedAttribute() }; + } + IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop)); + MaxStringLength = Orm.MaxStringLength(prop); + } public void SetValue (object obj, object val) { @@ -1908,9 +1925,9 @@ public object GetValue (object obj) public static class Orm { - public const int DefaultMaxStringLength = 140; - public const string ImplicitPkName = "Id"; - public const string ImplicitIndexSuffix = "Id"; + public const int DefaultMaxStringLength = 140; + public const string ImplicitPkName = "Id"; + public const string ImplicitIndexSuffix = "Id"; public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks) { @@ -1949,7 +1966,7 @@ public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks) return "varchar"; } else if (clrType == typeof(TimeSpan)) { - return "bigint"; + return "bigint"; } else if (clrType == typeof(DateTime)) { return storeDateTimeAsTicks ? "bigint" : "datetime"; } else if (clrType == typeof(DateTimeOffset)) { @@ -1962,9 +1979,9 @@ public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks) return "integer"; } else if (clrType == typeof(byte[])) { return "blob"; - } else if (clrType == typeof(Guid)) { - return "varchar(36)"; - } else { + } else if (clrType == typeof(Guid)) { + return "varchar(36)"; + } else { throw new NotSupportedException ("Don't know about " + clrType); } } @@ -1987,7 +2004,7 @@ public static string Collation (MemberInfo p) return ((CollationAttribute)attrs [0]).Value; #else if (attrs.Count() > 0) { - return ((CollationAttribute)attrs.First()).Value; + return ((CollationAttribute)attrs.First()).Value; #endif } else { return string.Empty; @@ -2061,7 +2078,6 @@ public int ExecuteNonQuery () r = SQLite3.Step (stmt); Finalize(stmt); } - if (r == SQLite3.Result.Done) { int rowsAffected = SQLite3.Changes (_conn.Handle); return rowsAffected; @@ -2134,7 +2150,7 @@ public IEnumerable ExecuteDeferredQuery (TableMapping map) var colType = SQLite3.ColumnType (stmt, i); var val = ReadCol (stmt, i, colType, cols [i].ColumnType); cols [i].SetValue (obj, val); - } + } OnInstanceCreated (obj); yield return (T)obj; } @@ -2156,17 +2172,17 @@ public T ExecuteScalar () var stmt = Prepare(); try { - var r = SQLite3.Step (stmt); - if (r == SQLite3.Result.Row) { - var colType = SQLite3.ColumnType (stmt, 0); - val = (T)ReadCol (stmt, 0, colType, typeof(T)); - } - else if (r == SQLite3.Result.Done) { - } - else - { - throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle)); - } + var r = SQLite3.Step (stmt); + if (r == SQLite3.Result.Row) { + var colType = SQLite3.ColumnType (stmt, 0); + val = (T)ReadCol (stmt, 0, colType, typeof(T)); + } + else if (r == SQLite3.Result.Done) { + } + else + { + throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle)); + } } finally { Finalize (stmt); } @@ -2262,13 +2278,13 @@ internal static void BindParameter (Sqlite3Statement stmt, int index, object val } else if (value.GetType().GetTypeInfo().IsEnum) { #endif SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is byte[]){ - SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); - } else if (value is Guid) { - SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); - } else { - throw new NotSupportedException("Cannot store type: " + value.GetType()); - } + } else if (value is byte[]){ + SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); + } else if (value is Guid) { + SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); + } else { + throw new NotSupportedException("Cannot store type: " + value.GetType()); + } } } @@ -2331,9 +2347,9 @@ object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clr } else if (clrType == typeof(byte[])) { return SQLite3.ColumnByteArray (stmt, index); } else if (clrType == typeof(Guid)) { - var text = SQLite3.ColumnString(stmt, index); - return new Guid(text); - } else{ + var text = SQLite3.ColumnString(stmt, index); + return new Guid(text); + } else{ throw new NotSupportedException ("Don't know how to read " + clrType); } } @@ -2724,6 +2740,15 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) CommandText = valr.CommandText, Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null }; + } else if (expr.NodeType == ExpressionType.Not) { + var u = (UnaryExpression)expr; + var ty = u.Type; + var valr = CompileExpr (u.Operand, queryArgs); + + return new CompileResult { + CommandText = "NOT " + valr.CommandText, + Value = valr.Value != null ? valr.Value : null + }; } else if (expr.NodeType == ExpressionType.MemberAccess) { var mem = (MemberExpression)expr; @@ -2759,7 +2784,7 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) #endif var m = (PropertyInfo)mem.Member; //val = m.GetValue (obj, null); - val = m.GetGetMethod().Invoke(obj, null); + val = m.GetGetMethod().Invoke(obj, null); #if !NETFX_CORE } else if (mem.Member.MemberType == MemberTypes.Field) { #else @@ -2897,7 +2922,7 @@ public T FirstOrDefault () var query = Take (1); return query.ToList().FirstOrDefault (); } - } + } public static class SQLite3 { @@ -2984,7 +3009,7 @@ public enum ExtendedResult : int NoticeRecoverWAL = (Result.Notice | (1 << 8)), NoticeRecoverRollback = (Result.Notice | (2 << 8)) } - + public enum ConfigOption : int { @@ -3042,10 +3067,10 @@ public static IntPtr Prepare2 (IntPtr db, string query) { IntPtr stmt; #if NETFX_CORE - byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query); - var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero); + byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query); + var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero); #else - var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero); + var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero); #endif if (r != Result.OK) { throw SQLiteException.New (r, GetErrmsg (db)); diff --git a/Example_unity4x/Assets/Scripts/Person.cs.meta b/Example/Assets/Scripts/SQLite.cs.meta similarity index 52% rename from Example_unity4x/Assets/Scripts/Person.cs.meta rename to Example/Assets/Scripts/SQLite.cs.meta index b45e795..0957163 100644 --- a/Example_unity4x/Assets/Scripts/Person.cs.meta +++ b/Example/Assets/Scripts/SQLite.cs.meta @@ -1,8 +1,12 @@ fileFormatVersion: 2 -guid: 6773d9b70bd0c85499a631dcfc466635 +guid: 1384d96dd0201b949857a121d225a5a4 +timeCreated: 1453572025 +licenseType: Free MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: + assetBundleName: + assetBundleVariant: diff --git a/Example_unity5/Assets/StreamingAssets.meta b/Example/Assets/StreamingAssets.meta similarity index 67% rename from Example_unity5/Assets/StreamingAssets.meta rename to Example/Assets/StreamingAssets.meta index a5f56e8..4a01558 100644 --- a/Example_unity5/Assets/StreamingAssets.meta +++ b/Example/Assets/StreamingAssets.meta @@ -1,7 +1,7 @@ fileFormatVersion: 2 -guid: 15f8ea1414a7c2544b0100672419a316 +guid: f265153daaae64c4f95baa15799711c2 folderAsset: yes -timeCreated: 1445132694 +timeCreated: 1453576960 licenseType: Free DefaultImporter: userData: diff --git a/Example_unity5/Assets/StreamingAssets/existing.db b/Example/Assets/StreamingAssets/existing.db similarity index 89% rename from Example_unity5/Assets/StreamingAssets/existing.db rename to Example/Assets/StreamingAssets/existing.db index 081c9db..b8b00f3 100644 Binary files a/Example_unity5/Assets/StreamingAssets/existing.db and b/Example/Assets/StreamingAssets/existing.db differ diff --git a/Example_unity5/Assets/StreamingAssets/existing.db.meta b/Example/Assets/StreamingAssets/existing.db.meta similarity index 100% rename from Example_unity5/Assets/StreamingAssets/existing.db.meta rename to Example/Assets/StreamingAssets/existing.db.meta diff --git a/Example_unity4x/Assets/Plugins.meta b/Example_unity4x/Assets/Plugins.meta deleted file mode 100644 index 1405795..0000000 --- a/Example_unity4x/Assets/Plugins.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: fda2923f5039add46ae29032389f1b85 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/Android.meta b/Example_unity4x/Assets/Plugins/Android.meta deleted file mode 100644 index ee11af6..0000000 --- a/Example_unity4x/Assets/Plugins/Android.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: d0f2c64195dbc614c8c2fdd69bf5ba2a -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/Android/libs.meta b/Example_unity4x/Assets/Plugins/Android/libs.meta deleted file mode 100644 index 7541d92..0000000 --- a/Example_unity4x/Assets/Plugins/Android/libs.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: cd630a67a76adfb43a84731922e0a678 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a.meta b/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a.meta deleted file mode 100644 index 6627ba6..0000000 --- a/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 03d1a68c370cb2047bf4c240a556a086 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so b/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so deleted file mode 100644 index d69ba56..0000000 Binary files a/Example_unity4x/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/Android/libs/x86.meta b/Example_unity4x/Assets/Plugins/Android/libs/x86.meta deleted file mode 100644 index 6615e1d..0000000 --- a/Example_unity4x/Assets/Plugins/Android/libs/x86.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 1eaeb264e07ef2b4d9609b2e5074ad0a -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/Android/libs/x86/libsqlite3.so b/Example_unity4x/Assets/Plugins/Android/libs/x86/libsqlite3.so deleted file mode 100644 index d4d1203..0000000 Binary files a/Example_unity4x/Assets/Plugins/Android/libs/x86/libsqlite3.so and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta b/Example_unity4x/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta deleted file mode 100644 index dd4d4c1..0000000 --- a/Example_unity4x/Assets/Plugins/Android/libs/x86/libsqlite3.so.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 94b405184f3f68049b7c35035951f88f -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/SQLite4Unity3d.dll b/Example_unity4x/Assets/Plugins/SQLite4Unity3d.dll deleted file mode 100644 index 6789822..0000000 Binary files a/Example_unity4x/Assets/Plugins/SQLite4Unity3d.dll and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/SQLite4Unity3d.dll.meta b/Example_unity4x/Assets/Plugins/SQLite4Unity3d.dll.meta deleted file mode 100644 index 97f5a92..0000000 --- a/Example_unity4x/Assets/Plugins/SQLite4Unity3d.dll.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: ad4253fa87f19e64398208b29f782b30 -MonoAssemblyImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8.meta b/Example_unity4x/Assets/Plugins/WP8.meta deleted file mode 100644 index 246ccb8..0000000 --- a/Example_unity4x/Assets/Plugins/WP8.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 8f57a25f3d05b9b498b7ea974e40d5c3 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM.meta b/Example_unity4x/Assets/Plugins/WP8/ARM.meta deleted file mode 100644 index ca3fced..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/ARM.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 2001be933d37b714e92f675804364f7f -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll b/Example_unity4x/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll deleted file mode 100644 index fcd68f8..0000000 Binary files a/Example_unity4x/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll.meta b/Example_unity4x/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll.meta deleted file mode 100644 index 9f96cd3..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: d0c088ffdaf312e44b44bb198e827ef6 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.dll b/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.dll deleted file mode 100644 index 4b214ef..0000000 Binary files a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.dll and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.dll.meta b/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.dll.meta deleted file mode 100644 index cc62c7b..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.dll.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 70805c109a0e665409c4b11b500d325d -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.winmd b/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.winmd deleted file mode 100644 index aa03ff2..0000000 Binary files a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.winmd and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.winmd.meta b/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.winmd.meta deleted file mode 100644 index dcaebec..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/ARM/Sqlite.winmd.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 06d52e99e69d37547b0fd46a22268cec -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/README.txt b/Example_unity4x/Assets/Plugins/WP8/README.txt deleted file mode 100644 index 52a341a..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/README.txt +++ /dev/null @@ -1,13 +0,0 @@ -For this to work properly you will have to do some extra work. -It seems that Unity 4.x is not recognizing the folder structure when creating the WP8 project and it will use the x86 dlls by default. If you try to override them in your recently created solution it will compile but when you try to run it it wont work and you will recibe an error similar to this: -'Could not load type 'UnityEngine.Internal.$Metadata[..]' - -You will have to follow these steps: -0. If you're targeting a the emulator an not a real device, then when it says WP/x86 you must read WP/ARM and the other way around. i.e. 1-5 is written considering you want to deploy to a real device. -1. In your Unity project, remove the WP/x86 folder. -2. Put the content of the WP/ARM folder into WP and remove WP/ARM folder. -3. Generate the project. -4. Add the following references: - - sqlite.winmd (directly in the root) - - SQLite for Windows Phone (Windows Phone/Extensions in your reference manager. You will have to download this with TOOLS > Extensions and Updates in your VS ) -5. You're ready to go! \ No newline at end of file diff --git a/Example_unity4x/Assets/Plugins/WP8/README.txt.meta b/Example_unity4x/Assets/Plugins/WP8/README.txt.meta deleted file mode 100644 index 78659a4..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/README.txt.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 9a5647017aa3f16459d0d6bf64b757b5 -TextScriptImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/x86.meta b/Example_unity4x/Assets/Plugins/WP8/x86.meta deleted file mode 100644 index 0e25995..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/x86.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 1eec5e54dd983a74aa547c4de30ea3e3 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll b/Example_unity4x/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll deleted file mode 100644 index 2c39578..0000000 Binary files a/Example_unity4x/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll.meta b/Example_unity4x/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll.meta deleted file mode 100644 index 47b817d..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: ecb623d045489f24990940516508f957 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.dll b/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.dll deleted file mode 100644 index 9058eb4..0000000 Binary files a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.dll and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.dll.meta b/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.dll.meta deleted file mode 100644 index 08c3fcd..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.dll.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: adde190b83034c844a1a7f5add0b1b99 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.winmd b/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.winmd deleted file mode 100644 index 46466bc..0000000 Binary files a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.winmd and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.winmd.meta b/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.winmd.meta deleted file mode 100644 index 14f845c..0000000 --- a/Example_unity4x/Assets/Plugins/WP8/x86/Sqlite.winmd.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: cda79e6bab5bb3142bbcf32f5674cb01 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/iOS.meta b/Example_unity4x/Assets/Plugins/iOS.meta deleted file mode 100644 index be3aebf..0000000 --- a/Example_unity4x/Assets/Plugins/iOS.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: bc03fb268174f19499bfd68729b9a332 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/iOS/x64.meta b/Example_unity4x/Assets/Plugins/iOS/x64.meta deleted file mode 100644 index f5e5554..0000000 --- a/Example_unity4x/Assets/Plugins/iOS/x64.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: a73a244939fc73045b3ccdd0436a6b1b -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/iOS/x64/sqlite3.dll.meta b/Example_unity4x/Assets/Plugins/iOS/x64/sqlite3.dll.meta deleted file mode 100644 index 3a70273..0000000 --- a/Example_unity4x/Assets/Plugins/iOS/x64/sqlite3.dll.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 3f9d7d46b921d2f4bb5fa8df8e26675b -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/iOS/x86.meta b/Example_unity4x/Assets/Plugins/iOS/x86.meta deleted file mode 100644 index 8f21a21..0000000 --- a/Example_unity4x/Assets/Plugins/iOS/x86.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 551c4d62722bf4042b2537e429dc4396 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Plugins/iOS/x86/sqlite3.dll b/Example_unity4x/Assets/Plugins/iOS/x86/sqlite3.dll deleted file mode 100644 index 4cd5a11..0000000 Binary files a/Example_unity4x/Assets/Plugins/iOS/x86/sqlite3.dll and /dev/null differ diff --git a/Example_unity4x/Assets/Plugins/iOS/x86/sqlite3.dll.meta b/Example_unity4x/Assets/Plugins/iOS/x86/sqlite3.dll.meta deleted file mode 100644 index 28d1c84..0000000 --- a/Example_unity4x/Assets/Plugins/iOS/x86/sqlite3.dll.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: f9d16dac973025d4a8a5d1bb81b40624 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Scenes.meta b/Example_unity4x/Assets/Scenes.meta deleted file mode 100644 index 3485c14..0000000 --- a/Example_unity4x/Assets/Scenes.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 884f336ba20f41f41ae45fd33f7d594a -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Scenes/CreateDBFromScript.unity b/Example_unity4x/Assets/Scenes/CreateDBFromScript.unity deleted file mode 100644 index 54f6e84..0000000 Binary files a/Example_unity4x/Assets/Scenes/CreateDBFromScript.unity and /dev/null differ diff --git a/Example_unity4x/Assets/Scenes/CreateDBFromScript.unity.meta b/Example_unity4x/Assets/Scenes/CreateDBFromScript.unity.meta deleted file mode 100644 index 3eb205e..0000000 --- a/Example_unity4x/Assets/Scenes/CreateDBFromScript.unity.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 39df29e4e465a5544b9a93440d6e4d07 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Scenes/ExistingDBScript.unity b/Example_unity4x/Assets/Scenes/ExistingDBScript.unity deleted file mode 100644 index c05302b..0000000 Binary files a/Example_unity4x/Assets/Scenes/ExistingDBScript.unity and /dev/null differ diff --git a/Example_unity4x/Assets/Scenes/ExistingDBScript.unity.meta b/Example_unity4x/Assets/Scenes/ExistingDBScript.unity.meta deleted file mode 100644 index df9e8fd..0000000 --- a/Example_unity4x/Assets/Scenes/ExistingDBScript.unity.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: 7ea874199b10b0044a45ccd901a9b5bb -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Scripts.meta b/Example_unity4x/Assets/Scripts.meta deleted file mode 100644 index 32937c7..0000000 --- a/Example_unity4x/Assets/Scripts.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: f47528bb367389d4a9c8d78342271cd3 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/Scripts/CreateDBScript.cs b/Example_unity4x/Assets/Scripts/CreateDBScript.cs deleted file mode 100644 index e75ab3f..0000000 --- a/Example_unity4x/Assets/Scripts/CreateDBScript.cs +++ /dev/null @@ -1,32 +0,0 @@ -using UnityEngine; -using System.Collections; -using System.Collections.Generic; -using UnityEngine.UI; -using System; - -public class CreateDBScript : MonoBehaviour { - - public Text DebugText; - - // Use this for initialization - void Start () { - var ds = new DataService ("tempDatabase.db"); - ds.CreateDB (); - var people = ds.GetPersons (); - ToConsole (people); - people = ds.GetPersonsNamedRoberto (); - ToConsole("Searching for Roberto ..."); - ToConsole (people); - } - - private void ToConsole(IEnumerable people){ - foreach (var person in people) { - ToConsole(person.ToString()); - } - } - - private void ToConsole(string msg){ - DebugText.text += System.Environment.NewLine + msg; - Debug.Log (msg); - } -} diff --git a/Example_unity4x/Assets/Scripts/CreateDBScript.cs.meta b/Example_unity4x/Assets/Scripts/CreateDBScript.cs.meta deleted file mode 100644 index 5d756c1..0000000 --- a/Example_unity4x/Assets/Scripts/CreateDBScript.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: e0cba9468d3b00a44ac7b867c0dd19d1 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/Example_unity4x/Assets/Scripts/DataService.cs b/Example_unity4x/Assets/Scripts/DataService.cs deleted file mode 100644 index 15eb10f..0000000 --- a/Example_unity4x/Assets/Scripts/DataService.cs +++ /dev/null @@ -1,111 +0,0 @@ -using UnityEngine; -#if !UNITY_EDITOR -using System.Collections; -using System.IO; -#endif -using SQLite4Unity3d; -using System.Collections.Generic; - -public class DataService { - - private SQLiteConnection _connection; - - public DataService(string DatabaseName){ - - - -#if UNITY_EDITOR - var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName); -#else - // check if file exists in Application.persistentDataPath - var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName); - if (!File.Exists(filepath)) - { - Debug.Log("Database not in Persistent path"); - // if it doesn't -> - // open StreamingAssets directory and load the db -> - -#if UNITY_ANDROID - var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android - while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check - // then save to Application.persistentDataPath - File.WriteAllBytes(filepath, loadDb.bytes); -#elif UNITY_IOS - var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS - // then save to Application.persistentDataPath - File.Copy(loadDb, filepath); -#elif UNITY_WP8 - var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS - // then save to Application.persistentDataPath - File.Copy(loadDb, filepath); - -#elif UNITY_WINRT - var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS - // then save to Application.persistentDataPath - File.Copy(loadDb, filepath); -#endif - - Debug.Log("Database written"); - } - - var dbPath = filepath; -#endif - _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create); - Debug.Log("Final PATH: " + dbPath); - - } - - public void CreateDB(){ - _connection.DropTable (); - _connection.CreateTable (); - - _connection.InsertAll (new[]{ - new Person{ - Id = 1, - Name = "Tom", - Surname = "Perez", - Age = 56 - }, - new Person{ - Id = 2, - Name = "Fred", - Surname = "Arthurson", - Age = 16 - }, - new Person{ - Id = 3, - Name = "John", - Surname = "Doe", - Age = 25 - }, - new Person{ - Id = 4, - Name = "Roberto", - Surname = "Huertas", - Age = 37 - }, - }); - } - - public IEnumerable GetPersons(){ - return _connection.Table(); - } - - public IEnumerable GetPersonsNamedRoberto(){ - return _connection.Table().Where(x => x.Name == "Roberto"); - } - - public Person GetJohnny(){ - return _connection.Table().Where(x => x.Name == "Johnny").FirstOrDefault(); - } - - public Person CreatePerson(){ - var p = new Person{ - Name = "Johnny", - Surname = "Mnemonic", - Age = 21 - }; - _connection.Insert (p); - return p; - } -} diff --git a/Example_unity4x/Assets/Scripts/DataService.cs.meta b/Example_unity4x/Assets/Scripts/DataService.cs.meta deleted file mode 100644 index 4baef02..0000000 --- a/Example_unity4x/Assets/Scripts/DataService.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 971ed78b0daa43e49bbe3fbfb0dbbc57 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/Example_unity4x/Assets/Scripts/ExistingDBScript.cs b/Example_unity4x/Assets/Scripts/ExistingDBScript.cs deleted file mode 100644 index 52cd628..0000000 --- a/Example_unity4x/Assets/Scripts/ExistingDBScript.cs +++ /dev/null @@ -1,39 +0,0 @@ -using UnityEngine; -using System.Collections; -using System.Collections.Generic; -using UnityEngine.UI; - -public class ExistingDBScript : MonoBehaviour { - - public Text DebugText; - - // Use this for initialization - void Start () { - var ds = new DataService ("existing.db"); - //ds.CreateDB (); - var people = ds.GetPersons (); - ToConsole (people); - - people = ds.GetPersonsNamedRoberto (); - ToConsole("Searching for Roberto ..."); - ToConsole (people); - - ds.CreatePerson (); - ToConsole("New person has been created"); - var p = ds.GetJohnny (); - ToConsole(p.ToString()); - - } - - private void ToConsole(IEnumerable people){ - foreach (var person in people) { - ToConsole(person.ToString()); - } - } - - private void ToConsole(string msg){ - DebugText.text += System.Environment.NewLine + msg; - Debug.Log (msg); - } - -} diff --git a/Example_unity4x/Assets/Scripts/ExistingDBScript.cs.meta b/Example_unity4x/Assets/Scripts/ExistingDBScript.cs.meta deleted file mode 100644 index b3a8bd0..0000000 --- a/Example_unity4x/Assets/Scripts/ExistingDBScript.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: aac67c9c822da4b44889febc132d24f5 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/Example_unity4x/Assets/Scripts/Person.cs b/Example_unity4x/Assets/Scripts/Person.cs deleted file mode 100644 index f15b4d1..0000000 --- a/Example_unity4x/Assets/Scripts/Person.cs +++ /dev/null @@ -1,17 +0,0 @@ -using UnityEngine; -using System.Collections; -using SQLite4Unity3d; - -public class Person { - - [PrimaryKey, AutoIncrement] - public int Id { get; set; } - public string Name { get; set; } - public string Surname { get; set; } - public int Age { get; set; } - - public override string ToString () - { - return string.Format ("[Person: Id={0}, Name={1}, Surname={2}, Age={3}]", Id, Name, Surname, Age); - } -} diff --git a/Example_unity4x/Assets/StreamingAssets.meta b/Example_unity4x/Assets/StreamingAssets.meta deleted file mode 100644 index b4b95e1..0000000 --- a/Example_unity4x/Assets/StreamingAssets.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: b6c249d1db1ae1d409db7e26475f56e3 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/StreamingAssets/existing.db b/Example_unity4x/Assets/StreamingAssets/existing.db deleted file mode 100644 index eb6b1d5..0000000 Binary files a/Example_unity4x/Assets/StreamingAssets/existing.db and /dev/null differ diff --git a/Example_unity4x/Assets/StreamingAssets/existing.db.meta b/Example_unity4x/Assets/StreamingAssets/existing.db.meta deleted file mode 100644 index aa6fee1..0000000 --- a/Example_unity4x/Assets/StreamingAssets/existing.db.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: edb2d2743d9183e4b9118afeaaf07192 -DefaultImporter: - userData: diff --git a/Example_unity4x/Assets/StreamingAssets/tempDatabase.db b/Example_unity4x/Assets/StreamingAssets/tempDatabase.db deleted file mode 100644 index 19f9997..0000000 Binary files a/Example_unity4x/Assets/StreamingAssets/tempDatabase.db and /dev/null differ diff --git a/Example_unity4x/Assets/StreamingAssets/tempDatabase.db.meta b/Example_unity4x/Assets/StreamingAssets/tempDatabase.db.meta deleted file mode 100644 index 8bb5847..0000000 --- a/Example_unity4x/Assets/StreamingAssets/tempDatabase.db.meta +++ /dev/null @@ -1,4 +0,0 @@ -fileFormatVersion: 2 -guid: f78def66405d5224389b320cf8e489b8 -DefaultImporter: - userData: diff --git a/Example_unity4x/Library/AnnotationManager b/Example_unity4x/Library/AnnotationManager deleted file mode 100644 index 6cbaf86..0000000 Binary files a/Example_unity4x/Library/AnnotationManager and /dev/null differ diff --git a/Example_unity4x/Library/AssetImportState b/Example_unity4x/Library/AssetImportState deleted file mode 100644 index cfb43ea..0000000 --- a/Example_unity4x/Library/AssetImportState +++ /dev/null @@ -1 +0,0 @@ -5;0;-1 \ No newline at end of file diff --git a/Example_unity4x/Library/AssetServerCacheV3 b/Example_unity4x/Library/AssetServerCacheV3 deleted file mode 100644 index 1786f9b..0000000 Binary files a/Example_unity4x/Library/AssetServerCacheV3 and /dev/null differ diff --git a/Example_unity4x/Library/BuildPlayer.prefs b/Example_unity4x/Library/BuildPlayer.prefs deleted file mode 100644 index e69de29..0000000 diff --git a/Example_unity4x/Library/CurrentLayout.dwlt b/Example_unity4x/Library/CurrentLayout.dwlt deleted file mode 100644 index d8db655..0000000 Binary files a/Example_unity4x/Library/CurrentLayout.dwlt and /dev/null differ diff --git a/Example_unity4x/Library/FailedAssetImports.txt b/Example_unity4x/Library/FailedAssetImports.txt deleted file mode 100644 index e69de29..0000000 diff --git a/Example_unity4x/Library/ScriptAssemblies/Assembly-CSharp.dll b/Example_unity4x/Library/ScriptAssemblies/Assembly-CSharp.dll deleted file mode 100644 index 8399d6a..0000000 Binary files a/Example_unity4x/Library/ScriptAssemblies/Assembly-CSharp.dll and /dev/null differ diff --git a/Example_unity4x/Library/ScriptAssemblies/Assembly-CSharp.dll.mdb b/Example_unity4x/Library/ScriptAssemblies/Assembly-CSharp.dll.mdb deleted file mode 100644 index f388f5c..0000000 Binary files a/Example_unity4x/Library/ScriptAssemblies/Assembly-CSharp.dll.mdb and /dev/null differ diff --git a/Example_unity4x/Library/ScriptAssemblies/CompilationCompleted.txt b/Example_unity4x/Library/ScriptAssemblies/CompilationCompleted.txt deleted file mode 100644 index d25ad0d..0000000 --- a/Example_unity4x/Library/ScriptAssemblies/CompilationCompleted.txt +++ /dev/null @@ -1 +0,0 @@ -Completed diff --git a/Example_unity4x/Library/ScriptMapper b/Example_unity4x/Library/ScriptMapper deleted file mode 100644 index 95bbf72..0000000 Binary files a/Example_unity4x/Library/ScriptMapper and /dev/null differ diff --git a/Example_unity4x/Library/assetDatabase3 b/Example_unity4x/Library/assetDatabase3 deleted file mode 100644 index 97a7ada..0000000 Binary files a/Example_unity4x/Library/assetDatabase3 and /dev/null differ diff --git a/Example_unity4x/Library/expandedItems b/Example_unity4x/Library/expandedItems deleted file mode 100644 index fba93b2..0000000 Binary files a/Example_unity4x/Library/expandedItems and /dev/null differ diff --git a/Example_unity4x/Library/guidmapper b/Example_unity4x/Library/guidmapper deleted file mode 100644 index d886495..0000000 Binary files a/Example_unity4x/Library/guidmapper and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000001000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000001000000000000000 deleted file mode 100644 index eb68f85..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000001000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000002000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000002000000000000000 deleted file mode 100644 index 852e993..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000002000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000003000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000003000000000000000 deleted file mode 100644 index 8197f93..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000003000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000004000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000004000000000000000 deleted file mode 100644 index b1ab503..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000004000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000004100000000000000 b/Example_unity4x/Library/metadata/00/00000000000000004100000000000000 deleted file mode 100644 index 18e172d..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000004100000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000005000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000005000000000000000 deleted file mode 100644 index ae461fd..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000005000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000005100000000000000 b/Example_unity4x/Library/metadata/00/00000000000000005100000000000000 deleted file mode 100644 index 356a530..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000005100000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000006000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000006000000000000000 deleted file mode 100644 index e300b13..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000006000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000006100000000000000 b/Example_unity4x/Library/metadata/00/00000000000000006100000000000000 deleted file mode 100644 index b52d9b7..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000006100000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000007000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000007000000000000000 deleted file mode 100644 index 22fd804..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000007000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000008000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000008000000000000000 deleted file mode 100644 index f508a38..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000008000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/00000000000000009000000000000000 b/Example_unity4x/Library/metadata/00/00000000000000009000000000000000 deleted file mode 100644 index d336c3e..0000000 Binary files a/Example_unity4x/Library/metadata/00/00000000000000009000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/0000000000000000a000000000000000 b/Example_unity4x/Library/metadata/00/0000000000000000a000000000000000 deleted file mode 100644 index 5b534e7..0000000 Binary files a/Example_unity4x/Library/metadata/00/0000000000000000a000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/0000000000000000b000000000000000 b/Example_unity4x/Library/metadata/00/0000000000000000b000000000000000 deleted file mode 100644 index 60bc656..0000000 Binary files a/Example_unity4x/Library/metadata/00/0000000000000000b000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/00/0000000000000000c000000000000000 b/Example_unity4x/Library/metadata/00/0000000000000000c000000000000000 deleted file mode 100644 index 924e81f..0000000 Binary files a/Example_unity4x/Library/metadata/00/0000000000000000c000000000000000 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/03/03d1a68c370cb2047bf4c240a556a086 b/Example_unity4x/Library/metadata/03/03d1a68c370cb2047bf4c240a556a086 deleted file mode 100644 index 82e2062..0000000 Binary files a/Example_unity4x/Library/metadata/03/03d1a68c370cb2047bf4c240a556a086 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/06/06d52e99e69d37547b0fd46a22268cec b/Example_unity4x/Library/metadata/06/06d52e99e69d37547b0fd46a22268cec deleted file mode 100644 index 28bc774..0000000 Binary files a/Example_unity4x/Library/metadata/06/06d52e99e69d37547b0fd46a22268cec and /dev/null differ diff --git a/Example_unity4x/Library/metadata/1e/1eaeb264e07ef2b4d9609b2e5074ad0a b/Example_unity4x/Library/metadata/1e/1eaeb264e07ef2b4d9609b2e5074ad0a deleted file mode 100644 index e74297f..0000000 Binary files a/Example_unity4x/Library/metadata/1e/1eaeb264e07ef2b4d9609b2e5074ad0a and /dev/null differ diff --git a/Example_unity4x/Library/metadata/1e/1eec5e54dd983a74aa547c4de30ea3e3 b/Example_unity4x/Library/metadata/1e/1eec5e54dd983a74aa547c4de30ea3e3 deleted file mode 100644 index eb64c0f..0000000 Binary files a/Example_unity4x/Library/metadata/1e/1eec5e54dd983a74aa547c4de30ea3e3 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/20/2001be933d37b714e92f675804364f7f b/Example_unity4x/Library/metadata/20/2001be933d37b714e92f675804364f7f deleted file mode 100644 index 2c3d0a3..0000000 Binary files a/Example_unity4x/Library/metadata/20/2001be933d37b714e92f675804364f7f and /dev/null differ diff --git a/Example_unity4x/Library/metadata/39/39df29e4e465a5544b9a93440d6e4d07 b/Example_unity4x/Library/metadata/39/39df29e4e465a5544b9a93440d6e4d07 deleted file mode 100644 index 460581b..0000000 Binary files a/Example_unity4x/Library/metadata/39/39df29e4e465a5544b9a93440d6e4d07 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/3f/3f9d7d46b921d2f4bb5fa8df8e26675b b/Example_unity4x/Library/metadata/3f/3f9d7d46b921d2f4bb5fa8df8e26675b deleted file mode 100644 index 6b12089..0000000 Binary files a/Example_unity4x/Library/metadata/3f/3f9d7d46b921d2f4bb5fa8df8e26675b and /dev/null differ diff --git a/Example_unity4x/Library/metadata/55/551c4d62722bf4042b2537e429dc4396 b/Example_unity4x/Library/metadata/55/551c4d62722bf4042b2537e429dc4396 deleted file mode 100644 index 6cc2b54..0000000 Binary files a/Example_unity4x/Library/metadata/55/551c4d62722bf4042b2537e429dc4396 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/67/6773d9b70bd0c85499a631dcfc466635 b/Example_unity4x/Library/metadata/67/6773d9b70bd0c85499a631dcfc466635 deleted file mode 100644 index b32b676..0000000 Binary files a/Example_unity4x/Library/metadata/67/6773d9b70bd0c85499a631dcfc466635 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/70/70805c109a0e665409c4b11b500d325d b/Example_unity4x/Library/metadata/70/70805c109a0e665409c4b11b500d325d deleted file mode 100644 index 9921006..0000000 Binary files a/Example_unity4x/Library/metadata/70/70805c109a0e665409c4b11b500d325d and /dev/null differ diff --git a/Example_unity4x/Library/metadata/70/70e08f118a6a4ff4d94bb1e26fc37c0a b/Example_unity4x/Library/metadata/70/70e08f118a6a4ff4d94bb1e26fc37c0a deleted file mode 100644 index f00bedb..0000000 Binary files a/Example_unity4x/Library/metadata/70/70e08f118a6a4ff4d94bb1e26fc37c0a and /dev/null differ diff --git a/Example_unity4x/Library/metadata/7e/7ea874199b10b0044a45ccd901a9b5bb b/Example_unity4x/Library/metadata/7e/7ea874199b10b0044a45ccd901a9b5bb deleted file mode 100644 index 6883571..0000000 Binary files a/Example_unity4x/Library/metadata/7e/7ea874199b10b0044a45ccd901a9b5bb and /dev/null differ diff --git a/Example_unity4x/Library/metadata/80/80a3616ca19596e4da0f10f14d241e9f b/Example_unity4x/Library/metadata/80/80a3616ca19596e4da0f10f14d241e9f deleted file mode 100644 index c3d20a4..0000000 Binary files a/Example_unity4x/Library/metadata/80/80a3616ca19596e4da0f10f14d241e9f and /dev/null differ diff --git a/Example_unity4x/Library/metadata/88/884f336ba20f41f41ae45fd33f7d594a b/Example_unity4x/Library/metadata/88/884f336ba20f41f41ae45fd33f7d594a deleted file mode 100644 index 7572a07..0000000 Binary files a/Example_unity4x/Library/metadata/88/884f336ba20f41f41ae45fd33f7d594a and /dev/null differ diff --git a/Example_unity4x/Library/metadata/8f/8f57a25f3d05b9b498b7ea974e40d5c3 b/Example_unity4x/Library/metadata/8f/8f57a25f3d05b9b498b7ea974e40d5c3 deleted file mode 100644 index f99dff5..0000000 Binary files a/Example_unity4x/Library/metadata/8f/8f57a25f3d05b9b498b7ea974e40d5c3 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/94/94b405184f3f68049b7c35035951f88f b/Example_unity4x/Library/metadata/94/94b405184f3f68049b7c35035951f88f deleted file mode 100644 index 8ff230e..0000000 Binary files a/Example_unity4x/Library/metadata/94/94b405184f3f68049b7c35035951f88f and /dev/null differ diff --git a/Example_unity4x/Library/metadata/97/971ed78b0daa43e49bbe3fbfb0dbbc57 b/Example_unity4x/Library/metadata/97/971ed78b0daa43e49bbe3fbfb0dbbc57 deleted file mode 100644 index 8c32e84..0000000 Binary files a/Example_unity4x/Library/metadata/97/971ed78b0daa43e49bbe3fbfb0dbbc57 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/9a/9a5647017aa3f16459d0d6bf64b757b5 b/Example_unity4x/Library/metadata/9a/9a5647017aa3f16459d0d6bf64b757b5 deleted file mode 100644 index 8c218aa..0000000 Binary files a/Example_unity4x/Library/metadata/9a/9a5647017aa3f16459d0d6bf64b757b5 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/a7/a73a244939fc73045b3ccdd0436a6b1b b/Example_unity4x/Library/metadata/a7/a73a244939fc73045b3ccdd0436a6b1b deleted file mode 100644 index fac75c2..0000000 Binary files a/Example_unity4x/Library/metadata/a7/a73a244939fc73045b3ccdd0436a6b1b and /dev/null differ diff --git a/Example_unity4x/Library/metadata/aa/aac67c9c822da4b44889febc132d24f5 b/Example_unity4x/Library/metadata/aa/aac67c9c822da4b44889febc132d24f5 deleted file mode 100644 index 697243c..0000000 Binary files a/Example_unity4x/Library/metadata/aa/aac67c9c822da4b44889febc132d24f5 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/ad/ad4253fa87f19e64398208b29f782b30 b/Example_unity4x/Library/metadata/ad/ad4253fa87f19e64398208b29f782b30 deleted file mode 100644 index ff5d6f9..0000000 Binary files a/Example_unity4x/Library/metadata/ad/ad4253fa87f19e64398208b29f782b30 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/ad/adde190b83034c844a1a7f5add0b1b99 b/Example_unity4x/Library/metadata/ad/adde190b83034c844a1a7f5add0b1b99 deleted file mode 100644 index c0de98a..0000000 Binary files a/Example_unity4x/Library/metadata/ad/adde190b83034c844a1a7f5add0b1b99 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/bc/bc03fb268174f19499bfd68729b9a332 b/Example_unity4x/Library/metadata/bc/bc03fb268174f19499bfd68729b9a332 deleted file mode 100644 index 04262cd..0000000 Binary files a/Example_unity4x/Library/metadata/bc/bc03fb268174f19499bfd68729b9a332 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/cd/cd630a67a76adfb43a84731922e0a678 b/Example_unity4x/Library/metadata/cd/cd630a67a76adfb43a84731922e0a678 deleted file mode 100644 index ab5d626..0000000 Binary files a/Example_unity4x/Library/metadata/cd/cd630a67a76adfb43a84731922e0a678 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/cd/cda79e6bab5bb3142bbcf32f5674cb01 b/Example_unity4x/Library/metadata/cd/cda79e6bab5bb3142bbcf32f5674cb01 deleted file mode 100644 index 5dd8840..0000000 Binary files a/Example_unity4x/Library/metadata/cd/cda79e6bab5bb3142bbcf32f5674cb01 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/d0/d0c088ffdaf312e44b44bb198e827ef6 b/Example_unity4x/Library/metadata/d0/d0c088ffdaf312e44b44bb198e827ef6 deleted file mode 100644 index aed8130..0000000 Binary files a/Example_unity4x/Library/metadata/d0/d0c088ffdaf312e44b44bb198e827ef6 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/d0/d0f2c64195dbc614c8c2fdd69bf5ba2a b/Example_unity4x/Library/metadata/d0/d0f2c64195dbc614c8c2fdd69bf5ba2a deleted file mode 100644 index 55e2a83..0000000 Binary files a/Example_unity4x/Library/metadata/d0/d0f2c64195dbc614c8c2fdd69bf5ba2a and /dev/null differ diff --git a/Example_unity4x/Library/metadata/e0/e0cba9468d3b00a44ac7b867c0dd19d1 b/Example_unity4x/Library/metadata/e0/e0cba9468d3b00a44ac7b867c0dd19d1 deleted file mode 100644 index bf99873..0000000 Binary files a/Example_unity4x/Library/metadata/e0/e0cba9468d3b00a44ac7b867c0dd19d1 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/ec/ecb623d045489f24990940516508f957 b/Example_unity4x/Library/metadata/ec/ecb623d045489f24990940516508f957 deleted file mode 100644 index 2fa9d93..0000000 Binary files a/Example_unity4x/Library/metadata/ec/ecb623d045489f24990940516508f957 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/f4/f47528bb367389d4a9c8d78342271cd3 b/Example_unity4x/Library/metadata/f4/f47528bb367389d4a9c8d78342271cd3 deleted file mode 100644 index eb8e0d0..0000000 Binary files a/Example_unity4x/Library/metadata/f4/f47528bb367389d4a9c8d78342271cd3 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/f5/f5f67c52d1564df4a8936ccd202a3bd8 b/Example_unity4x/Library/metadata/f5/f5f67c52d1564df4a8936ccd202a3bd8 deleted file mode 100644 index a620402..0000000 Binary files a/Example_unity4x/Library/metadata/f5/f5f67c52d1564df4a8936ccd202a3bd8 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/f9/f9d16dac973025d4a8a5d1bb81b40624 b/Example_unity4x/Library/metadata/f9/f9d16dac973025d4a8a5d1bb81b40624 deleted file mode 100644 index 58aa147..0000000 Binary files a/Example_unity4x/Library/metadata/f9/f9d16dac973025d4a8a5d1bb81b40624 and /dev/null differ diff --git a/Example_unity4x/Library/metadata/fd/fda2923f5039add46ae29032389f1b85 b/Example_unity4x/Library/metadata/fd/fda2923f5039add46ae29032389f1b85 deleted file mode 100644 index 401c97b..0000000 Binary files a/Example_unity4x/Library/metadata/fd/fda2923f5039add46ae29032389f1b85 and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/AudioManager.asset b/Example_unity4x/ProjectSettings/AudioManager.asset deleted file mode 100644 index ae5fc8d..0000000 Binary files a/Example_unity4x/ProjectSettings/AudioManager.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/DynamicsManager.asset b/Example_unity4x/ProjectSettings/DynamicsManager.asset deleted file mode 100644 index 569c766..0000000 Binary files a/Example_unity4x/ProjectSettings/DynamicsManager.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/EditorBuildSettings.asset b/Example_unity4x/ProjectSettings/EditorBuildSettings.asset deleted file mode 100644 index cb57ef2..0000000 Binary files a/Example_unity4x/ProjectSettings/EditorBuildSettings.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/EditorSettings.asset b/Example_unity4x/ProjectSettings/EditorSettings.asset deleted file mode 100644 index 29b2298..0000000 Binary files a/Example_unity4x/ProjectSettings/EditorSettings.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/GraphicsSettings.asset b/Example_unity4x/ProjectSettings/GraphicsSettings.asset deleted file mode 100644 index 1e9d050..0000000 Binary files a/Example_unity4x/ProjectSettings/GraphicsSettings.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/InputManager.asset b/Example_unity4x/ProjectSettings/InputManager.asset deleted file mode 100644 index 8eaef6b..0000000 Binary files a/Example_unity4x/ProjectSettings/InputManager.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/NavMeshLayers.asset b/Example_unity4x/ProjectSettings/NavMeshLayers.asset deleted file mode 100644 index 68cee17..0000000 Binary files a/Example_unity4x/ProjectSettings/NavMeshLayers.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/NetworkManager.asset b/Example_unity4x/ProjectSettings/NetworkManager.asset deleted file mode 100644 index 4be605e..0000000 Binary files a/Example_unity4x/ProjectSettings/NetworkManager.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/Physics2DSettings.asset b/Example_unity4x/ProjectSettings/Physics2DSettings.asset deleted file mode 100644 index 22d2334..0000000 Binary files a/Example_unity4x/ProjectSettings/Physics2DSettings.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/ProjectSettings.asset b/Example_unity4x/ProjectSettings/ProjectSettings.asset deleted file mode 100644 index 1f31ff9..0000000 Binary files a/Example_unity4x/ProjectSettings/ProjectSettings.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/QualitySettings.asset b/Example_unity4x/ProjectSettings/QualitySettings.asset deleted file mode 100644 index 6ff26e0..0000000 Binary files a/Example_unity4x/ProjectSettings/QualitySettings.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/TagManager.asset b/Example_unity4x/ProjectSettings/TagManager.asset deleted file mode 100644 index 5c4731b..0000000 Binary files a/Example_unity4x/ProjectSettings/TagManager.asset and /dev/null differ diff --git a/Example_unity4x/ProjectSettings/TimeManager.asset b/Example_unity4x/ProjectSettings/TimeManager.asset deleted file mode 100644 index 253e5e3..0000000 Binary files a/Example_unity4x/ProjectSettings/TimeManager.asset and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so b/Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so deleted file mode 100644 index d69ba56..0000000 Binary files a/Example_unity5/Assets/Plugins/Android/libs/armeabi-v7a/libsqlite3.so and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/Android/libs/x86/libsqlite3.so b/Example_unity5/Assets/Plugins/Android/libs/x86/libsqlite3.so deleted file mode 100644 index d4d1203..0000000 Binary files a/Example_unity5/Assets/Plugins/Android/libs/x86/libsqlite3.so and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/SQLite4Unity3d.dll b/Example_unity5/Assets/Plugins/SQLite4Unity3d.dll deleted file mode 100644 index 98c63de..0000000 Binary files a/Example_unity5/Assets/Plugins/SQLite4Unity3d.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/SQLite4Unity3d.dll.meta b/Example_unity5/Assets/Plugins/SQLite4Unity3d.dll.meta deleted file mode 100644 index 7afcff0..0000000 --- a/Example_unity5/Assets/Plugins/SQLite4Unity3d.dll.meta +++ /dev/null @@ -1,20 +0,0 @@ -fileFormatVersion: 2 -guid: c57e702971126e04ba60cbebd69ea13f -timeCreated: 1445131379 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 1 - settings: {} - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll b/Example_unity5/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll deleted file mode 100644 index fcd68f8..0000000 Binary files a/Example_unity5/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll.meta b/Example_unity5/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll.meta deleted file mode 100644 index 3d29516..0000000 --- a/Example_unity5/Assets/Plugins/WP8/ARM/SQLite4Unity3d.dll.meta +++ /dev/null @@ -1,24 +0,0 @@ -fileFormatVersion: 2 -guid: d40f23fcaadafff4c9c4043e7acdd3a8 -timeCreated: 1445131379 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 0 - settings: {} - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - WP8: - enabled: 1 - settings: - CPU: ARM - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.dll b/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.dll deleted file mode 100644 index 4b214ef..0000000 Binary files a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.dll.meta b/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.dll.meta deleted file mode 100644 index f3df819..0000000 --- a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.dll.meta +++ /dev/null @@ -1,16 +0,0 @@ -fileFormatVersion: 2 -guid: 50cb3996c8176fa45b2bb0bd97fc94bf -timeCreated: 1445131383 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 1 - settings: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.winmd b/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.winmd deleted file mode 100644 index aa03ff2..0000000 Binary files a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.winmd and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.winmd.meta b/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.winmd.meta deleted file mode 100644 index e12cda6..0000000 --- a/Example_unity5/Assets/Plugins/WP8/ARM/Sqlite.winmd.meta +++ /dev/null @@ -1,24 +0,0 @@ -fileFormatVersion: 2 -guid: 3da9870ad177ea74196b021d5e18b0e2 -timeCreated: 1445131378 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 0 - settings: {} - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - WP8: - enabled: 1 - settings: - CPU: ARM - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/README_Unity_4x.md b/Example_unity5/Assets/Plugins/WP8/README_Unity_4x.md deleted file mode 100644 index 4fc9d88..0000000 --- a/Example_unity5/Assets/Plugins/WP8/README_Unity_4x.md +++ /dev/null @@ -1,12 +0,0 @@ -For this to work properly you will have to do some extra work. -It seems that Unity 4.x is not recognizing the folder structure when creating the WP8 project and it will use the x86 dlls by default. If you try to override them in your recently created solution it will compile but when you try to run it it wont work and you will recibe an error similar to this: -'Could not load type 'UnityEngine.Internal.$Metadata[..]' - -You will have to follow these steps: -1. In your Unity project, remove the WP/x86 folder. -2. Put the content of the WP/ARM folder into WP and remove WP/ARM folder. -3. Generate the project. -4. Add the following references: - - sqlite.winmd (directly in the root) - - SQLite for Windows Phone (Windows Phone/Extensions in your reference manager. You will have to download this with TOOLS > Extensions and Updates in your VS ) -5. You're ready to go! diff --git a/Example_unity5/Assets/Plugins/WP8/README_Unity_4x.md.meta b/Example_unity5/Assets/Plugins/WP8/README_Unity_4x.md.meta deleted file mode 100644 index 82458f7..0000000 --- a/Example_unity5/Assets/Plugins/WP8/README_Unity_4x.md.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f00e79c1cf79a204da20dd82bfad1ef7 -timeCreated: 1445131378 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/README_Unity_5.md b/Example_unity5/Assets/Plugins/WP8/README_Unity_5.md deleted file mode 100644 index bda5359..0000000 --- a/Example_unity5/Assets/Plugins/WP8/README_Unity_5.md +++ /dev/null @@ -1,14 +0,0 @@ -For this to work properly you will have to do some extra work. - -You will have to follow these steps: -0. If you're targeting a the emulator an not a real device, then when it says WP/x86 you must read WP/ARM and the other way around. i.e. 1-5 is written considering you want to deploy to a real device. -1. In your Unity project's Plugin inspector, remove the WP/x86 folder items from the WP8Player. -2. Select the content of the WP/ARM folder and in the Plugin Inspector check "Don't process" and set them for WP8Player. -3. Make sure that the SQLite4Unity3d.dll in your plugin folder contains a placeholder to Assets/Plugins/SQLite4Unity3d.dll -4. Generate the project. -5. If you receive any error, go to Assets/Plugins/SQLite4Unity3d, check "Don't process" and set the architecture to the opposite you wan't to build for (i.e. if you aim for ARM then x86) -6. Add the following references: - - sqlite.winmd (if you already have a sqlite reference in your project check it's the correct one in terms of architecture) - - SQLite4Unity3d.dll (maybe your project already has this reference but don't forget to check the architecture) - - SQLite for Windows Phone (Windows Phone/Extensions in your reference manager. You will have to download this with TOOLS > Extensions and Updates in your VS ) -7. You're ready to go! diff --git a/Example_unity5/Assets/Plugins/WP8/README_Unity_5.md.meta b/Example_unity5/Assets/Plugins/WP8/README_Unity_5.md.meta deleted file mode 100644 index 74f4bb7..0000000 --- a/Example_unity5/Assets/Plugins/WP8/README_Unity_5.md.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 5d78def155d6fec4092b5fed2fb5c5c3 -timeCreated: 1445131378 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll b/Example_unity5/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll deleted file mode 100644 index 2c39578..0000000 Binary files a/Example_unity5/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll.meta b/Example_unity5/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll.meta deleted file mode 100644 index 603a160..0000000 --- a/Example_unity5/Assets/Plugins/WP8/x86/SQLite4Unity3d.dll.meta +++ /dev/null @@ -1,24 +0,0 @@ -fileFormatVersion: 2 -guid: d7599e594e7819641b3803b0a0bc8660 -timeCreated: 1445131380 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 0 - settings: {} - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - WP8: - enabled: 1 - settings: - CPU: x86 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.dll b/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.dll deleted file mode 100644 index 9058eb4..0000000 Binary files a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.dll.meta b/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.dll.meta deleted file mode 100644 index f32c2ac..0000000 --- a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.dll.meta +++ /dev/null @@ -1,16 +0,0 @@ -fileFormatVersion: 2 -guid: 20cf067006d30a6448deeca3cf3d93ad -timeCreated: 1445131383 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 1 - settings: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.winmd b/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.winmd deleted file mode 100644 index 46466bc..0000000 Binary files a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.winmd and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.winmd.meta b/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.winmd.meta deleted file mode 100644 index 63b1302..0000000 --- a/Example_unity5/Assets/Plugins/WP8/x86/Sqlite.winmd.meta +++ /dev/null @@ -1,24 +0,0 @@ -fileFormatVersion: 2 -guid: 55076fd7c6c077b4fbc230091536f04a -timeCreated: 1445131378 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 0 - settings: {} - Editor: - enabled: 0 - settings: - DefaultValueInitialized: true - WP8: - enabled: 1 - settings: - CPU: x86 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/x64/sqlite3.dll b/Example_unity5/Assets/Plugins/x64/sqlite3.dll deleted file mode 100644 index 6f07d5e..0000000 Binary files a/Example_unity5/Assets/Plugins/x64/sqlite3.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/x64/sqlite3.dll.meta b/Example_unity5/Assets/Plugins/x64/sqlite3.dll.meta deleted file mode 100644 index 2807d93..0000000 --- a/Example_unity5/Assets/Plugins/x64/sqlite3.dll.meta +++ /dev/null @@ -1,16 +0,0 @@ -fileFormatVersion: 2 -guid: a3fee75616c5ab0449e841e6fc8a5172 -timeCreated: 1445131383 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 1 - settings: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/Plugins/x86/sqlite3.dll b/Example_unity5/Assets/Plugins/x86/sqlite3.dll deleted file mode 100644 index 4cd5a11..0000000 Binary files a/Example_unity5/Assets/Plugins/x86/sqlite3.dll and /dev/null differ diff --git a/Example_unity5/Assets/Plugins/x86/sqlite3.dll.meta b/Example_unity5/Assets/Plugins/x86/sqlite3.dll.meta deleted file mode 100644 index 06435af..0000000 --- a/Example_unity5/Assets/Plugins/x86/sqlite3.dll.meta +++ /dev/null @@ -1,16 +0,0 @@ -fileFormatVersion: 2 -guid: 34afd3dfc3051f3438965ecf7bd8c8df -timeCreated: 1445131383 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - platformData: - Any: - enabled: 1 - settings: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/Assets/StreamingAssets/tempDatabase.db b/Example_unity5/Assets/StreamingAssets/tempDatabase.db deleted file mode 100644 index 9537b0d..0000000 Binary files a/Example_unity5/Assets/StreamingAssets/tempDatabase.db and /dev/null differ diff --git a/Example_unity5/Assets/StreamingAssets/tempDatabase.db.meta b/Example_unity5/Assets/StreamingAssets/tempDatabase.db.meta deleted file mode 100644 index e6c516d..0000000 --- a/Example_unity5/Assets/StreamingAssets/tempDatabase.db.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 60a22dcc5539cce40955b26e61e7601a -timeCreated: 1445208111 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/Example_unity5/ProjectSettings/AudioManager.asset b/Example_unity5/ProjectSettings/AudioManager.asset deleted file mode 100644 index 850a4f9..0000000 Binary files a/Example_unity5/ProjectSettings/AudioManager.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/DynamicsManager.asset b/Example_unity5/ProjectSettings/DynamicsManager.asset deleted file mode 100644 index 563a3a0..0000000 Binary files a/Example_unity5/ProjectSettings/DynamicsManager.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/EditorBuildSettings.asset b/Example_unity5/ProjectSettings/EditorBuildSettings.asset deleted file mode 100644 index 570ecd3..0000000 Binary files a/Example_unity5/ProjectSettings/EditorBuildSettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/EditorSettings.asset b/Example_unity5/ProjectSettings/EditorSettings.asset deleted file mode 100644 index 539bf93..0000000 Binary files a/Example_unity5/ProjectSettings/EditorSettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/GraphicsSettings.asset b/Example_unity5/ProjectSettings/GraphicsSettings.asset deleted file mode 100644 index 20f231a..0000000 Binary files a/Example_unity5/ProjectSettings/GraphicsSettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/InputManager.asset b/Example_unity5/ProjectSettings/InputManager.asset deleted file mode 100644 index f88841d..0000000 Binary files a/Example_unity5/ProjectSettings/InputManager.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/NavMeshAreas.asset b/Example_unity5/ProjectSettings/NavMeshAreas.asset deleted file mode 100644 index 72481a5..0000000 Binary files a/Example_unity5/ProjectSettings/NavMeshAreas.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/NetworkManager.asset b/Example_unity5/ProjectSettings/NetworkManager.asset deleted file mode 100644 index eb205e0..0000000 Binary files a/Example_unity5/ProjectSettings/NetworkManager.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/Physics2DSettings.asset b/Example_unity5/ProjectSettings/Physics2DSettings.asset deleted file mode 100644 index cf3a1bf..0000000 Binary files a/Example_unity5/ProjectSettings/Physics2DSettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/ProjectSettings.asset b/Example_unity5/ProjectSettings/ProjectSettings.asset deleted file mode 100644 index 9fb0615..0000000 Binary files a/Example_unity5/ProjectSettings/ProjectSettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/ProjectVersion.txt b/Example_unity5/ProjectSettings/ProjectVersion.txt deleted file mode 100644 index 8a062e6..0000000 --- a/Example_unity5/ProjectSettings/ProjectVersion.txt +++ /dev/null @@ -1,2 +0,0 @@ -m_EditorVersion: 5.2.1f1 -m_StandardAssetsVersion: 0 diff --git a/Example_unity5/ProjectSettings/QualitySettings.asset b/Example_unity5/ProjectSettings/QualitySettings.asset deleted file mode 100644 index b7b6c19..0000000 Binary files a/Example_unity5/ProjectSettings/QualitySettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/TagManager.asset b/Example_unity5/ProjectSettings/TagManager.asset deleted file mode 100644 index 761f435..0000000 Binary files a/Example_unity5/ProjectSettings/TagManager.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/TimeManager.asset b/Example_unity5/ProjectSettings/TimeManager.asset deleted file mode 100644 index decdb13..0000000 Binary files a/Example_unity5/ProjectSettings/TimeManager.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/UnityAdsSettings.asset b/Example_unity5/ProjectSettings/UnityAdsSettings.asset deleted file mode 100644 index 2d1d81b..0000000 Binary files a/Example_unity5/ProjectSettings/UnityAdsSettings.asset and /dev/null differ diff --git a/Example_unity5/ProjectSettings/UnityAnalyticsManager.asset b/Example_unity5/ProjectSettings/UnityAnalyticsManager.asset deleted file mode 100644 index e52c94d..0000000 Binary files a/Example_unity5/ProjectSettings/UnityAnalyticsManager.asset and /dev/null differ diff --git a/Plugins.zip b/Plugins.zip deleted file mode 100644 index b3dced5..0000000 Binary files a/Plugins.zip and /dev/null differ diff --git a/Plugins/Android/libs/armeabi-v7a/libsqlite3.so b/Plugins/Android/libs/armeabi-v7a/libsqlite3.so deleted file mode 100644 index d69ba56..0000000 Binary files a/Plugins/Android/libs/armeabi-v7a/libsqlite3.so and /dev/null differ diff --git a/Plugins/Android/libs/x86/libsqlite3.so b/Plugins/Android/libs/x86/libsqlite3.so deleted file mode 100644 index d4d1203..0000000 Binary files a/Plugins/Android/libs/x86/libsqlite3.so and /dev/null differ diff --git a/Plugins/SQLite4Unity3d.dll b/Plugins/SQLite4Unity3d.dll deleted file mode 100644 index 98c63de..0000000 Binary files a/Plugins/SQLite4Unity3d.dll and /dev/null differ diff --git a/Plugins/WP8/ARM/SQLite4Unity3d.dll b/Plugins/WP8/ARM/SQLite4Unity3d.dll deleted file mode 100644 index fcd68f8..0000000 Binary files a/Plugins/WP8/ARM/SQLite4Unity3d.dll and /dev/null differ diff --git a/Plugins/WP8/ARM/Sqlite.dll b/Plugins/WP8/ARM/Sqlite.dll deleted file mode 100644 index 4b214ef..0000000 Binary files a/Plugins/WP8/ARM/Sqlite.dll and /dev/null differ diff --git a/Plugins/WP8/ARM/Sqlite.winmd b/Plugins/WP8/ARM/Sqlite.winmd deleted file mode 100644 index aa03ff2..0000000 Binary files a/Plugins/WP8/ARM/Sqlite.winmd and /dev/null differ diff --git a/Plugins/WP8/README_Unity_4x.txt b/Plugins/WP8/README_Unity_4x.txt deleted file mode 100644 index 52a341a..0000000 --- a/Plugins/WP8/README_Unity_4x.txt +++ /dev/null @@ -1,13 +0,0 @@ -For this to work properly you will have to do some extra work. -It seems that Unity 4.x is not recognizing the folder structure when creating the WP8 project and it will use the x86 dlls by default. If you try to override them in your recently created solution it will compile but when you try to run it it wont work and you will recibe an error similar to this: -'Could not load type 'UnityEngine.Internal.$Metadata[..]' - -You will have to follow these steps: -0. If you're targeting a the emulator an not a real device, then when it says WP/x86 you must read WP/ARM and the other way around. i.e. 1-5 is written considering you want to deploy to a real device. -1. In your Unity project, remove the WP/x86 folder. -2. Put the content of the WP/ARM folder into WP and remove WP/ARM folder. -3. Generate the project. -4. Add the following references: - - sqlite.winmd (directly in the root) - - SQLite for Windows Phone (Windows Phone/Extensions in your reference manager. You will have to download this with TOOLS > Extensions and Updates in your VS ) -5. You're ready to go! \ No newline at end of file diff --git a/Plugins/WP8/README_Unity_5.txt b/Plugins/WP8/README_Unity_5.txt deleted file mode 100644 index b7fb9b9..0000000 --- a/Plugins/WP8/README_Unity_5.txt +++ /dev/null @@ -1,13 +0,0 @@ -For this to work properly you will have to do some extra work. - -You will have to follow these steps: -0. If you're targeting a the emulator an not a real device, then when it says WP/x86 you must read WP/ARM and the other way around. i.e. 1-5 is written considering you want to deploy to a real device. -1. In your Unity project's Plugin inspector, remove the WP/x86 folder items from the WP8Player. -2. Select the content of the WP/ARM folder and in the Plugin Inspector check "Don't process" and set them for WP8Player. -3. Make sure that the SQLite4Unity3d.dll in your plugin folder contains a placeholder to Assets/Plugins/SQLite4Unity3d.dll -3. Generate the project. -4. Add the following references: - - sqlite.winmd (if you already have a sqlite reference in your project check it's the correct one in terms of architecture) - - SQLite4Unity3d.dll (maybe your project already has this reference but don't forget to check the architecture) - - SQLite for Windows Phone (Windows Phone/Extensions in your reference manager. You will have to download this with TOOLS > Extensions and Updates in your VS ) -5. You're ready to go! \ No newline at end of file diff --git a/Plugins/WP8/x86/SQLite4Unity3d.dll b/Plugins/WP8/x86/SQLite4Unity3d.dll deleted file mode 100644 index 2c39578..0000000 Binary files a/Plugins/WP8/x86/SQLite4Unity3d.dll and /dev/null differ diff --git a/Plugins/WP8/x86/Sqlite.dll b/Plugins/WP8/x86/Sqlite.dll deleted file mode 100644 index 9058eb4..0000000 Binary files a/Plugins/WP8/x86/Sqlite.dll and /dev/null differ diff --git a/Plugins/WP8/x86/Sqlite.winmd b/Plugins/WP8/x86/Sqlite.winmd deleted file mode 100644 index 46466bc..0000000 Binary files a/Plugins/WP8/x86/Sqlite.winmd and /dev/null differ diff --git a/Plugins/x64/sqlite3.dll b/Plugins/x64/sqlite3.dll deleted file mode 100644 index 6f07d5e..0000000 Binary files a/Plugins/x64/sqlite3.dll and /dev/null differ diff --git a/Plugins/x86/sqlite3.dll b/Plugins/x86/sqlite3.dll deleted file mode 100644 index 4cd5a11..0000000 Binary files a/Plugins/x86/sqlite3.dll and /dev/null differ diff --git a/README.md b/README.md index c9f4bf5..56d1e38 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ # What's this? When I started with Unity3d development I needed to use SQLite in my project and it was very hard to me to find a place with simple instructions on how to make it work. All I got were links to paid solutions on the Unity3d's Assets Store and a lot of different and complicated tutorials. -At the end, I decided that there should be a simpler way and I created **SQLite4Unity3d**, a library that helps you to use SQLite in your Unity3d projects in a clear and easy way and works in **iOS, Android and Windows Phone** projects. +At the end, I decided that there should be a simpler way and I created **SQLite4Unity3d**, a plugin that helps you to use SQLite in your Unity3d projects in a clear and easy way and works in **iOS, Mac, Android and Windows** projects. -Besides that, it uses the great [sqlite-net](https://github.com/praeclarum/sqlite-net) library as a base so you will have **Linq besides sql**. For a further reference on what possibilities you have available with this library I encourage you to visit [its github repository](https://github.com/praeclarum/sqlite-net). +It uses the great [sqlite-net](https://github.com/praeclarum/sqlite-net) library as a base so you will have **Linq besides sql**. For a further reference on what possibilities you have available with this library I encourage you to visit [its github repository](https://github.com/praeclarum/sqlite-net). *Note: _SQLite4Unity3d uses only the synchronous part of sqlite-net, so all the calls to the database are synchronous._ @@ -15,18 +15,30 @@ If you want to know more about why I created this plugin you can read more [here # The fast track All you have to do to start using it in your project: -1. [Download this zip](https://github.com/codecoding/SQLite4Unity3d/raw/master/Plugins.zip) and **copy the resulting folder to your Assets/Plugins folder**. It contains the dlls that Unity3d will need to access sqlite. -2. Don’t forget to **copy your SQLite database file in your Assets/StreamingAssets folder if you’re shipping one**. -3. **You’re done!** Now you can get access to your database using sqlite-net. ;P +1. [Download this zip](https://github.com/codecoding/SQLite4Unity3d/raw/master/SQLite4Unity3d.zip), extract its content and **copy the resulting folder to your Assets/Plugins folder**. It contains the dlls that Unity3d will need to access sqlite. +2. **Copy the SQLite.cs** file into your scripts folder. +3. Don’t forget to **copy your SQLite database file in your Assets/StreamingAssets folder if you’re shipping one**. +4. **You’re done!** Now you can get access to your database using sqlite-net. ;P # Example -If you want to try it I've uploaded a small example that you will be able to find in the "Example" folder. Download the folder and open it with Unity3d to give it a try. You will notice that I've placed a specific example for Unity 4.x and Unity 5. +If you want to try it I've uploaded a small example that you will be able to find in the "Example" folder. Download the folder and open it with Unity3d to give it a try. It contains classes that will help you to start. + +## Android particularities +Android configuration and deployment is very straight forward. Take a look at the **following video** if you want to get a picture on how to proceed: + +UWP # iOS particularities As you may know **iOS doesn't allow JIT compilation** so, generally speaking, you will have to be very careful when you use **reflection** in your code. For a more deeper explanation of this issue please refer to Google but making it short: you cannot create dynamic objects using reflection. How is this affecting SQLite4Unity3d? Well, prior to this version you couldn't use very complicated queries. Now, **for basic queries you will have iOS support**. In case you stumble uppon a JIT compilation error it's time to use the old sql syntax. -# Plugins in several platforms -In general you won't find any issues with Android and iOS. When you start deploying your **WP version**, please take a look at the **readme files inside the plugins folder**. They will help you make it work without problems. +Check this video to know how to proceed with iOS deployment: + +UWP + +# Windows particularities +In general you won't find any issues with Android and iOS. For **Windows versions**, please take a look at the **the video below** for more details on how to proceed: + +UWP # Acknowledgements This project is based on the work of: diff --git a/SQLite4Unity3d.zip b/SQLite4Unity3d.zip new file mode 100644 index 0000000..d4452c2 Binary files /dev/null and b/SQLite4Unity3d.zip differ diff --git a/SQLite4Unity3d/SQLite4Unity3d.sln b/SQLite4Unity3d/SQLite4Unity3d.sln deleted file mode 100644 index eb8b984..0000000 --- a/SQLite4Unity3d/SQLite4Unity3d.sln +++ /dev/null @@ -1,44 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite4Unity3d", "SQLite4Unity3d\SQLite4Unity3d.csproj", "{73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite4Unity3dWP8", "SQLite4Unity3dWP8\SQLite4Unity3dWP8.csproj", "{DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Debug|ARM.ActiveCfg = Debug|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Debug|x86.ActiveCfg = Debug|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Release|Any CPU.Build.0 = Release|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Release|ARM.ActiveCfg = Release|Any CPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C}.Release|x86.ActiveCfg = Release|Any CPU - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Debug|ARM.ActiveCfg = Debug|ARM - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Debug|ARM.Build.0 = Debug|ARM - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Debug|x86.ActiveCfg = Debug|x86 - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Debug|x86.Build.0 = Debug|x86 - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Release|Any CPU.ActiveCfg = Release|x86 - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Release|Any CPU.Build.0 = Release|x86 - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Release|ARM.ActiveCfg = Release|ARM - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Release|ARM.Build.0 = Release|ARM - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Release|x86.ActiveCfg = Release|x86 - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/SQLite4Unity3d/SQLite4Unity3d.userprefs b/SQLite4Unity3d/SQLite4Unity3d.userprefs deleted file mode 100644 index 8a063db..0000000 --- a/SQLite4Unity3d/SQLite4Unity3d.userprefs +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3d.v11.suo b/SQLite4Unity3d/SQLite4Unity3d.v11.suo deleted file mode 100644 index 6c68a2f..0000000 Binary files a/SQLite4Unity3d/SQLite4Unity3d.v11.suo and /dev/null differ diff --git a/SQLite4Unity3d/SQLite4Unity3d.v12.suo b/SQLite4Unity3d/SQLite4Unity3d.v12.suo deleted file mode 100644 index eb5ca5e..0000000 Binary files a/SQLite4Unity3d/SQLite4Unity3d.v12.suo and /dev/null differ diff --git a/SQLite4Unity3d/SQLite4Unity3d/Properties/AssemblyInfo.cs b/SQLite4Unity3d/SQLite4Unity3d/Properties/AssemblyInfo.cs deleted file mode 100644 index 730cf70..0000000 --- a/SQLite4Unity3d/SQLite4Unity3d/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SQLite4Unity3d")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SQLite4Unity3d")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("77675504-8d6d-475c-9054-4d3ea1bcf275")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: NeutralResourcesLanguageAttribute("en-US")] diff --git a/SQLite4Unity3d/SQLite4Unity3d/SQLite4Unity3d.csproj b/SQLite4Unity3d/SQLite4Unity3d/SQLite4Unity3d.csproj deleted file mode 100644 index 8b5933d..0000000 --- a/SQLite4Unity3d/SQLite4Unity3d/SQLite4Unity3d.csproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - - Debug - AnyCPU - {73A034D8-0D4D-410F-AEE2-64DB1C9EFE3C} - Library - Properties - SQLite4Unity3d - SQLite4Unity3d - v3.5 - 512 - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3d/SQLite4Unity3d.csproj.user b/SQLite4Unity3d/SQLite4Unity3d/SQLite4Unity3d.csproj.user deleted file mode 100644 index fe7dc22..0000000 --- a/SQLite4Unity3d/SQLite4Unity3d/SQLite4Unity3d.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ShowAllFiles - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3d/packages.config b/SQLite4Unity3d/SQLite4Unity3d/packages.config deleted file mode 100644 index 7030e31..0000000 --- a/SQLite4Unity3d/SQLite4Unity3d/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/Lib/Community.CsharpSqlite.WP7.dll b/SQLite4Unity3d/SQLite4Unity3dWP8/Lib/Community.CsharpSqlite.WP7.dll deleted file mode 100644 index 80a162f..0000000 Binary files a/SQLite4Unity3d/SQLite4Unity3dWP8/Lib/Community.CsharpSqlite.WP7.dll and /dev/null differ diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/Properties/AssemblyInfo.cs b/SQLite4Unity3d/SQLite4Unity3dWP8/Properties/AssemblyInfo.cs deleted file mode 100644 index 2dd2206..0000000 --- a/SQLite4Unity3d/SQLite4Unity3dWP8/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SQLite4Unity3dWP8")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SQLite4Unity3dWP8")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("dff95d7b-03ad-4627-bbb8-38a2ead07aa0")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: NeutralResourcesLanguageAttribute("en-US")] diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite.cs b/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite.cs deleted file mode 100644 index 0ddd103..0000000 --- a/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite.cs +++ /dev/null @@ -1,3278 +0,0 @@ -// -// Copyright (c) 2009-2012 Krueger Systems, 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. -// -#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE -#define USE_CSHARP_SQLITE -#endif - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Collections.Generic; -using System.Reflection; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; - -#if USE_CSHARP_SQLITE -using Sqlite3 = Community.CsharpSqlite.Sqlite3; -using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3; -using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe; -#elif USE_WP8_NATIVE_SQLITE -using Sqlite3 = Sqlite.Sqlite3; -using Sqlite3DatabaseHandle = Sqlite.Database; -using Sqlite3Statement = Sqlite.Statement; -#else -using Sqlite3DatabaseHandle = System.IntPtr; -using Sqlite3Statement = System.IntPtr; -#endif - -namespace SQLite4Unity3d -{ - public class SQLiteException : Exception - { - public SQLite3.Result Result { get; private set; } - - protected SQLiteException (SQLite3.Result r,string message) : base(message) - { - Result = r; - } - - public static SQLiteException New (SQLite3.Result r, string message) - { - return new SQLiteException (r, message); - } - } - - public class NotNullConstraintViolationException : SQLiteException - { - public IEnumerable Columns { get; protected set; } - - protected NotNullConstraintViolationException (SQLite3.Result r, string message) - : this (r, message, null, null) - { - - } - - protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj) - : base (r, message) - { - if (mapping != null && obj != null) { - this.Columns = from c in mapping.Columns - where c.IsNullable == false && c.GetValue (obj) == null - select c; - } - } - - public static new NotNullConstraintViolationException New (SQLite3.Result r, string message) - { - return new NotNullConstraintViolationException (r, message); - } - - public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj) - { - return new NotNullConstraintViolationException (r, message, mapping, obj); - } - - public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj) - { - return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj); - } - } - - [Flags] - public enum SQLiteOpenFlags { - ReadOnly = 1, ReadWrite = 2, Create = 4, - NoMutex = 0x8000, FullMutex = 0x10000, - SharedCache = 0x20000, PrivateCache = 0x40000, - ProtectionComplete = 0x00100000, - ProtectionCompleteUnlessOpen = 0x00200000, - ProtectionCompleteUntilFirstUserAuthentication = 0x00300000, - ProtectionNone = 0x00400000 - } - - [Flags] - public enum CreateFlags - { - None = 0, - ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName) - ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix) - AllImplicit = 3, // do both above - - AutoIncPK = 4 // force PK field to be auto inc - } - - /// - /// Represents an open connection to a SQLite database. - /// - public partial class SQLiteConnection : IDisposable - { - private bool _open; - private TimeSpan _busyTimeout; - private Dictionary _mappings = null; - private Dictionary _tables = null; - private System.Diagnostics.Stopwatch _sw; - private long _elapsedMilliseconds = 0; - - private int _transactionDepth = 0; - private Random _rand = new Random (); - - public Sqlite3DatabaseHandle Handle { get; private set; } - internal static readonly Sqlite3DatabaseHandle NullHandle = default(Sqlite3DatabaseHandle); - - public string DatabasePath { get; private set; } - - public bool TimeExecution { get; set; } - - public bool Trace { get; set; } - - public bool StoreDateTimeAsTicks { get; private set; } - - /// - /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. - /// - /// - /// Specifies the path to the database file. - /// - /// - /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You - /// absolutely do want to store them as Ticks in all new projects. The default of false is - /// only here for backwards compatibility. There is a *significant* speed advantage, with no - /// down sides, when setting storeDateTimeAsTicks = true. - /// - public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false) - : this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) - { - } - - /// - /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. - /// - /// - /// Specifies the path to the database file. - /// - /// - /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You - /// absolutely do want to store them as Ticks in all new projects. The default of false is - /// only here for backwards compatibility. There is a *significant* speed advantage, with no - /// down sides, when setting storeDateTimeAsTicks = true. - /// - public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false) - { - if (string.IsNullOrEmpty (databasePath)) - throw new ArgumentException ("Must be specified", "databasePath"); - - DatabasePath = databasePath; - -#if NETFX_CORE - SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path); -#endif - - Sqlite3DatabaseHandle handle; - -#if SILVERLIGHT || USE_CSHARP_SQLITE - var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero); -#else - // open using the byte[] - // in the case where the path may include Unicode - // force open to using UTF-8 using sqlite3_open_v2 - var databasePathAsBytes = GetNullTerminatedUtf8 (DatabasePath); - var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero); -#endif - - Handle = handle; - if (r != SQLite3.Result.OK) { - throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r)); - } - _open = true; - - StoreDateTimeAsTicks = storeDateTimeAsTicks; - - BusyTimeout = TimeSpan.FromSeconds (0.1); - } - - static SQLiteConnection () - { - if (_preserveDuringLinkMagic) { - var ti = new ColumnInfo (); - ti.Name = "magic"; - } - } - - public void EnableLoadExtension(int onoff) - { - SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff); - if (r != SQLite3.Result.OK) { - string msg = SQLite3.GetErrmsg (Handle); - throw SQLiteException.New (r, msg); - } - } - - static byte[] GetNullTerminatedUtf8 (string s) - { - var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s); - var bytes = new byte [utf8Length + 1]; - utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); - return bytes; - } - - /// - /// Used to list some code that we want the MonoTouch linker - /// to see, but that we never want to actually execute. - /// - static bool _preserveDuringLinkMagic; - - /// - /// Sets a busy handler to sleep the specified amount of time when a table is locked. - /// The handler will sleep multiple times until a total time of has accumulated. - /// - public TimeSpan BusyTimeout { - get { return _busyTimeout; } - set { - _busyTimeout = value; - if (Handle != NullHandle) { - SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds); - } - } - } - - /// - /// Returns the mappings from types to tables that the connection - /// currently understands. - /// - public IEnumerable TableMappings { - get { - return _tables != null ? _tables.Values : Enumerable.Empty (); - } - } - - /// - /// Retrieves the mapping that is automatically generated for the given type. - /// - /// - /// The type whose mapping to the database is returned. - /// - /// - /// Optional flags allowing implicit PK and indexes based on naming conventions - /// - /// - /// The mapping represents the schema of the columns of the database and contains - /// methods to set and get properties of objects. - /// - public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) - { - if (_mappings == null) { - _mappings = new Dictionary (); - } - TableMapping map; - if (!_mappings.TryGetValue (type.FullName, out map)) { - map = new TableMapping (type, createFlags); - _mappings [type.FullName] = map; - } - return map; - } - - /// - /// Retrieves the mapping that is automatically generated for the given type. - /// - /// - /// The mapping represents the schema of the columns of the database and contains - /// methods to set and get properties of objects. - /// - public TableMapping GetMapping () - { - return GetMapping (typeof (T)); - } - - private struct IndexedColumn - { - public int Order; - public string ColumnName; - } - - private struct IndexInfo - { - public string IndexName; - public string TableName; - public bool Unique; - public List Columns; - } - - /// - /// Executes a "drop table" on the database. This is non-recoverable. - /// - public int DropTable() - { - var map = GetMapping (typeof (T)); - - var query = string.Format("drop table if exists \"{0}\"", map.TableName); - - return Execute (query); - } - - /// - /// Executes a "create table if not exists" on the database. It also - /// creates any specified indexes on the columns of the table. It uses - /// a schema automatically generated from the specified type. You can - /// later access this schema by calling GetMapping. - /// - /// - /// The number of entries added to the database schema. - /// - public int CreateTable(CreateFlags createFlags = CreateFlags.None) - { - return CreateTable(typeof (T), createFlags); - } - - /// - /// Executes a "create table if not exists" on the database. It also - /// creates any specified indexes on the columns of the table. It uses - /// a schema automatically generated from the specified type. You can - /// later access this schema by calling GetMapping. - /// - /// Type to reflect to a database table. - /// Optional flags allowing implicit PK and indexes based on naming conventions. - /// - /// The number of entries added to the database schema. - /// - public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) - { - if (_tables == null) { - _tables = new Dictionary (); - } - TableMapping map; - if (!_tables.TryGetValue (ty.FullName, out map)) { - map = GetMapping (ty, createFlags); - _tables.Add (ty.FullName, map); - } - var query = "create table if not exists \"" + map.TableName + "\"(\n"; - - var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks)); - var decl = string.Join (",\n", decls.ToArray ()); - query += decl; - query += ")"; - - var count = Execute (query); - - if (count == 0) { //Possible bug: This always seems to return 0? - // Table already exists, migrate it - MigrateTable (map); - } - - var indexes = new Dictionary (); - foreach (var c in map.Columns) { - foreach (var i in c.Indices) { - var iname = i.Name ?? map.TableName + "_" + c.Name; - IndexInfo iinfo; - if (!indexes.TryGetValue (iname, out iinfo)) { - iinfo = new IndexInfo { - IndexName = iname, - TableName = map.TableName, - Unique = i.Unique, - Columns = new List () - }; - indexes.Add (iname, iinfo); - } - - if (i.Unique != iinfo.Unique) - throw new Exception ("All the columns in an index must have the same value for their Unique property"); - - iinfo.Columns.Add (new IndexedColumn { - Order = i.Order, - ColumnName = c.Name - }); - } - } - - foreach (var indexName in indexes.Keys) { - var index = indexes[indexName]; - var columns = index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray(); - count += CreateIndex(indexName, index.TableName, columns, index.Unique); - } - - return count; - } - - /// - /// Creates an index for the specified table and columns. - /// - /// Name of the index to create - /// Name of the database table - /// An array of column names to index - /// Whether the index should be unique - public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false) - { - const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; - var sql = String.Format(sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName); - return Execute(sql); - } - - /// - /// Creates an index for the specified table and column. - /// - /// Name of the index to create - /// Name of the database table - /// Name of the column to index - /// Whether the index should be unique - public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) - { - return CreateIndex(indexName, tableName, new string[] { columnName }, unique); - } - - /// - /// Creates an index for the specified table and column. - /// - /// Name of the database table - /// Name of the column to index - /// Whether the index should be unique - public int CreateIndex(string tableName, string columnName, bool unique = false) - { - return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique); - } - - /// - /// Creates an index for the specified table and columns. - /// - /// Name of the database table - /// An array of column names to index - /// Whether the index should be unique - public int CreateIndex(string tableName, string[] columnNames, bool unique = false) - { - return CreateIndex(tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique); - } - - /// - /// Creates an index for the specified object property. - /// e.g. CreateIndex(c => c.Name); - /// - /// Type to reflect to a database table. - /// Property to index - /// Whether the index should be unique - public void CreateIndex(Expression> property, bool unique = false) - { - MemberExpression mx; - if (property.Body.NodeType == ExpressionType.Convert) - { - mx = ((UnaryExpression)property.Body).Operand as MemberExpression; - } - else - { - mx= (property.Body as MemberExpression); - } - var propertyInfo = mx.Member as PropertyInfo; - if (propertyInfo == null) - { - throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); - } - - var propName = propertyInfo.Name; - - var map = GetMapping(); - var colName = map.FindColumnWithPropertyName(propName).Name; - - CreateIndex(map.TableName, colName, unique); - } - - public class ColumnInfo - { -// public int cid { get; set; } - - [Column ("name")] - public string Name { get; set; } - -// [Column ("type")] -// public string ColumnType { get; set; } - - public int notnull { get; set; } - -// public string dflt_value { get; set; } - -// public int pk { get; set; } - - public override string ToString () - { - return Name; - } - } - - public List GetTableInfo (string tableName) - { - var query = "pragma table_info(\"" + tableName + "\")"; - return Query (query); - } - - void MigrateTable (TableMapping map) - { - var existingCols = GetTableInfo (map.TableName); - - var toBeAdded = new List (); - - foreach (var p in map.Columns) { - var found = false; - foreach (var c in existingCols) { - found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0); - if (found) - break; - } - if (!found) { - toBeAdded.Add (p); - } - } - - foreach (var p in toBeAdded) { - var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks); - Execute (addCol); - } - } - - /// - /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class. - /// - /// - protected virtual SQLiteCommand NewCommand () - { - return new SQLiteCommand (this); - } - - /// - /// Creates a new SQLiteCommand given the command text with arguments. Place a '?' - /// in the command text for each of the arguments. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the command text. - /// - /// - /// A - /// - public SQLiteCommand CreateCommand (string cmdText, params object[] ps) - { - if (!_open) - throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database"); - - var cmd = NewCommand (); - cmd.CommandText = cmdText; - foreach (var o in ps) { - cmd.Bind (o); - } - return cmd; - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// Use this method instead of Query when you don't expect rows back. Such cases include - /// INSERTs, UPDATEs, and DELETEs. - /// You can set the Trace or TimeExecution properties of the connection - /// to profile execution. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// The number of rows modified in the database as a result of this execution. - /// - public int Execute (string query, params object[] args) - { - var cmd = CreateCommand (query, args); - - if (TimeExecution) { - if (_sw == null) { - _sw = new Stopwatch (); - } - _sw.Reset (); - _sw.Start (); - } - - var r = cmd.ExecuteNonQuery (); - - if (TimeExecution) { - _sw.Stop (); - _elapsedMilliseconds += _sw.ElapsedMilliseconds; - Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); - } - - return r; - } - - public T ExecuteScalar (string query, params object[] args) - { - var cmd = CreateCommand (query, args); - - if (TimeExecution) { - if (_sw == null) { - _sw = new Stopwatch (); - } - _sw.Reset (); - _sw.Start (); - } - - var r = cmd.ExecuteScalar (); - - if (TimeExecution) { - _sw.Stop (); - _elapsedMilliseconds += _sw.ElapsedMilliseconds; - Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); - } - - return r; - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the mapping automatically generated for - /// the given type. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// - public List Query (string query, params object[] args) where T : new() - { - var cmd = CreateCommand (query, args); - return cmd.ExecuteQuery (); - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the mapping automatically generated for - /// the given type. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// The enumerator will call sqlite3_step on each call to MoveNext, so the database - /// connection must remain open for the lifetime of the enumerator. - /// - public IEnumerable DeferredQuery(string query, params object[] args) where T : new() - { - var cmd = CreateCommand(query, args); - return cmd.ExecuteDeferredQuery(); - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the specified mapping. This function is - /// only used by libraries in order to query the database via introspection. It is - /// normally not used. - /// - /// - /// A to use to convert the resulting rows - /// into objects. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// - public List Query (TableMapping map, string query, params object[] args) - { - var cmd = CreateCommand (query, args); - return cmd.ExecuteQuery (map); - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the specified mapping. This function is - /// only used by libraries in order to query the database via introspection. It is - /// normally not used. - /// - /// - /// A to use to convert the resulting rows - /// into objects. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// The enumerator will call sqlite3_step on each call to MoveNext, so the database - /// connection must remain open for the lifetime of the enumerator. - /// - public IEnumerable DeferredQuery(TableMapping map, string query, params object[] args) - { - var cmd = CreateCommand(query, args); - return cmd.ExecuteDeferredQuery(map); - } - - /// - /// Returns a queryable interface to the table represented by the given type. - /// - /// - /// A queryable object that is able to translate Where, OrderBy, and Take - /// queries into native SQL. - /// - public TableQuery Table () where T : new() - { - return new TableQuery (this); - } - - /// - /// Attempts to retrieve an object with the given primary key from the table - /// associated with the specified type. Use of this method requires that - /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). - /// - /// - /// The primary key. - /// - /// - /// The object with the given primary key. Throws a not found exception - /// if the object is not found. - /// - public T Get (object pk) where T : new() - { - var map = GetMapping (typeof(T)); - return Query (map.GetByPrimaryKeySql, pk).First (); - } - - /// - /// Attempts to retrieve the first object that matches the predicate from the table - /// associated with the specified type. - /// - /// - /// A predicate for which object to find. - /// - /// - /// The object that matches the given predicate. Throws a not found exception - /// if the object is not found. - /// - public T Get (Expression> predicate) where T : new() - { - return Table ().Where (predicate).First (); - } - - /// - /// Attempts to retrieve an object with the given primary key from the table - /// associated with the specified type. Use of this method requires that - /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). - /// - /// - /// The primary key. - /// - /// - /// The object with the given primary key or null - /// if the object is not found. - /// - public T Find (object pk) where T : new () - { - var map = GetMapping (typeof (T)); - return Query (map.GetByPrimaryKeySql, pk).FirstOrDefault (); - } - - /// - /// Attempts to retrieve an object with the given primary key from the table - /// associated with the specified type. Use of this method requires that - /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). - /// - /// - /// The primary key. - /// - /// - /// The TableMapping used to identify the object type. - /// - /// - /// The object with the given primary key or null - /// if the object is not found. - /// - public object Find (object pk, TableMapping map) - { - return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault (); - } - - /// - /// Attempts to retrieve the first object that matches the predicate from the table - /// associated with the specified type. - /// - /// - /// A predicate for which object to find. - /// - /// - /// The object that matches the given predicate or null - /// if the object is not found. - /// - public T Find (Expression> predicate) where T : new() - { - return Table ().Where (predicate).FirstOrDefault (); - } - - /// - /// Whether has been called and the database is waiting for a . - /// - public bool IsInTransaction { - get { return _transactionDepth > 0; } - } - - /// - /// Begins a new transaction. Call to end the transaction. - /// - /// Throws if a transaction has already begun. - public void BeginTransaction () - { - // The BEGIN command only works if the transaction stack is empty, - // or in other words if there are no pending transactions. - // If the transaction stack is not empty when the BEGIN command is invoked, - // then the command fails with an error. - // Rather than crash with an error, we will just ignore calls to BeginTransaction - // that would result in an error. - if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) { - try { - Execute ("begin transaction"); - } catch (Exception ex) { - var sqlExp = ex as SQLiteException; - if (sqlExp != null) { - // It is recommended that applications respond to the errors listed below - // by explicitly issuing a ROLLBACK command. - // TODO: This rollback failsafe should be localized to all throw sites. - switch (sqlExp.Result) { - case SQLite3.Result.IOError: - case SQLite3.Result.Full: - case SQLite3.Result.Busy: - case SQLite3.Result.NoMem: - case SQLite3.Result.Interrupt: - RollbackTo (null, true); - break; - } - } else { - // Call decrement and not VolatileWrite in case we've already - // created a transaction point in SaveTransactionPoint since the catch. - Interlocked.Decrement (ref _transactionDepth); - } - - throw; - } - } else { - // Calling BeginTransaction on an already open transaction is invalid - throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction."); - } - } - - /// - /// Creates a savepoint in the database at the current point in the transaction timeline. - /// Begins a new transaction if one is not in progress. - /// - /// Call to undo transactions since the returned savepoint. - /// Call to commit transactions after the savepoint returned here. - /// Call to end the transaction, committing all changes. - /// - /// A string naming the savepoint. - public string SaveTransactionPoint () - { - int depth = Interlocked.Increment (ref _transactionDepth) - 1; - string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth; - - try { - Execute ("savepoint " + retVal); - } catch (Exception ex) { - var sqlExp = ex as SQLiteException; - if (sqlExp != null) { - // It is recommended that applications respond to the errors listed below - // by explicitly issuing a ROLLBACK command. - // TODO: This rollback failsafe should be localized to all throw sites. - switch (sqlExp.Result) { - case SQLite3.Result.IOError: - case SQLite3.Result.Full: - case SQLite3.Result.Busy: - case SQLite3.Result.NoMem: - case SQLite3.Result.Interrupt: - RollbackTo (null, true); - break; - } - } else { - Interlocked.Decrement (ref _transactionDepth); - } - - throw; - } - - return retVal; - } - - /// - /// Rolls back the transaction that was begun by or . - /// - public void Rollback () - { - RollbackTo (null, false); - } - - /// - /// Rolls back the savepoint created by or SaveTransactionPoint. - /// - /// The name of the savepoint to roll back to, as returned by . If savepoint is null or empty, this method is equivalent to a call to - public void RollbackTo (string savepoint) - { - RollbackTo (savepoint, false); - } - - /// - /// Rolls back the transaction that was begun by . - /// - /// true to avoid throwing exceptions, false otherwise - void RollbackTo (string savepoint, bool noThrow) - { - // Rolling back without a TO clause rolls backs all transactions - // and leaves the transaction stack empty. - try { - if (String.IsNullOrEmpty (savepoint)) { - if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) { - Execute ("rollback"); - } - } else { - DoSavePointExecute (savepoint, "rollback to "); - } - } catch (SQLiteException) { - if (!noThrow) - throw; - - } - // No need to rollback if there are no transactions open. - } - - /// - /// Releases a savepoint returned from . Releasing a savepoint - /// makes changes since that savepoint permanent if the savepoint began the transaction, - /// or otherwise the changes are permanent pending a call to . - /// - /// The RELEASE command is like a COMMIT for a SAVEPOINT. - /// - /// The name of the savepoint to release. The string should be the result of a call to - public void Release (string savepoint) - { - DoSavePointExecute (savepoint, "release "); - } - - void DoSavePointExecute (string savepoint, string cmd) - { - // Validate the savepoint - int firstLen = savepoint.IndexOf ('D'); - if (firstLen >= 2 && savepoint.Length > firstLen + 1) { - int depth; - if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) { - // TODO: Mild race here, but inescapable without locking almost everywhere. - if (0 <= depth && depth < _transactionDepth) { -#if NETFX_CORE - Volatile.Write (ref _transactionDepth, depth); -#elif SILVERLIGHT - _transactionDepth = depth; -#else - Thread.VolatileWrite (ref _transactionDepth, depth); -#endif - Execute (cmd + savepoint); - return; - } - } - } - - throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint"); - } - - /// - /// Commits the transaction that was begun by . - /// - public void Commit () - { - if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) { - Execute ("commit"); - } - // Do nothing on a commit with no open transaction - } - - /// - /// Executes within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an - /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception - /// is rethrown. - /// - /// - /// The to perform within a transaction. can contain any number - /// of operations on the connection but should never call or - /// . - /// - public void RunInTransaction (Action action) - { - try { - var savePoint = SaveTransactionPoint (); - action (); - Release (savePoint); - } catch (Exception) { - Rollback (); - throw; - } - } - - /// - /// Inserts all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// The number of rows added to the table. - /// - public int InsertAll (System.Collections.IEnumerable objects) - { - var c = 0; - RunInTransaction(() => { - foreach (var r in objects) { - c += Insert (r); - } - }); - return c; - } - - /// - /// Inserts all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The number of rows added to the table. - /// - public int InsertAll (System.Collections.IEnumerable objects, string extra) - { - var c = 0; - RunInTransaction (() => { - foreach (var r in objects) { - c += Insert (r, extra); - } - }); - return c; - } - - /// - /// Inserts all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int InsertAll (System.Collections.IEnumerable objects, Type objType) - { - var c = 0; - RunInTransaction (() => { - foreach (var r in objects) { - c += Insert (r, objType); - } - }); - return c; - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj) - { - if (obj == null) { - return 0; - } - return Insert (obj, "", obj.GetType ()); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// If a UNIQUE constraint violation occurs with - /// some pre-existing object, this function deletes - /// the old object. - /// - /// - /// The object to insert. - /// - /// - /// The number of rows modified. - /// - public int InsertOrReplace (object obj) - { - if (obj == null) { - return 0; - } - return Insert (obj, "OR REPLACE", obj.GetType ()); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, Type objType) - { - return Insert (obj, "", objType); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// If a UNIQUE constraint violation occurs with - /// some pre-existing object, this function deletes - /// the old object. - /// - /// - /// The object to insert. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows modified. - /// - public int InsertOrReplace (object obj, Type objType) - { - return Insert (obj, "OR REPLACE", objType); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, string extra) - { - if (obj == null) { - return 0; - } - return Insert (obj, extra, obj.GetType ()); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, string extra, Type objType) - { - if (obj == null || objType == null) { - return 0; - } - - - var map = GetMapping (objType); - -#if NETFX_CORE - if (map.PK != null && map.PK.IsAutoGuid) - { - // no GetProperty so search our way up the inheritance chain till we find it - PropertyInfo prop; - while (objType != null) - { - var info = objType.GetTypeInfo(); - prop = info.GetDeclaredProperty(map.PK.PropertyName); - if (prop != null) - { - if (prop.GetValue(obj, null).Equals(Guid.Empty)) - { - prop.SetValue(obj, Guid.NewGuid(), null); - } - break; - } - - objType = info.BaseType; - } - } -#else - if (map.PK != null && map.PK.IsAutoGuid) { - var prop = objType.GetProperty(map.PK.PropertyName); - if (prop != null) { - if (prop.GetValue(obj, null).Equals(Guid.Empty)) { - prop.SetValue(obj, Guid.NewGuid(), null); - } - } - } -#endif - - - var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; - - var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns; - var vals = new object[cols.Length]; - for (var i = 0; i < vals.Length; i++) { - vals [i] = cols [i].GetValue (obj); - } - - var insertCmd = map.GetInsertCommand (this, extra); - int count; - - try { - count = insertCmd.ExecuteNonQuery (vals); - } - catch (SQLiteException ex) { - - if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj); - } - throw; - } - - if (map.HasAutoIncPK) - { - var id = SQLite3.LastInsertRowid (Handle); - map.SetAutoIncPK (obj, id); - } - - return count; - } - - /// - /// Updates all of the columns of a table using the specified object - /// except for its primary key. - /// The object is required to have a primary key. - /// - /// - /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. - /// - /// - /// The number of rows updated. - /// - public int Update (object obj) - { - if (obj == null) { - return 0; - } - return Update (obj, obj.GetType ()); - } - - /// - /// Updates all of the columns of a table using the specified object - /// except for its primary key. - /// The object is required to have a primary key. - /// - /// - /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows updated. - /// - public int Update (object obj, Type objType) - { - int rowsAffected = 0; - if (obj == null || objType == null) { - return 0; - } - - var map = GetMapping (objType); - - var pk = map.PK; - - if (pk == null) { - throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK"); - } - - var cols = from p in map.Columns - where p != pk - select p; - var vals = from c in cols - select c.GetValue (obj); - var ps = new List (vals); - ps.Add (pk.GetValue (obj)); - var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols - select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); - - try { - rowsAffected = Execute (q, ps.ToArray ()); - } - catch (SQLiteException ex) { - - if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - throw NotNullConstraintViolationException.New (ex, map, obj); - } - - throw ex; - } - - return rowsAffected; - } - - /// - /// Updates all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// The number of rows modified. - /// - public int UpdateAll (System.Collections.IEnumerable objects) - { - var c = 0; - RunInTransaction (() => { - foreach (var r in objects) { - c += Update (r); - } - }); - return c; - } - - /// - /// Deletes the given object from the database using its primary key. - /// - /// - /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. - /// - /// - /// The number of rows deleted. - /// - public int Delete (object objectToDelete) - { - var map = GetMapping (objectToDelete.GetType ()); - var pk = map.PK; - if (pk == null) { - throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); - } - var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); - return Execute (q, pk.GetValue (objectToDelete)); - } - - /// - /// Deletes the object with the specified primary key. - /// - /// - /// The primary key of the object to delete. - /// - /// - /// The number of objects deleted. - /// - /// - /// The type of object. - /// - public int Delete (object primaryKey) - { - var map = GetMapping (typeof (T)); - var pk = map.PK; - if (pk == null) { - throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); - } - var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); - return Execute (q, primaryKey); - } - - /// - /// Deletes all the objects from the specified table. - /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the - /// specified table. Do you really want to do that? - /// - /// - /// The number of objects deleted. - /// - /// - /// The type of objects to delete. - /// - public int DeleteAll () - { - var map = GetMapping (typeof (T)); - var query = string.Format("delete from \"{0}\"", map.TableName); - return Execute (query); - } - - ~SQLiteConnection () - { - Dispose (false); - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } - - protected virtual void Dispose (bool disposing) - { - Close (); - } - - public void Close () - { - if (_open && Handle != NullHandle) { - try { - if (_mappings != null) { - foreach (var sqlInsertCommand in _mappings.Values) { - sqlInsertCommand.Dispose(); - } - } - var r = SQLite3.Close (Handle); - if (r != SQLite3.Result.OK) { - string msg = SQLite3.GetErrmsg (Handle); - throw SQLiteException.New (r, msg); - } - } - finally { - Handle = NullHandle; - _open = false; - } - } - } - } - - /// - /// Represents a parsed connection string. - /// - class SQLiteConnectionString - { - public string ConnectionString { get; private set; } - public string DatabasePath { get; private set; } - public bool StoreDateTimeAsTicks { get; private set; } - -#if NETFX_CORE - static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; -#endif - - public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks) - { - ConnectionString = databasePath; - StoreDateTimeAsTicks = storeDateTimeAsTicks; - -#if NETFX_CORE - DatabasePath = System.IO.Path.Combine (MetroStyleDataPath, databasePath); -#else - DatabasePath = databasePath; -#endif - } - } - - [AttributeUsage (AttributeTargets.Class)] - public class TableAttribute : Attribute - { - public string Name { get; set; } - - public TableAttribute (string name) - { - Name = name; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class ColumnAttribute : Attribute - { - public string Name { get; set; } - - public ColumnAttribute (string name) - { - Name = name; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class PrimaryKeyAttribute : Attribute - { - } - - [AttributeUsage (AttributeTargets.Property)] - public class AutoIncrementAttribute : Attribute - { - } - - [AttributeUsage (AttributeTargets.Property)] - public class IndexedAttribute : Attribute - { - public string Name { get; set; } - public int Order { get; set; } - public virtual bool Unique { get; set; } - - public IndexedAttribute() - { - } - - public IndexedAttribute(string name, int order) - { - Name = name; - Order = order; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class IgnoreAttribute : Attribute - { - } - - [AttributeUsage (AttributeTargets.Property)] - public class UniqueAttribute : IndexedAttribute - { - public override bool Unique { - get { return true; } - set { /* throw? */ } - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class MaxLengthAttribute : Attribute - { - public int Value { get; private set; } - - public MaxLengthAttribute (int length) - { - Value = length; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class CollationAttribute: Attribute - { - public string Value { get; private set; } - - public CollationAttribute (string collation) - { - Value = collation; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class NotNullAttribute : Attribute - { - } - - public class TableMapping - { - public Type MappedType { get; private set; } - - public string TableName { get; private set; } - - public Column[] Columns { get; private set; } - - public Column PK { get; private set; } - - public string GetByPrimaryKeySql { get; private set; } - - Column _autoPk; - Column[] _insertColumns; - Column[] _insertOrReplaceColumns; - - public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None) - { - MappedType = type; - -#if NETFX_CORE - var tableAttr = (TableAttribute)System.Reflection.CustomAttributeExtensions - .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true); -#else - var tableAttr = (TableAttribute)type.GetCustomAttributes (typeof (TableAttribute), true).FirstOrDefault (); -#endif - - TableName = tableAttr != null ? tableAttr.Name : MappedType.Name; - -#if !NETFX_CORE - var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); -#else - var props = from p in MappedType.GetRuntimeProperties() - where ((p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic) || (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic)) - select p; -#endif - var cols = new List (); - foreach (var p in props) { -#if !NETFX_CORE - var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0; -#else - var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Count() > 0; -#endif - if (p.CanWrite && !ignore) { - cols.Add (new Column (p, createFlags)); - } - } - Columns = cols.ToArray (); - foreach (var c in Columns) { - if (c.IsAutoInc && c.IsPK) { - _autoPk = c; - } - if (c.IsPK) { - PK = c; - } - } - - HasAutoIncPK = _autoPk != null; - - if (PK != null) { - GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name); - } - else { - // People should not be calling Get/Find without a PK - GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName); - } - } - - public bool HasAutoIncPK { get; private set; } - - public void SetAutoIncPK (object obj, long id) - { - if (_autoPk != null) { - _autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null)); - } - } - - public Column[] InsertColumns { - get { - if (_insertColumns == null) { - _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray (); - } - return _insertColumns; - } - } - - public Column[] InsertOrReplaceColumns { - get { - if (_insertOrReplaceColumns == null) { - _insertOrReplaceColumns = Columns.ToArray (); - } - return _insertOrReplaceColumns; - } - } - - public Column FindColumnWithPropertyName (string propertyName) - { - var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName); - return exact; - } - - public Column FindColumn (string columnName) - { - var exact = Columns.FirstOrDefault (c => c.Name == columnName); - return exact; - } - - PreparedSqlLiteInsertCommand _insertCommand; - string _insertCommandExtra; - - public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, string extra) - { - if (_insertCommand == null) { - _insertCommand = CreateInsertCommand(conn, extra); - _insertCommandExtra = extra; - } - else if (_insertCommandExtra != extra) { - _insertCommand.Dispose(); - _insertCommand = CreateInsertCommand(conn, extra); - _insertCommandExtra = extra; - } - return _insertCommand; - } - - PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra) - { - var cols = InsertColumns; - string insertSql; - if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) - { - insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra); - } - else - { - var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; - - if (replacing) { - cols = InsertOrReplaceColumns; - } - - insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName, - string.Join(",", (from c in cols - select "\"" + c.Name + "\"").ToArray()), - string.Join(",", (from c in cols - select "?").ToArray()), extra); - - } - - var insertCommand = new PreparedSqlLiteInsertCommand(conn); - insertCommand.CommandText = insertSql; - return insertCommand; - } - - protected internal void Dispose() - { - if (_insertCommand != null) { - _insertCommand.Dispose(); - _insertCommand = null; - } - } - - public class Column - { - PropertyInfo _prop; - - public string Name { get; private set; } - - public string PropertyName { get { return _prop.Name; } } - - public Type ColumnType { get; private set; } - - public string Collation { get; private set; } - - public bool IsAutoInc { get; private set; } - public bool IsAutoGuid { get; private set; } - - public bool IsPK { get; private set; } - - public IEnumerable Indices { get; set; } - - public bool IsNullable { get; private set; } - - public int? MaxStringLength { get; private set; } - - public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) - { - var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); - - _prop = prop; - Name = colAttr == null ? prop.Name : colAttr.Name; - //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead - ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; - Collation = Orm.Collation(prop); - - IsPK = Orm.IsPK(prop) || - (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) && - string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); - - var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); - IsAutoGuid = isAuto && ColumnType == typeof(Guid); - IsAutoInc = isAuto && !IsAutoGuid; - - Indices = Orm.GetIndices(prop); - if (!Indices.Any() - && !IsPK - && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) - && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) - ) - { - Indices = new IndexedAttribute[] { new IndexedAttribute() }; - } - IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop)); - MaxStringLength = Orm.MaxStringLength(prop); - } - - public void SetValue (object obj, object val) - { - _prop.SetValue (obj, val, null); - } - - public object GetValue (object obj) - { - return _prop.GetValue (obj, null); - } - } - } - - public static class Orm - { - public const int DefaultMaxStringLength = 140; - public const string ImplicitPkName = "Id"; - public const string ImplicitIndexSuffix = "Id"; - - public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks) - { - string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks) + " "; - - if (p.IsPK) { - decl += "primary key "; - } - if (p.IsAutoInc) { - decl += "autoincrement "; - } - if (!p.IsNullable) { - decl += "not null "; - } - if (!string.IsNullOrEmpty (p.Collation)) { - decl += "collate " + p.Collation + " "; - } - - return decl; - } - - public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks) - { - var clrType = p.ColumnType; - if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) { - return "integer"; - } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) { - return "bigint"; - } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) { - return "float"; - } else if (clrType == typeof(String)) { - int? len = p.MaxStringLength; - - if (len.HasValue) - return "varchar(" + len.Value + ")"; - - return "varchar"; - } else if (clrType == typeof(TimeSpan)) { - return "bigint"; - } else if (clrType == typeof(DateTime)) { - return storeDateTimeAsTicks ? "bigint" : "datetime"; - } else if (clrType == typeof(DateTimeOffset)) { - return "bigint"; -#if !NETFX_CORE - } else if (clrType.IsEnum) { -#else - } else if (clrType.GetTypeInfo().IsEnum) { -#endif - return "integer"; - } else if (clrType == typeof(byte[])) { - return "blob"; - } else if (clrType == typeof(Guid)) { - return "varchar(36)"; - } else { - throw new NotSupportedException ("Don't know about " + clrType); - } - } - - public static bool IsPK (MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true); -#if !NETFX_CORE - return attrs.Length > 0; -#else - return attrs.Count() > 0; -#endif - } - - public static string Collation (MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof(CollationAttribute), true); -#if !NETFX_CORE - if (attrs.Length > 0) { - return ((CollationAttribute)attrs [0]).Value; -#else - if (attrs.Count() > 0) { - return ((CollationAttribute)attrs.First()).Value; -#endif - } else { - return string.Empty; - } - } - - public static bool IsAutoInc (MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true); -#if !NETFX_CORE - return attrs.Length > 0; -#else - return attrs.Count() > 0; -#endif - } - - public static IEnumerable GetIndices(MemberInfo p) - { - var attrs = p.GetCustomAttributes(typeof(IndexedAttribute), true); - return attrs.Cast(); - } - - public static int? MaxStringLength(PropertyInfo p) - { - var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true); -#if !NETFX_CORE - if (attrs.Length > 0) - return ((MaxLengthAttribute)attrs [0]).Value; -#else - if (attrs.Count() > 0) - return ((MaxLengthAttribute)attrs.First()).Value; -#endif - - return null; - } - - public static bool IsMarkedNotNull(MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof (NotNullAttribute), true); -#if !NETFX_CORE - return attrs.Length > 0; -#else - return attrs.Count() > 0; -#endif - } - } - - public partial class SQLiteCommand - { - SQLiteConnection _conn; - private List _bindings; - - public string CommandText { get; set; } - - internal SQLiteCommand (SQLiteConnection conn) - { - _conn = conn; - _bindings = new List (); - CommandText = ""; - } - - public int ExecuteNonQuery () - { - if (_conn.Trace) { - Debug.WriteLine ("Executing: " + this); - } - - var r = SQLite3.Result.OK; - var stmt = Prepare (); - r = SQLite3.Step (stmt); - Finalize (stmt); - if (r == SQLite3.Result.Done) { - int rowsAffected = SQLite3.Changes (_conn.Handle); - return rowsAffected; - } else if (r == SQLite3.Result.Error) { - string msg = SQLite3.GetErrmsg (_conn.Handle); - throw SQLiteException.New (r, msg); - } - else if (r == SQLite3.Result.Constraint) { - if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle)); - } - } - - throw SQLiteException.New(r, r.ToString()); - } - - public IEnumerable ExecuteDeferredQuery () - { - return ExecuteDeferredQuery(_conn.GetMapping(typeof(T))); - } - - public List ExecuteQuery () - { - return ExecuteDeferredQuery(_conn.GetMapping(typeof(T))).ToList(); - } - - public List ExecuteQuery (TableMapping map) - { - return ExecuteDeferredQuery(map).ToList(); - } - - /// - /// Invoked every time an instance is loaded from the database. - /// - /// - /// The newly created object. - /// - /// - /// This can be overridden in combination with the - /// method to hook into the life-cycle of objects. - /// - /// Type safety is not possible because MonoTouch does not support virtual generic methods. - /// - protected virtual void OnInstanceCreated (object obj) - { - // Can be overridden. - } - - public IEnumerable ExecuteDeferredQuery (TableMapping map) - { - if (_conn.Trace) { - Debug.WriteLine ("Executing Query: " + this); - } - - var stmt = Prepare (); - try - { - var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)]; - - for (int i = 0; i < cols.Length; i++) { - var name = SQLite3.ColumnName16 (stmt, i); - cols [i] = map.FindColumn (name); - } - - while (SQLite3.Step (stmt) == SQLite3.Result.Row) { - var obj = Activator.CreateInstance(map.MappedType); - for (int i = 0; i < cols.Length; i++) { - if (cols [i] == null) - continue; - var colType = SQLite3.ColumnType (stmt, i); - var val = ReadCol (stmt, i, colType, cols [i].ColumnType); - cols [i].SetValue (obj, val); - } - OnInstanceCreated (obj); - yield return (T)obj; - } - } - finally - { - SQLite3.Finalize(stmt); - } - } - - public T ExecuteScalar () - { - if (_conn.Trace) { - Debug.WriteLine ("Executing Query: " + this); - } - - T val = default(T); - - var stmt = Prepare (); - - try - { - var r = SQLite3.Step (stmt); - if (r == SQLite3.Result.Row) { - var colType = SQLite3.ColumnType (stmt, 0); - val = (T)ReadCol (stmt, 0, colType, typeof(T)); - } - else if (r == SQLite3.Result.Done) { - } - else - { - throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle)); - } - } - finally - { - Finalize (stmt); - } - - return val; - } - - public void Bind (string name, object val) - { - _bindings.Add (new Binding { - Name = name, - Value = val - }); - } - - public void Bind (object val) - { - Bind (null, val); - } - - public override string ToString () - { - var parts = new string[1 + _bindings.Count]; - parts [0] = CommandText; - var i = 1; - foreach (var b in _bindings) { - parts [i] = string.Format (" {0}: {1}", i - 1, b.Value); - i++; - } - return string.Join (Environment.NewLine, parts); - } - - Sqlite3Statement Prepare() - { - var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText); - BindAll (stmt); - return stmt; - } - - void Finalize (Sqlite3Statement stmt) - { - SQLite3.Finalize (stmt); - } - - void BindAll (Sqlite3Statement stmt) - { - int nextIdx = 1; - foreach (var b in _bindings) { - if (b.Name != null) { - b.Index = SQLite3.BindParameterIndex (stmt, b.Name); - } else { - b.Index = nextIdx++; - } - - BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks); - } - } - - internal static IntPtr NegativePointer = new IntPtr (-1); - - internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks) - { - if (value == null) { - SQLite3.BindNull (stmt, index); - } else { - if (value is Int32) { - SQLite3.BindInt (stmt, index, (int)value); - } else if (value is String) { - SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer); - } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { - SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is Boolean) { - SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0); - } else if (value is UInt32 || value is Int64) { - SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value)); - } else if (value is Single || value is Double || value is Decimal) { - SQLite3.BindDouble (stmt, index, Convert.ToDouble (value)); - } else if (value is TimeSpan) { - SQLite3.BindInt64(stmt, index, ((TimeSpan)value).Ticks); - } else if (value is DateTime) { - if (storeDateTimeAsTicks) { - SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks); - } - else { - SQLite3.BindText (stmt, index, ((DateTime)value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); - } - } else if (value is DateTimeOffset) { - SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks); -#if !NETFX_CORE - } else if (value.GetType().IsEnum) { -#else - } else if (value.GetType().GetTypeInfo().IsEnum) { -#endif - SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is byte[]){ - SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); - } else if (value is Guid) { - SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); - } else { - throw new NotSupportedException("Cannot store type: " + value.GetType()); - } - } - } - - class Binding - { - public string Name { get; set; } - - public object Value { get; set; } - - public int Index { get; set; } - } - - object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType) - { - if (type == SQLite3.ColType.Null) { - return null; - } else { - if (clrType == typeof(String)) { - return SQLite3.ColumnString (stmt, index); - } else if (clrType == typeof(Int32)) { - return (int)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Boolean)) { - return SQLite3.ColumnInt (stmt, index) == 1; - } else if (clrType == typeof(double)) { - return SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(float)) { - return (float)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(TimeSpan)) { - return new TimeSpan(SQLite3.ColumnInt64(stmt, index)); - } else if (clrType == typeof(DateTime)) { - if (_conn.StoreDateTimeAsTicks) { - return new DateTime (SQLite3.ColumnInt64 (stmt, index)); - } - else { - var text = SQLite3.ColumnString (stmt, index); - return DateTime.Parse (text); - } - } else if (clrType == typeof(DateTimeOffset)) { - return new DateTimeOffset(SQLite3.ColumnInt64 (stmt, index),TimeSpan.Zero); -#if !NETFX_CORE - } else if (clrType.IsEnum) { -#else - } else if (clrType.GetTypeInfo().IsEnum) { -#endif - return SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int64)) { - return SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(UInt32)) { - return (uint)SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(decimal)) { - return (decimal)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(Byte)) { - return (byte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(UInt16)) { - return (ushort)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int16)) { - return (short)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(sbyte)) { - return (sbyte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(byte[])) { - return SQLite3.ColumnByteArray (stmt, index); - } else if (clrType == typeof(Guid)) { - var text = SQLite3.ColumnString(stmt, index); - return new Guid(text); - } else{ - throw new NotSupportedException ("Don't know how to read " + clrType); - } - } - } - } - - /// - /// Since the insert never changed, we only need to prepare once. - /// - public class PreparedSqlLiteInsertCommand : IDisposable - { - public bool Initialized { get; set; } - - protected SQLiteConnection Connection { get; set; } - - public string CommandText { get; set; } - - protected Sqlite3Statement Statement { get; set; } - internal static readonly Sqlite3Statement NullStatement = default(Sqlite3Statement); - - internal PreparedSqlLiteInsertCommand (SQLiteConnection conn) - { - Connection = conn; - } - - public int ExecuteNonQuery (object[] source) - { - if (Connection.Trace) { - Debug.WriteLine ("Executing: " + CommandText); - } - - var r = SQLite3.Result.OK; - - if (!Initialized) { - Statement = Prepare (); - Initialized = true; - } - - //bind the values. - if (source != null) { - for (int i = 0; i < source.Length; i++) { - SQLiteCommand.BindParameter (Statement, i + 1, source [i], Connection.StoreDateTimeAsTicks); - } - } - r = SQLite3.Step (Statement); - - if (r == SQLite3.Result.Done) { - int rowsAffected = SQLite3.Changes (Connection.Handle); - SQLite3.Reset (Statement); - return rowsAffected; - } else if (r == SQLite3.Result.Error) { - string msg = SQLite3.GetErrmsg (Connection.Handle); - SQLite3.Reset (Statement); - throw SQLiteException.New (r, msg); - } else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - SQLite3.Reset (Statement); - throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle)); - } else { - SQLite3.Reset (Statement); - throw SQLiteException.New (r, r.ToString ()); - } - } - - protected virtual Sqlite3Statement Prepare () - { - var stmt = SQLite3.Prepare2 (Connection.Handle, CommandText); - return stmt; - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } - - private void Dispose (bool disposing) - { - if (Statement != NullStatement) { - try { - SQLite3.Finalize (Statement); - } finally { - Statement = NullStatement; - Connection = null; - } - } - } - - ~PreparedSqlLiteInsertCommand () - { - Dispose (false); - } - } - - public abstract class BaseTableQuery - { - protected class Ordering - { - public string ColumnName { get; set; } - public bool Ascending { get; set; } - } - } - - public class TableQuery : BaseTableQuery, IEnumerable - { - public SQLiteConnection Connection { get; private set; } - - public TableMapping Table { get; private set; } - - Expression _where; - List _orderBys; - int? _limit; - int? _offset; - - BaseTableQuery _joinInner; - Expression _joinInnerKeySelector; - BaseTableQuery _joinOuter; - Expression _joinOuterKeySelector; - Expression _joinSelector; - - Expression _selector; - - TableQuery (SQLiteConnection conn, TableMapping table) - { - Connection = conn; - Table = table; - } - - public TableQuery (SQLiteConnection conn) - { - Connection = conn; - Table = Connection.GetMapping (typeof(T)); - } - - public TableQuery Clone () - { - var q = new TableQuery (Connection, Table); - q._where = _where; - q._deferred = _deferred; - if (_orderBys != null) { - q._orderBys = new List (_orderBys); - } - q._limit = _limit; - q._offset = _offset; - q._joinInner = _joinInner; - q._joinInnerKeySelector = _joinInnerKeySelector; - q._joinOuter = _joinOuter; - q._joinOuterKeySelector = _joinOuterKeySelector; - q._joinSelector = _joinSelector; - q._selector = _selector; - return q; - } - - public TableQuery Where (Expression> predExpr) - { - if (predExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)predExpr; - var pred = lambda.Body; - var q = Clone (); - q.AddWhere (pred); - return q; - } else { - throw new NotSupportedException ("Must be a predicate"); - } - } - - public TableQuery Take (int n) - { - var q = Clone (); - q._limit = n; - return q; - } - - public TableQuery Skip (int n) - { - var q = Clone (); - q._offset = n; - return q; - } - - public T ElementAt (int index) - { - return Skip (index).Take (1).First (); - } - - bool _deferred; - public TableQuery Deferred () - { - var q = Clone (); - q._deferred = true; - return q; - } - - public TableQuery OrderBy (Expression> orderExpr) - { - return AddOrderBy (orderExpr, true); - } - - public TableQuery OrderByDescending (Expression> orderExpr) - { - return AddOrderBy (orderExpr, false); - } - - public TableQuery ThenBy(Expression> orderExpr) - { - return AddOrderBy(orderExpr, true); - } - - public TableQuery ThenByDescending(Expression> orderExpr) - { - return AddOrderBy(orderExpr, false); - } - - private TableQuery AddOrderBy (Expression> orderExpr, bool asc) - { - if (orderExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)orderExpr; - - MemberExpression mem = null; - - var unary = lambda.Body as UnaryExpression; - if (unary != null && unary.NodeType == ExpressionType.Convert) { - mem = unary.Operand as MemberExpression; - } - else { - mem = lambda.Body as MemberExpression; - } - - if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { - var q = Clone (); - if (q._orderBys == null) { - q._orderBys = new List (); - } - q._orderBys.Add (new Ordering { - ColumnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name, - Ascending = asc - }); - return q; - } else { - throw new NotSupportedException ("Order By does not support: " + orderExpr); - } - } else { - throw new NotSupportedException ("Must be a predicate"); - } - } - - private void AddWhere (Expression pred) - { - if (_where == null) { - _where = pred; - } else { - _where = Expression.AndAlso (_where, pred); - } - } - - public TableQuery Join ( - TableQuery inner, - Expression> outerKeySelector, - Expression> innerKeySelector, - Expression> resultSelector) - { - var q = new TableQuery (Connection, Connection.GetMapping (typeof (TResult))) { - _joinOuter = this, - _joinOuterKeySelector = outerKeySelector, - _joinInner = inner, - _joinInnerKeySelector = innerKeySelector, - _joinSelector = resultSelector, - }; - return q; - } - - public TableQuery Select (Expression> selector) - { - var q = Clone (); - q._selector = selector; - return q; - } - - private SQLiteCommand GenerateCommand (string selectionList) - { - if (_joinInner != null && _joinOuter != null) { - throw new NotSupportedException ("Joins are not supported."); - } - else { - var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\""; - var args = new List (); - if (_where != null) { - var w = CompileExpr (_where, args); - cmdText += " where " + w.CommandText; - } - if ((_orderBys != null) && (_orderBys.Count > 0)) { - var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ()); - cmdText += " order by " + t; - } - if (_limit.HasValue) { - cmdText += " limit " + _limit.Value; - } - if (_offset.HasValue) { - if (!_limit.HasValue) { - cmdText += " limit -1 "; - } - cmdText += " offset " + _offset.Value; - } - return Connection.CreateCommand (cmdText, args.ToArray ()); - } - } - - class CompileResult - { - public string CommandText { get; set; } - - public object Value { get; set; } - } - - private CompileResult CompileExpr (Expression expr, List queryArgs) - { - if (expr == null) { - throw new NotSupportedException ("Expression is NULL"); - } else if (expr is BinaryExpression) { - var bin = (BinaryExpression)expr; - - var leftr = CompileExpr (bin.Left, queryArgs); - var rightr = CompileExpr (bin.Right, queryArgs); - - //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") - string text; - if (leftr.CommandText == "?" && leftr.Value == null) - text = CompileNullBinaryExpression(bin, rightr); - else if (rightr.CommandText == "?" && rightr.Value == null) - text = CompileNullBinaryExpression(bin, leftr); - else - text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")"; - return new CompileResult { CommandText = text }; - } else if (expr.NodeType == ExpressionType.Call) { - - var call = (MethodCallExpression)expr; - var args = new CompileResult[call.Arguments.Count]; - var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null; - - for (var i = 0; i < args.Length; i++) { - args [i] = CompileExpr (call.Arguments [i], queryArgs); - } - - var sqlCall = ""; - - if (call.Method.Name == "Like" && args.Length == 2) { - sqlCall = "(" + args [0].CommandText + " like " + args [1].CommandText + ")"; - } - else if (call.Method.Name == "Contains" && args.Length == 2) { - sqlCall = "(" + args [1].CommandText + " in " + args [0].CommandText + ")"; - } - else if (call.Method.Name == "Contains" && args.Length == 1) { - if (call.Object != null && call.Object.Type == typeof(string)) { - sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + " || '%'))"; - } - else { - sqlCall = "(" + args [0].CommandText + " in " + obj.CommandText + ")"; - } - } - else if (call.Method.Name == "StartsWith" && args.Length == 1) { - sqlCall = "(" + obj.CommandText + " like (" + args [0].CommandText + " || '%'))"; - } - else if (call.Method.Name == "EndsWith" && args.Length == 1) { - sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + "))"; - } - else if (call.Method.Name == "Equals" && args.Length == 1) { - sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))"; - } else if (call.Method.Name == "ToLower") { - sqlCall = "(lower(" + obj.CommandText + "))"; - } else if (call.Method.Name == "ToUpper") { - sqlCall = "(upper(" + obj.CommandText + "))"; - } else { - sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")"; - } - return new CompileResult { CommandText = sqlCall }; - - } else if (expr.NodeType == ExpressionType.Constant) { - var c = (ConstantExpression)expr; - queryArgs.Add (c.Value); - return new CompileResult { - CommandText = "?", - Value = c.Value - }; - } else if (expr.NodeType == ExpressionType.Convert) { - var u = (UnaryExpression)expr; - var ty = u.Type; - var valr = CompileExpr (u.Operand, queryArgs); - return new CompileResult { - CommandText = valr.CommandText, - Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null - }; - } else if (expr.NodeType == ExpressionType.MemberAccess) { - var mem = (MemberExpression)expr; - - if (mem.Expression!=null && mem.Expression.NodeType == ExpressionType.Parameter) { - // - // This is a column of our table, output just the column name - // Need to translate it if that column name is mapped - // - var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name; - return new CompileResult { CommandText = "\"" + columnName + "\"" }; - } else { - object obj = null; - if (mem.Expression != null) { - var r = CompileExpr (mem.Expression, queryArgs); - if (r.Value == null) { - throw new NotSupportedException ("Member access failed to compile expression"); - } - if (r.CommandText == "?") { - queryArgs.RemoveAt (queryArgs.Count - 1); - } - obj = r.Value; - } - - // - // Get the member value - // - object val = null; - -#if !NETFX_CORE - if (mem.Member.MemberType == MemberTypes.Property) { -#else - if (mem.Member is PropertyInfo) { -#endif - var m = (PropertyInfo)mem.Member; - val = m.GetValue (obj, null); -#if !NETFX_CORE - } else if (mem.Member.MemberType == MemberTypes.Field) { -#else - } else if (mem.Member is FieldInfo) { -#endif -#if SILVERLIGHT - val = Expression.Lambda (expr).Compile ().DynamicInvoke (); -#else - var m = (FieldInfo)mem.Member; - val = m.GetValue (obj); -#endif - } else { -#if !NETFX_CORE - throw new NotSupportedException ("MemberExpr: " + mem.Member.MemberType); -#else - throw new NotSupportedException ("MemberExpr: " + mem.Member.DeclaringType); -#endif - } - - // - // Work special magic for enumerables - // - if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable)) { - var sb = new System.Text.StringBuilder(); - sb.Append("("); - var head = ""; - foreach (var a in (System.Collections.IEnumerable)val) { - queryArgs.Add(a); - sb.Append(head); - sb.Append("?"); - head = ","; - } - sb.Append(")"); - return new CompileResult { - CommandText = sb.ToString(), - Value = val - }; - } - else { - queryArgs.Add (val); - return new CompileResult { - CommandText = "?", - Value = val - }; - } - } - } - throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ()); - } - - static object ConvertTo (object obj, Type t) - { - Type nut = Nullable.GetUnderlyingType(t); - - if (nut != null) { - if (obj == null) return null; - return Convert.ChangeType (obj, nut); - } else { - return Convert.ChangeType (obj, t); - } - } - - /// - /// Compiles a BinaryExpression where one of the parameters is null. - /// - /// The non-null parameter - private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) - { - if (expression.NodeType == ExpressionType.Equal) - return "(" + parameter.CommandText + " is ?)"; - else if (expression.NodeType == ExpressionType.NotEqual) - return "(" + parameter.CommandText + " is not ?)"; - else - throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString()); - } - - string GetSqlName (Expression expr) - { - var n = expr.NodeType; - if (n == ExpressionType.GreaterThan) - return ">"; else if (n == ExpressionType.GreaterThanOrEqual) { - return ">="; - } else if (n == ExpressionType.LessThan) { - return "<"; - } else if (n == ExpressionType.LessThanOrEqual) { - return "<="; - } else if (n == ExpressionType.And) { - return "&"; - } else if (n == ExpressionType.AndAlso) { - return "and"; - } else if (n == ExpressionType.Or) { - return "|"; - } else if (n == ExpressionType.OrElse) { - return "or"; - } else if (n == ExpressionType.Equal) { - return "="; - } else if (n == ExpressionType.NotEqual) { - return "!="; - } else { - throw new NotSupportedException ("Cannot get SQL for: " + n); - } - } - - public int Count () - { - return GenerateCommand("count(*)").ExecuteScalar (); - } - - public int Count (Expression> predExpr) - { - return Where (predExpr).Count (); - } - - public IEnumerator GetEnumerator () - { - if (!_deferred) - return GenerateCommand("*").ExecuteQuery().GetEnumerator(); - - return GenerateCommand("*").ExecuteDeferredQuery().GetEnumerator(); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () - { - return GetEnumerator (); - } - - public T First () - { - var query = Take (1); - return query.ToList().First (); - } - - public T FirstOrDefault () - { - var query = Take (1); - return query.ToList().FirstOrDefault (); - } - } - - public static class SQLite3 - { - public enum Result : int - { - OK = 0, - Error = 1, - Internal = 2, - Perm = 3, - Abort = 4, - Busy = 5, - Locked = 6, - NoMem = 7, - ReadOnly = 8, - Interrupt = 9, - IOError = 10, - Corrupt = 11, - NotFound = 12, - Full = 13, - CannotOpen = 14, - LockErr = 15, - Empty = 16, - SchemaChngd = 17, - TooBig = 18, - Constraint = 19, - Mismatch = 20, - Misuse = 21, - NotImplementedLFS = 22, - AccessDenied = 23, - Format = 24, - Range = 25, - NonDBFile = 26, - Notice = 27, - Warning = 28, - Row = 100, - Done = 101 - } - - public enum ExtendedResult : int - { - IOErrorRead = (Result.IOError | (1 << 8)), - IOErrorShortRead = (Result.IOError | (2 << 8)), - IOErrorWrite = (Result.IOError | (3 << 8)), - IOErrorFsync = (Result.IOError | (4 << 8)), - IOErrorDirFSync = (Result.IOError | (5 << 8)), - IOErrorTruncate = (Result.IOError | (6 << 8)), - IOErrorFStat = (Result.IOError | (7 << 8)), - IOErrorUnlock = (Result.IOError | (8 << 8)), - IOErrorRdlock = (Result.IOError | (9 << 8)), - IOErrorDelete = (Result.IOError | (10 << 8)), - IOErrorBlocked = (Result.IOError | (11 << 8)), - IOErrorNoMem = (Result.IOError | (12 << 8)), - IOErrorAccess = (Result.IOError | (13 << 8)), - IOErrorCheckReservedLock = (Result.IOError | (14 << 8)), - IOErrorLock = (Result.IOError | (15 << 8)), - IOErrorClose = (Result.IOError | (16 << 8)), - IOErrorDirClose = (Result.IOError | (17 << 8)), - IOErrorSHMOpen = (Result.IOError | (18 << 8)), - IOErrorSHMSize = (Result.IOError | (19 << 8)), - IOErrorSHMLock = (Result.IOError | (20 << 8)), - IOErrorSHMMap = (Result.IOError | (21 << 8)), - IOErrorSeek = (Result.IOError | (22 << 8)), - IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)), - IOErrorMMap = (Result.IOError | (24 << 8)), - LockedSharedcache = (Result.Locked | (1 << 8)), - BusyRecovery = (Result.Busy | (1 << 8)), - CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)), - CannotOpenIsDir = (Result.CannotOpen | (2 << 8)), - CannotOpenFullPath = (Result.CannotOpen | (3 << 8)), - CorruptVTab = (Result.Corrupt | (1 << 8)), - ReadonlyRecovery = (Result.ReadOnly | (1 << 8)), - ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)), - ReadonlyRollback = (Result.ReadOnly | (3 << 8)), - AbortRollback = (Result.Abort | (2 << 8)), - ConstraintCheck = (Result.Constraint | (1 << 8)), - ConstraintCommitHook = (Result.Constraint | (2 << 8)), - ConstraintForeignKey = (Result.Constraint | (3 << 8)), - ConstraintFunction = (Result.Constraint | (4 << 8)), - ConstraintNotNull = (Result.Constraint | (5 << 8)), - ConstraintPrimaryKey = (Result.Constraint | (6 << 8)), - ConstraintTrigger = (Result.Constraint | (7 << 8)), - ConstraintUnique = (Result.Constraint | (8 << 8)), - ConstraintVTab = (Result.Constraint | (9 << 8)), - NoticeRecoverWAL = (Result.Notice | (1 << 8)), - NoticeRecoverRollback = (Result.Notice | (2 << 8)) - } - - - public enum ConfigOption : int - { - SingleThread = 1, - MultiThread = 2, - Serialized = 3 - } - -#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE - [DllImport("sqlite3", EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, IntPtr zvfs); - - [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs); - - [DllImport("sqlite3", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)] - public static extern Result EnableLoadExtension (IntPtr db, int onoff); - - [DllImport("sqlite3", EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Close (IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Initialize(); - - [DllImport("sqlite3", EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Shutdown(); - - [DllImport("sqlite3", EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Config (ConfigOption option); - - [DllImport("sqlite3", EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)] - public static extern int SetDirectory (uint directoryType, string directoryPath); - - [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)] - public static extern Result BusyTimeout (IntPtr db, int milliseconds); - - [DllImport("sqlite3", EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)] - public static extern int Changes (IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); - -#if NETFX_CORE - [DllImport ("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail); -#endif - - public static IntPtr Prepare2 (IntPtr db, string query) - { - IntPtr stmt; -#if NETFX_CORE - byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query); - var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero); -#else - var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero); -#endif - if (r != Result.OK) { - throw SQLiteException.New (r, GetErrmsg (db)); - } - return stmt; - } - - [DllImport("sqlite3", EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Step (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Reset (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Finalize (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)] - public static extern long LastInsertRowid (IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr Errmsg (IntPtr db); - - public static string GetErrmsg (IntPtr db) - { - return Marshal.PtrToStringUni (Errmsg (db)); - } - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindNull (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindInt (IntPtr stmt, int index, int val); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindInt64 (IntPtr stmt, int index, long val); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindDouble (IntPtr stmt, int index, double val); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)] - public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)] - public static extern int ColumnCount (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnName (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)] - static extern IntPtr ColumnName16Internal (IntPtr stmt, int index); - public static string ColumnName16(IntPtr stmt, int index) - { - return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index)); - } - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)] - public static extern ColType ColumnType (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)] - public static extern int ColumnInt (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)] - public static extern long ColumnInt64 (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)] - public static extern double ColumnDouble (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnText (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnText16 (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnBlob (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)] - public static extern int ColumnBytes (IntPtr stmt, int index); - - public static string ColumnString (IntPtr stmt, int index) - { - return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index)); - } - - public static byte[] ColumnByteArray (IntPtr stmt, int index) - { - int length = ColumnBytes (stmt, index); - var result = new byte[length]; - if (length > 0) - Marshal.Copy (ColumnBlob (stmt, index), result, 0, length); - return result; - } - - [DllImport ("sqlite3", EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)] - public static extern ExtendedResult ExtendedErrCode (IntPtr db); - - [DllImport ("sqlite3", EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)] - public static extern int LibVersionNumber (); -#else - public static Result Open(string filename, out Sqlite3DatabaseHandle db) - { - return (Result) Sqlite3.sqlite3_open(filename, out db); - } - - public static Result Open(string filename, out Sqlite3DatabaseHandle db, int flags, IntPtr zVfs) - { -#if USE_WP8_NATIVE_SQLITE - return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, ""); -#else - return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, null); -#endif - } - - public static Result Close(Sqlite3DatabaseHandle db) - { - return (Result)Sqlite3.sqlite3_close(db); - } - - public static Result BusyTimeout(Sqlite3DatabaseHandle db, int milliseconds) - { - return (Result)Sqlite3.sqlite3_busy_timeout(db, milliseconds); - } - - public static int Changes(Sqlite3DatabaseHandle db) - { - return Sqlite3.sqlite3_changes(db); - } - - public static Sqlite3Statement Prepare2(Sqlite3DatabaseHandle db, string query) - { - Sqlite3Statement stmt = default(Sqlite3Statement); -#if USE_WP8_NATIVE_SQLITE - var r = Sqlite3.sqlite3_prepare_v2(db, query, out stmt); -#else - stmt = new Sqlite3Statement(); - var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0); -#endif - if (r != 0) - { - throw SQLiteException.New((Result)r, GetErrmsg(db)); - } - return stmt; - } - - public static Result Step(Sqlite3Statement stmt) - { - return (Result)Sqlite3.sqlite3_step(stmt); - } - - public static Result Reset(Sqlite3Statement stmt) - { - return (Result)Sqlite3.sqlite3_reset(stmt); - } - - public static Result Finalize(Sqlite3Statement stmt) - { - return (Result)Sqlite3.sqlite3_finalize(stmt); - } - - public static long LastInsertRowid(Sqlite3DatabaseHandle db) - { - return Sqlite3.sqlite3_last_insert_rowid(db); - } - - public static string GetErrmsg(Sqlite3DatabaseHandle db) - { - return Sqlite3.sqlite3_errmsg(db); - } - - public static int BindParameterIndex(Sqlite3Statement stmt, string name) - { - return Sqlite3.sqlite3_bind_parameter_index(stmt, name); - } - - public static int BindNull(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_bind_null(stmt, index); - } - - public static int BindInt(Sqlite3Statement stmt, int index, int val) - { - return Sqlite3.sqlite3_bind_int(stmt, index, val); - } - - public static int BindInt64(Sqlite3Statement stmt, int index, long val) - { - return Sqlite3.sqlite3_bind_int64(stmt, index, val); - } - - public static int BindDouble(Sqlite3Statement stmt, int index, double val) - { - return Sqlite3.sqlite3_bind_double(stmt, index, val); - } - - public static int BindText(Sqlite3Statement stmt, int index, string val, int n, IntPtr free) - { -#if USE_WP8_NATIVE_SQLITE - return Sqlite3.sqlite3_bind_text(stmt, index, val, n); -#else - return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null); -#endif - } - - public static int BindBlob(Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free) - { -#if USE_WP8_NATIVE_SQLITE - return Sqlite3.sqlite3_bind_blob(stmt, index, val, n); -#else - return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null); -#endif - } - - public static int ColumnCount(Sqlite3Statement stmt) - { - return Sqlite3.sqlite3_column_count(stmt); - } - - public static string ColumnName(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_name(stmt, index); - } - - public static string ColumnName16(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_name(stmt, index); - } - - public static ColType ColumnType(Sqlite3Statement stmt, int index) - { - return (ColType)Sqlite3.sqlite3_column_type(stmt, index); - } - - public static int ColumnInt(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_int(stmt, index); - } - - public static long ColumnInt64(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_int64(stmt, index); - } - - public static double ColumnDouble(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_double(stmt, index); - } - - public static string ColumnText(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_text(stmt, index); - } - - public static string ColumnText16(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_text(stmt, index); - } - - public static byte[] ColumnBlob(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_blob(stmt, index); - } - - public static int ColumnBytes(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_bytes(stmt, index); - } - - public static string ColumnString(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_text(stmt, index); - } - - public static byte[] ColumnByteArray(Sqlite3Statement stmt, int index) - { - return ColumnBlob(stmt, index); - } - - public static Result EnableLoadExtension(Sqlite3DatabaseHandle db, int onoff) - { - return (Result)Sqlite3.sqlite3_enable_load_extension(db, onoff); - } - - public static ExtendedResult ExtendedErrCode(Sqlite3DatabaseHandle db) - { - return (ExtendedResult)Sqlite3.sqlite3_extended_errcode(db); - } -#endif - - public enum ColType : int - { - Integer = 1, - Float = 2, - Text = 3, - Blob = 4, - Null = 5 - } - } -} diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite4Unity3dWP8.csproj b/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite4Unity3dWP8.csproj deleted file mode 100644 index 47276d3..0000000 --- a/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite4Unity3dWP8.csproj +++ /dev/null @@ -1,120 +0,0 @@ - - - - - Debug - AnyCPU - 10.0.20506 - 2.0 - {DFF95D7B-03AD-4627-BBB8-38A2EAD07AA0} - {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - SQLite4Unity3d - SQLite4Unity3d - WindowsPhone - v8.0 - $(TargetFrameworkVersion) - false - true - 11.0 - true - d27bab07 - - - true - full - false - Bin\Debug - TRACE;DEBUG;SILVERLIGHT;WINDOWS_PHONE;USE_CSHARP_SQLITE - true - true - prompt - 4 - - - pdbonly - true - Bin\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE;USE_WP8_NATIVE_SQLITE - true - true - prompt - 4 - - - true - full - false - Bin\x86\Debug - DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE - true - true - prompt - 4 - - - pdbonly - true - Bin\x86\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE;USE_WP8_NATIVE_SQLITE; - true - true - prompt - 4 - - - true - full - false - Bin\ARM\Debug - TRACE;DEBUG;SILVERLIGHT;WINDOWS_PHONE;USE_WP8_NATIVE_SQLITE - true - true - prompt - 4 - - - pdbonly - true - Bin\ARM\Release - TRACE;SILVERLIGHT;WINDOWS_PHONE;USE_WP8_NATIVE_SQLITE; - true - true - prompt - 4 - - - - - - - - - - - - - - ..\packages\sqlite-net-wp8.3.8.5\lib\windowsphone8\Sqlite.winmd - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite4Unity3dWP8.csproj.user b/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite4Unity3dWP8.csproj.user deleted file mode 100644 index cb087e3..0000000 --- a/SQLite4Unity3d/SQLite4Unity3dWP8/SQLite4Unity3dWP8.csproj.user +++ /dev/null @@ -1,18 +0,0 @@ - - - - ShowAllFiles - - - - - - True - Managed - Managed - False - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/packages.config b/SQLite4Unity3d/SQLite4Unity3dWP8/packages.config deleted file mode 100644 index db0238f..0000000 --- a/SQLite4Unity3d/SQLite4Unity3dWP8/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/SQLite4Unity3dWP8/readme.txt b/SQLite4Unity3d/SQLite4Unity3dWP8/readme.txt deleted file mode 100644 index d33e9e0..0000000 --- a/SQLite4Unity3d/SQLite4Unity3dWP8/readme.txt +++ /dev/null @@ -1,7 +0,0 @@ -http://developer.nokia.com/community/wiki/How_to_use_SQLite_in_Windows_Phone - -You'll probably get this error message: The type or namespace name 'Community' could not be found. It can be fixed by this approach: Create the USE_WP8_NATIVE_SQLITE compilation symbol in the "SqliteForWP8" project. Please pay attention to the configuration and platform that you are creating this symbol since each platform has its own set of compilation symbols. This symbol will tell the sqlite-net package that you are using the SQLite for Windows Phone SDK. - -"Any CPU" problem - -If you get a warning message as shown below, follow these steps to fix it: Right click on the Solution -> Click on Configuration Properties -> Configuration Manager and change the active solution platform to x86 (If you are using an emulator) or ARM (If you are using a Windows Phone 8 device). \ No newline at end of file diff --git a/SQLite4Unity3d/packages/repositories.config b/SQLite4Unity3d/packages/repositories.config deleted file mode 100644 index 838658c..0000000 --- a/SQLite4Unity3d/packages/repositories.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/ARM/Sqlite.dll b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/ARM/Sqlite.dll deleted file mode 100644 index 4b214ef..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/ARM/Sqlite.dll and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/ARM/Sqlite.winmd b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/ARM/Sqlite.winmd deleted file mode 100644 index aa03ff2..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/ARM/Sqlite.winmd and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/sqlite-net-wp8.props b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/sqlite-net-wp8.props deleted file mode 100644 index 383632b..0000000 --- a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/sqlite-net-wp8.props +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/sqlite-net-wp8.targets b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/sqlite-net-wp8.targets deleted file mode 100644 index db87c3f..0000000 --- a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/sqlite-net-wp8.targets +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - $(MSBuildThisFileDirectory)$(Platform)\Sqlite.winmd - - - - - \ No newline at end of file diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/x86/Sqlite.dll b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/x86/Sqlite.dll deleted file mode 100644 index 9058eb4..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/x86/Sqlite.dll and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/x86/Sqlite.winmd b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/x86/Sqlite.winmd deleted file mode 100644 index 46466bc..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/build/windowsphone8/x86/Sqlite.winmd and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/lib/windowsphone8/Sqlite.dll b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/lib/windowsphone8/Sqlite.dll deleted file mode 100644 index 9058eb4..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/lib/windowsphone8/Sqlite.dll and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/lib/windowsphone8/Sqlite.winmd b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/lib/windowsphone8/Sqlite.winmd deleted file mode 100644 index 46466bc..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/lib/windowsphone8/Sqlite.winmd and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/sqlite-net-wp8.3.8.5.nupkg b/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/sqlite-net-wp8.3.8.5.nupkg deleted file mode 100644 index 972a3a0..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net-wp8.3.8.5/sqlite-net-wp8.3.8.5.nupkg and /dev/null differ diff --git a/SQLite4Unity3d/packages/sqlite-net.1.0.8/content/SQLite.cs b/SQLite4Unity3d/packages/sqlite-net.1.0.8/content/SQLite.cs deleted file mode 100644 index e74447f..0000000 --- a/SQLite4Unity3d/packages/sqlite-net.1.0.8/content/SQLite.cs +++ /dev/null @@ -1,3278 +0,0 @@ -// -// Copyright (c) 2009-2012 Krueger Systems, 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. -// -#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE -#define USE_CSHARP_SQLITE -#endif - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Collections.Generic; -using System.Reflection; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; - -#if USE_CSHARP_SQLITE -using Sqlite3 = Community.CsharpSqlite.Sqlite3; -using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3; -using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe; -#elif USE_WP8_NATIVE_SQLITE -using Sqlite3 = Sqlite.Sqlite3; -using Sqlite3DatabaseHandle = Sqlite.Database; -using Sqlite3Statement = Sqlite.Statement; -#else -using Sqlite3DatabaseHandle = System.IntPtr; -using Sqlite3Statement = System.IntPtr; -#endif - -namespace SQLite -{ - public class SQLiteException : Exception - { - public SQLite3.Result Result { get; private set; } - - protected SQLiteException (SQLite3.Result r,string message) : base(message) - { - Result = r; - } - - public static SQLiteException New (SQLite3.Result r, string message) - { - return new SQLiteException (r, message); - } - } - - public class NotNullConstraintViolationException : SQLiteException - { - public IEnumerable Columns { get; protected set; } - - protected NotNullConstraintViolationException (SQLite3.Result r, string message) - : this (r, message, null, null) - { - - } - - protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj) - : base (r, message) - { - if (mapping != null && obj != null) { - this.Columns = from c in mapping.Columns - where c.IsNullable == false && c.GetValue (obj) == null - select c; - } - } - - public static new NotNullConstraintViolationException New (SQLite3.Result r, string message) - { - return new NotNullConstraintViolationException (r, message); - } - - public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj) - { - return new NotNullConstraintViolationException (r, message, mapping, obj); - } - - public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj) - { - return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj); - } - } - - [Flags] - public enum SQLiteOpenFlags { - ReadOnly = 1, ReadWrite = 2, Create = 4, - NoMutex = 0x8000, FullMutex = 0x10000, - SharedCache = 0x20000, PrivateCache = 0x40000, - ProtectionComplete = 0x00100000, - ProtectionCompleteUnlessOpen = 0x00200000, - ProtectionCompleteUntilFirstUserAuthentication = 0x00300000, - ProtectionNone = 0x00400000 - } - - [Flags] - public enum CreateFlags - { - None = 0, - ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName) - ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix) - AllImplicit = 3, // do both above - - AutoIncPK = 4 // force PK field to be auto inc - } - - /// - /// Represents an open connection to a SQLite database. - /// - public partial class SQLiteConnection : IDisposable - { - private bool _open; - private TimeSpan _busyTimeout; - private Dictionary _mappings = null; - private Dictionary _tables = null; - private System.Diagnostics.Stopwatch _sw; - private long _elapsedMilliseconds = 0; - - private int _transactionDepth = 0; - private Random _rand = new Random (); - - public Sqlite3DatabaseHandle Handle { get; private set; } - internal static readonly Sqlite3DatabaseHandle NullHandle = default(Sqlite3DatabaseHandle); - - public string DatabasePath { get; private set; } - - public bool TimeExecution { get; set; } - - public bool Trace { get; set; } - - public bool StoreDateTimeAsTicks { get; private set; } - - /// - /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. - /// - /// - /// Specifies the path to the database file. - /// - /// - /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You - /// absolutely do want to store them as Ticks in all new projects. The default of false is - /// only here for backwards compatibility. There is a *significant* speed advantage, with no - /// down sides, when setting storeDateTimeAsTicks = true. - /// - public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false) - : this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) - { - } - - /// - /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. - /// - /// - /// Specifies the path to the database file. - /// - /// - /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You - /// absolutely do want to store them as Ticks in all new projects. The default of false is - /// only here for backwards compatibility. There is a *significant* speed advantage, with no - /// down sides, when setting storeDateTimeAsTicks = true. - /// - public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false) - { - if (string.IsNullOrEmpty (databasePath)) - throw new ArgumentException ("Must be specified", "databasePath"); - - DatabasePath = databasePath; - -#if NETFX_CORE - SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path); -#endif - - Sqlite3DatabaseHandle handle; - -#if SILVERLIGHT || USE_CSHARP_SQLITE - var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero); -#else - // open using the byte[] - // in the case where the path may include Unicode - // force open to using UTF-8 using sqlite3_open_v2 - var databasePathAsBytes = GetNullTerminatedUtf8 (DatabasePath); - var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero); -#endif - - Handle = handle; - if (r != SQLite3.Result.OK) { - throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r)); - } - _open = true; - - StoreDateTimeAsTicks = storeDateTimeAsTicks; - - BusyTimeout = TimeSpan.FromSeconds (0.1); - } - - static SQLiteConnection () - { - if (_preserveDuringLinkMagic) { - var ti = new ColumnInfo (); - ti.Name = "magic"; - } - } - - public void EnableLoadExtension(int onoff) - { - SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff); - if (r != SQLite3.Result.OK) { - string msg = SQLite3.GetErrmsg (Handle); - throw SQLiteException.New (r, msg); - } - } - - static byte[] GetNullTerminatedUtf8 (string s) - { - var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s); - var bytes = new byte [utf8Length + 1]; - utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); - return bytes; - } - - /// - /// Used to list some code that we want the MonoTouch linker - /// to see, but that we never want to actually execute. - /// - static bool _preserveDuringLinkMagic; - - /// - /// Sets a busy handler to sleep the specified amount of time when a table is locked. - /// The handler will sleep multiple times until a total time of has accumulated. - /// - public TimeSpan BusyTimeout { - get { return _busyTimeout; } - set { - _busyTimeout = value; - if (Handle != NullHandle) { - SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds); - } - } - } - - /// - /// Returns the mappings from types to tables that the connection - /// currently understands. - /// - public IEnumerable TableMappings { - get { - return _tables != null ? _tables.Values : Enumerable.Empty (); - } - } - - /// - /// Retrieves the mapping that is automatically generated for the given type. - /// - /// - /// The type whose mapping to the database is returned. - /// - /// - /// Optional flags allowing implicit PK and indexes based on naming conventions - /// - /// - /// The mapping represents the schema of the columns of the database and contains - /// methods to set and get properties of objects. - /// - public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) - { - if (_mappings == null) { - _mappings = new Dictionary (); - } - TableMapping map; - if (!_mappings.TryGetValue (type.FullName, out map)) { - map = new TableMapping (type, createFlags); - _mappings [type.FullName] = map; - } - return map; - } - - /// - /// Retrieves the mapping that is automatically generated for the given type. - /// - /// - /// The mapping represents the schema of the columns of the database and contains - /// methods to set and get properties of objects. - /// - public TableMapping GetMapping () - { - return GetMapping (typeof (T)); - } - - private struct IndexedColumn - { - public int Order; - public string ColumnName; - } - - private struct IndexInfo - { - public string IndexName; - public string TableName; - public bool Unique; - public List Columns; - } - - /// - /// Executes a "drop table" on the database. This is non-recoverable. - /// - public int DropTable() - { - var map = GetMapping (typeof (T)); - - var query = string.Format("drop table if exists \"{0}\"", map.TableName); - - return Execute (query); - } - - /// - /// Executes a "create table if not exists" on the database. It also - /// creates any specified indexes on the columns of the table. It uses - /// a schema automatically generated from the specified type. You can - /// later access this schema by calling GetMapping. - /// - /// - /// The number of entries added to the database schema. - /// - public int CreateTable(CreateFlags createFlags = CreateFlags.None) - { - return CreateTable(typeof (T), createFlags); - } - - /// - /// Executes a "create table if not exists" on the database. It also - /// creates any specified indexes on the columns of the table. It uses - /// a schema automatically generated from the specified type. You can - /// later access this schema by calling GetMapping. - /// - /// Type to reflect to a database table. - /// Optional flags allowing implicit PK and indexes based on naming conventions. - /// - /// The number of entries added to the database schema. - /// - public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) - { - if (_tables == null) { - _tables = new Dictionary (); - } - TableMapping map; - if (!_tables.TryGetValue (ty.FullName, out map)) { - map = GetMapping (ty, createFlags); - _tables.Add (ty.FullName, map); - } - var query = "create table if not exists \"" + map.TableName + "\"(\n"; - - var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks)); - var decl = string.Join (",\n", decls.ToArray ()); - query += decl; - query += ")"; - - var count = Execute (query); - - if (count == 0) { //Possible bug: This always seems to return 0? - // Table already exists, migrate it - MigrateTable (map); - } - - var indexes = new Dictionary (); - foreach (var c in map.Columns) { - foreach (var i in c.Indices) { - var iname = i.Name ?? map.TableName + "_" + c.Name; - IndexInfo iinfo; - if (!indexes.TryGetValue (iname, out iinfo)) { - iinfo = new IndexInfo { - IndexName = iname, - TableName = map.TableName, - Unique = i.Unique, - Columns = new List () - }; - indexes.Add (iname, iinfo); - } - - if (i.Unique != iinfo.Unique) - throw new Exception ("All the columns in an index must have the same value for their Unique property"); - - iinfo.Columns.Add (new IndexedColumn { - Order = i.Order, - ColumnName = c.Name - }); - } - } - - foreach (var indexName in indexes.Keys) { - var index = indexes[indexName]; - var columns = index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray(); - count += CreateIndex(indexName, index.TableName, columns, index.Unique); - } - - return count; - } - - /// - /// Creates an index for the specified table and columns. - /// - /// Name of the index to create - /// Name of the database table - /// An array of column names to index - /// Whether the index should be unique - public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false) - { - const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; - var sql = String.Format(sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName); - return Execute(sql); - } - - /// - /// Creates an index for the specified table and column. - /// - /// Name of the index to create - /// Name of the database table - /// Name of the column to index - /// Whether the index should be unique - public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) - { - return CreateIndex(indexName, tableName, new string[] { columnName }, unique); - } - - /// - /// Creates an index for the specified table and column. - /// - /// Name of the database table - /// Name of the column to index - /// Whether the index should be unique - public int CreateIndex(string tableName, string columnName, bool unique = false) - { - return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique); - } - - /// - /// Creates an index for the specified table and columns. - /// - /// Name of the database table - /// An array of column names to index - /// Whether the index should be unique - public int CreateIndex(string tableName, string[] columnNames, bool unique = false) - { - return CreateIndex(tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique); - } - - /// - /// Creates an index for the specified object property. - /// e.g. CreateIndex(c => c.Name); - /// - /// Type to reflect to a database table. - /// Property to index - /// Whether the index should be unique - public void CreateIndex(Expression> property, bool unique = false) - { - MemberExpression mx; - if (property.Body.NodeType == ExpressionType.Convert) - { - mx = ((UnaryExpression)property.Body).Operand as MemberExpression; - } - else - { - mx= (property.Body as MemberExpression); - } - var propertyInfo = mx.Member as PropertyInfo; - if (propertyInfo == null) - { - throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); - } - - var propName = propertyInfo.Name; - - var map = GetMapping(); - var colName = map.FindColumnWithPropertyName(propName).Name; - - CreateIndex(map.TableName, colName, unique); - } - - public class ColumnInfo - { -// public int cid { get; set; } - - [Column ("name")] - public string Name { get; set; } - -// [Column ("type")] -// public string ColumnType { get; set; } - - public int notnull { get; set; } - -// public string dflt_value { get; set; } - -// public int pk { get; set; } - - public override string ToString () - { - return Name; - } - } - - public List GetTableInfo (string tableName) - { - var query = "pragma table_info(\"" + tableName + "\")"; - return Query (query); - } - - void MigrateTable (TableMapping map) - { - var existingCols = GetTableInfo (map.TableName); - - var toBeAdded = new List (); - - foreach (var p in map.Columns) { - var found = false; - foreach (var c in existingCols) { - found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0); - if (found) - break; - } - if (!found) { - toBeAdded.Add (p); - } - } - - foreach (var p in toBeAdded) { - var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks); - Execute (addCol); - } - } - - /// - /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class. - /// - /// - protected virtual SQLiteCommand NewCommand () - { - return new SQLiteCommand (this); - } - - /// - /// Creates a new SQLiteCommand given the command text with arguments. Place a '?' - /// in the command text for each of the arguments. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the command text. - /// - /// - /// A - /// - public SQLiteCommand CreateCommand (string cmdText, params object[] ps) - { - if (!_open) - throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database"); - - var cmd = NewCommand (); - cmd.CommandText = cmdText; - foreach (var o in ps) { - cmd.Bind (o); - } - return cmd; - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// Use this method instead of Query when you don't expect rows back. Such cases include - /// INSERTs, UPDATEs, and DELETEs. - /// You can set the Trace or TimeExecution properties of the connection - /// to profile execution. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// The number of rows modified in the database as a result of this execution. - /// - public int Execute (string query, params object[] args) - { - var cmd = CreateCommand (query, args); - - if (TimeExecution) { - if (_sw == null) { - _sw = new Stopwatch (); - } - _sw.Reset (); - _sw.Start (); - } - - var r = cmd.ExecuteNonQuery (); - - if (TimeExecution) { - _sw.Stop (); - _elapsedMilliseconds += _sw.ElapsedMilliseconds; - Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); - } - - return r; - } - - public T ExecuteScalar (string query, params object[] args) - { - var cmd = CreateCommand (query, args); - - if (TimeExecution) { - if (_sw == null) { - _sw = new Stopwatch (); - } - _sw.Reset (); - _sw.Start (); - } - - var r = cmd.ExecuteScalar (); - - if (TimeExecution) { - _sw.Stop (); - _elapsedMilliseconds += _sw.ElapsedMilliseconds; - Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); - } - - return r; - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the mapping automatically generated for - /// the given type. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// - public List Query (string query, params object[] args) where T : new() - { - var cmd = CreateCommand (query, args); - return cmd.ExecuteQuery (); - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the mapping automatically generated for - /// the given type. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// The enumerator will call sqlite3_step on each call to MoveNext, so the database - /// connection must remain open for the lifetime of the enumerator. - /// - public IEnumerable DeferredQuery(string query, params object[] args) where T : new() - { - var cmd = CreateCommand(query, args); - return cmd.ExecuteDeferredQuery(); - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the specified mapping. This function is - /// only used by libraries in order to query the database via introspection. It is - /// normally not used. - /// - /// - /// A to use to convert the resulting rows - /// into objects. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// - public List Query (TableMapping map, string query, params object[] args) - { - var cmd = CreateCommand (query, args); - return cmd.ExecuteQuery (map); - } - - /// - /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' - /// in the command text for each of the arguments and then executes that command. - /// It returns each row of the result using the specified mapping. This function is - /// only used by libraries in order to query the database via introspection. It is - /// normally not used. - /// - /// - /// A to use to convert the resulting rows - /// into objects. - /// - /// - /// The fully escaped SQL. - /// - /// - /// Arguments to substitute for the occurences of '?' in the query. - /// - /// - /// An enumerable with one result for each row returned by the query. - /// The enumerator will call sqlite3_step on each call to MoveNext, so the database - /// connection must remain open for the lifetime of the enumerator. - /// - public IEnumerable DeferredQuery(TableMapping map, string query, params object[] args) - { - var cmd = CreateCommand(query, args); - return cmd.ExecuteDeferredQuery(map); - } - - /// - /// Returns a queryable interface to the table represented by the given type. - /// - /// - /// A queryable object that is able to translate Where, OrderBy, and Take - /// queries into native SQL. - /// - public TableQuery Table () where T : new() - { - return new TableQuery (this); - } - - /// - /// Attempts to retrieve an object with the given primary key from the table - /// associated with the specified type. Use of this method requires that - /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). - /// - /// - /// The primary key. - /// - /// - /// The object with the given primary key. Throws a not found exception - /// if the object is not found. - /// - public T Get (object pk) where T : new() - { - var map = GetMapping (typeof(T)); - return Query (map.GetByPrimaryKeySql, pk).First (); - } - - /// - /// Attempts to retrieve the first object that matches the predicate from the table - /// associated with the specified type. - /// - /// - /// A predicate for which object to find. - /// - /// - /// The object that matches the given predicate. Throws a not found exception - /// if the object is not found. - /// - public T Get (Expression> predicate) where T : new() - { - return Table ().Where (predicate).First (); - } - - /// - /// Attempts to retrieve an object with the given primary key from the table - /// associated with the specified type. Use of this method requires that - /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). - /// - /// - /// The primary key. - /// - /// - /// The object with the given primary key or null - /// if the object is not found. - /// - public T Find (object pk) where T : new () - { - var map = GetMapping (typeof (T)); - return Query (map.GetByPrimaryKeySql, pk).FirstOrDefault (); - } - - /// - /// Attempts to retrieve an object with the given primary key from the table - /// associated with the specified type. Use of this method requires that - /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). - /// - /// - /// The primary key. - /// - /// - /// The TableMapping used to identify the object type. - /// - /// - /// The object with the given primary key or null - /// if the object is not found. - /// - public object Find (object pk, TableMapping map) - { - return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault (); - } - - /// - /// Attempts to retrieve the first object that matches the predicate from the table - /// associated with the specified type. - /// - /// - /// A predicate for which object to find. - /// - /// - /// The object that matches the given predicate or null - /// if the object is not found. - /// - public T Find (Expression> predicate) where T : new() - { - return Table ().Where (predicate).FirstOrDefault (); - } - - /// - /// Whether has been called and the database is waiting for a . - /// - public bool IsInTransaction { - get { return _transactionDepth > 0; } - } - - /// - /// Begins a new transaction. Call to end the transaction. - /// - /// Throws if a transaction has already begun. - public void BeginTransaction () - { - // The BEGIN command only works if the transaction stack is empty, - // or in other words if there are no pending transactions. - // If the transaction stack is not empty when the BEGIN command is invoked, - // then the command fails with an error. - // Rather than crash with an error, we will just ignore calls to BeginTransaction - // that would result in an error. - if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) { - try { - Execute ("begin transaction"); - } catch (Exception ex) { - var sqlExp = ex as SQLiteException; - if (sqlExp != null) { - // It is recommended that applications respond to the errors listed below - // by explicitly issuing a ROLLBACK command. - // TODO: This rollback failsafe should be localized to all throw sites. - switch (sqlExp.Result) { - case SQLite3.Result.IOError: - case SQLite3.Result.Full: - case SQLite3.Result.Busy: - case SQLite3.Result.NoMem: - case SQLite3.Result.Interrupt: - RollbackTo (null, true); - break; - } - } else { - // Call decrement and not VolatileWrite in case we've already - // created a transaction point in SaveTransactionPoint since the catch. - Interlocked.Decrement (ref _transactionDepth); - } - - throw; - } - } else { - // Calling BeginTransaction on an already open transaction is invalid - throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction."); - } - } - - /// - /// Creates a savepoint in the database at the current point in the transaction timeline. - /// Begins a new transaction if one is not in progress. - /// - /// Call to undo transactions since the returned savepoint. - /// Call to commit transactions after the savepoint returned here. - /// Call to end the transaction, committing all changes. - /// - /// A string naming the savepoint. - public string SaveTransactionPoint () - { - int depth = Interlocked.Increment (ref _transactionDepth) - 1; - string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth; - - try { - Execute ("savepoint " + retVal); - } catch (Exception ex) { - var sqlExp = ex as SQLiteException; - if (sqlExp != null) { - // It is recommended that applications respond to the errors listed below - // by explicitly issuing a ROLLBACK command. - // TODO: This rollback failsafe should be localized to all throw sites. - switch (sqlExp.Result) { - case SQLite3.Result.IOError: - case SQLite3.Result.Full: - case SQLite3.Result.Busy: - case SQLite3.Result.NoMem: - case SQLite3.Result.Interrupt: - RollbackTo (null, true); - break; - } - } else { - Interlocked.Decrement (ref _transactionDepth); - } - - throw; - } - - return retVal; - } - - /// - /// Rolls back the transaction that was begun by or . - /// - public void Rollback () - { - RollbackTo (null, false); - } - - /// - /// Rolls back the savepoint created by or SaveTransactionPoint. - /// - /// The name of the savepoint to roll back to, as returned by . If savepoint is null or empty, this method is equivalent to a call to - public void RollbackTo (string savepoint) - { - RollbackTo (savepoint, false); - } - - /// - /// Rolls back the transaction that was begun by . - /// - /// true to avoid throwing exceptions, false otherwise - void RollbackTo (string savepoint, bool noThrow) - { - // Rolling back without a TO clause rolls backs all transactions - // and leaves the transaction stack empty. - try { - if (String.IsNullOrEmpty (savepoint)) { - if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) { - Execute ("rollback"); - } - } else { - DoSavePointExecute (savepoint, "rollback to "); - } - } catch (SQLiteException) { - if (!noThrow) - throw; - - } - // No need to rollback if there are no transactions open. - } - - /// - /// Releases a savepoint returned from . Releasing a savepoint - /// makes changes since that savepoint permanent if the savepoint began the transaction, - /// or otherwise the changes are permanent pending a call to . - /// - /// The RELEASE command is like a COMMIT for a SAVEPOINT. - /// - /// The name of the savepoint to release. The string should be the result of a call to - public void Release (string savepoint) - { - DoSavePointExecute (savepoint, "release "); - } - - void DoSavePointExecute (string savepoint, string cmd) - { - // Validate the savepoint - int firstLen = savepoint.IndexOf ('D'); - if (firstLen >= 2 && savepoint.Length > firstLen + 1) { - int depth; - if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) { - // TODO: Mild race here, but inescapable without locking almost everywhere. - if (0 <= depth && depth < _transactionDepth) { -#if NETFX_CORE - Volatile.Write (ref _transactionDepth, depth); -#elif SILVERLIGHT - _transactionDepth = depth; -#else - Thread.VolatileWrite (ref _transactionDepth, depth); -#endif - Execute (cmd + savepoint); - return; - } - } - } - - throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint"); - } - - /// - /// Commits the transaction that was begun by . - /// - public void Commit () - { - if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) { - Execute ("commit"); - } - // Do nothing on a commit with no open transaction - } - - /// - /// Executes within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an - /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception - /// is rethrown. - /// - /// - /// The to perform within a transaction. can contain any number - /// of operations on the connection but should never call or - /// . - /// - public void RunInTransaction (Action action) - { - try { - var savePoint = SaveTransactionPoint (); - action (); - Release (savePoint); - } catch (Exception) { - Rollback (); - throw; - } - } - - /// - /// Inserts all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// The number of rows added to the table. - /// - public int InsertAll (System.Collections.IEnumerable objects) - { - var c = 0; - RunInTransaction(() => { - foreach (var r in objects) { - c += Insert (r); - } - }); - return c; - } - - /// - /// Inserts all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The number of rows added to the table. - /// - public int InsertAll (System.Collections.IEnumerable objects, string extra) - { - var c = 0; - RunInTransaction (() => { - foreach (var r in objects) { - c += Insert (r, extra); - } - }); - return c; - } - - /// - /// Inserts all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int InsertAll (System.Collections.IEnumerable objects, Type objType) - { - var c = 0; - RunInTransaction (() => { - foreach (var r in objects) { - c += Insert (r, objType); - } - }); - return c; - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj) - { - if (obj == null) { - return 0; - } - return Insert (obj, "", obj.GetType ()); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// If a UNIQUE constraint violation occurs with - /// some pre-existing object, this function deletes - /// the old object. - /// - /// - /// The object to insert. - /// - /// - /// The number of rows modified. - /// - public int InsertOrReplace (object obj) - { - if (obj == null) { - return 0; - } - return Insert (obj, "OR REPLACE", obj.GetType ()); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, Type objType) - { - return Insert (obj, "", objType); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// If a UNIQUE constraint violation occurs with - /// some pre-existing object, this function deletes - /// the old object. - /// - /// - /// The object to insert. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows modified. - /// - public int InsertOrReplace (object obj, Type objType) - { - return Insert (obj, "OR REPLACE", objType); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, string extra) - { - if (obj == null) { - return 0; - } - return Insert (obj, extra, obj.GetType ()); - } - - /// - /// Inserts the given object and retrieves its - /// auto incremented primary key if it has one. - /// - /// - /// The object to insert. - /// - /// - /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows added to the table. - /// - public int Insert (object obj, string extra, Type objType) - { - if (obj == null || objType == null) { - return 0; - } - - - var map = GetMapping (objType); - -#if NETFX_CORE - if (map.PK != null && map.PK.IsAutoGuid) - { - // no GetProperty so search our way up the inheritance chain till we find it - PropertyInfo prop; - while (objType != null) - { - var info = objType.GetTypeInfo(); - prop = info.GetDeclaredProperty(map.PK.PropertyName); - if (prop != null) - { - if (prop.GetValue(obj, null).Equals(Guid.Empty)) - { - prop.SetValue(obj, Guid.NewGuid(), null); - } - break; - } - - objType = info.BaseType; - } - } -#else - if (map.PK != null && map.PK.IsAutoGuid) { - var prop = objType.GetProperty(map.PK.PropertyName); - if (prop != null) { - if (prop.GetValue(obj, null).Equals(Guid.Empty)) { - prop.SetValue(obj, Guid.NewGuid(), null); - } - } - } -#endif - - - var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; - - var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns; - var vals = new object[cols.Length]; - for (var i = 0; i < vals.Length; i++) { - vals [i] = cols [i].GetValue (obj); - } - - var insertCmd = map.GetInsertCommand (this, extra); - int count; - - try { - count = insertCmd.ExecuteNonQuery (vals); - } - catch (SQLiteException ex) { - - if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj); - } - throw; - } - - if (map.HasAutoIncPK) - { - var id = SQLite3.LastInsertRowid (Handle); - map.SetAutoIncPK (obj, id); - } - - return count; - } - - /// - /// Updates all of the columns of a table using the specified object - /// except for its primary key. - /// The object is required to have a primary key. - /// - /// - /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. - /// - /// - /// The number of rows updated. - /// - public int Update (object obj) - { - if (obj == null) { - return 0; - } - return Update (obj, obj.GetType ()); - } - - /// - /// Updates all of the columns of a table using the specified object - /// except for its primary key. - /// The object is required to have a primary key. - /// - /// - /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. - /// - /// - /// The type of object to insert. - /// - /// - /// The number of rows updated. - /// - public int Update (object obj, Type objType) - { - int rowsAffected = 0; - if (obj == null || objType == null) { - return 0; - } - - var map = GetMapping (objType); - - var pk = map.PK; - - if (pk == null) { - throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK"); - } - - var cols = from p in map.Columns - where p != pk - select p; - var vals = from c in cols - select c.GetValue (obj); - var ps = new List (vals); - ps.Add (pk.GetValue (obj)); - var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols - select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); - - try { - rowsAffected = Execute (q, ps.ToArray ()); - } - catch (SQLiteException ex) { - - if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - throw NotNullConstraintViolationException.New (ex, map, obj); - } - - throw ex; - } - - return rowsAffected; - } - - /// - /// Updates all specified objects. - /// - /// - /// An of the objects to insert. - /// - /// - /// The number of rows modified. - /// - public int UpdateAll (System.Collections.IEnumerable objects) - { - var c = 0; - RunInTransaction (() => { - foreach (var r in objects) { - c += Update (r); - } - }); - return c; - } - - /// - /// Deletes the given object from the database using its primary key. - /// - /// - /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. - /// - /// - /// The number of rows deleted. - /// - public int Delete (object objectToDelete) - { - var map = GetMapping (objectToDelete.GetType ()); - var pk = map.PK; - if (pk == null) { - throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); - } - var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); - return Execute (q, pk.GetValue (objectToDelete)); - } - - /// - /// Deletes the object with the specified primary key. - /// - /// - /// The primary key of the object to delete. - /// - /// - /// The number of objects deleted. - /// - /// - /// The type of object. - /// - public int Delete (object primaryKey) - { - var map = GetMapping (typeof (T)); - var pk = map.PK; - if (pk == null) { - throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); - } - var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); - return Execute (q, primaryKey); - } - - /// - /// Deletes all the objects from the specified table. - /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the - /// specified table. Do you really want to do that? - /// - /// - /// The number of objects deleted. - /// - /// - /// The type of objects to delete. - /// - public int DeleteAll () - { - var map = GetMapping (typeof (T)); - var query = string.Format("delete from \"{0}\"", map.TableName); - return Execute (query); - } - - ~SQLiteConnection () - { - Dispose (false); - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } - - protected virtual void Dispose (bool disposing) - { - Close (); - } - - public void Close () - { - if (_open && Handle != NullHandle) { - try { - if (_mappings != null) { - foreach (var sqlInsertCommand in _mappings.Values) { - sqlInsertCommand.Dispose(); - } - } - var r = SQLite3.Close (Handle); - if (r != SQLite3.Result.OK) { - string msg = SQLite3.GetErrmsg (Handle); - throw SQLiteException.New (r, msg); - } - } - finally { - Handle = NullHandle; - _open = false; - } - } - } - } - - /// - /// Represents a parsed connection string. - /// - class SQLiteConnectionString - { - public string ConnectionString { get; private set; } - public string DatabasePath { get; private set; } - public bool StoreDateTimeAsTicks { get; private set; } - -#if NETFX_CORE - static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; -#endif - - public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks) - { - ConnectionString = databasePath; - StoreDateTimeAsTicks = storeDateTimeAsTicks; - -#if NETFX_CORE - DatabasePath = System.IO.Path.Combine (MetroStyleDataPath, databasePath); -#else - DatabasePath = databasePath; -#endif - } - } - - [AttributeUsage (AttributeTargets.Class)] - public class TableAttribute : Attribute - { - public string Name { get; set; } - - public TableAttribute (string name) - { - Name = name; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class ColumnAttribute : Attribute - { - public string Name { get; set; } - - public ColumnAttribute (string name) - { - Name = name; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class PrimaryKeyAttribute : Attribute - { - } - - [AttributeUsage (AttributeTargets.Property)] - public class AutoIncrementAttribute : Attribute - { - } - - [AttributeUsage (AttributeTargets.Property)] - public class IndexedAttribute : Attribute - { - public string Name { get; set; } - public int Order { get; set; } - public virtual bool Unique { get; set; } - - public IndexedAttribute() - { - } - - public IndexedAttribute(string name, int order) - { - Name = name; - Order = order; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class IgnoreAttribute : Attribute - { - } - - [AttributeUsage (AttributeTargets.Property)] - public class UniqueAttribute : IndexedAttribute - { - public override bool Unique { - get { return true; } - set { /* throw? */ } - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class MaxLengthAttribute : Attribute - { - public int Value { get; private set; } - - public MaxLengthAttribute (int length) - { - Value = length; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class CollationAttribute: Attribute - { - public string Value { get; private set; } - - public CollationAttribute (string collation) - { - Value = collation; - } - } - - [AttributeUsage (AttributeTargets.Property)] - public class NotNullAttribute : Attribute - { - } - - public class TableMapping - { - public Type MappedType { get; private set; } - - public string TableName { get; private set; } - - public Column[] Columns { get; private set; } - - public Column PK { get; private set; } - - public string GetByPrimaryKeySql { get; private set; } - - Column _autoPk; - Column[] _insertColumns; - Column[] _insertOrReplaceColumns; - - public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None) - { - MappedType = type; - -#if NETFX_CORE - var tableAttr = (TableAttribute)System.Reflection.CustomAttributeExtensions - .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true); -#else - var tableAttr = (TableAttribute)type.GetCustomAttributes (typeof (TableAttribute), true).FirstOrDefault (); -#endif - - TableName = tableAttr != null ? tableAttr.Name : MappedType.Name; - -#if !NETFX_CORE - var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); -#else - var props = from p in MappedType.GetRuntimeProperties() - where ((p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic) || (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic)) - select p; -#endif - var cols = new List (); - foreach (var p in props) { -#if !NETFX_CORE - var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0; -#else - var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Count() > 0; -#endif - if (p.CanWrite && !ignore) { - cols.Add (new Column (p, createFlags)); - } - } - Columns = cols.ToArray (); - foreach (var c in Columns) { - if (c.IsAutoInc && c.IsPK) { - _autoPk = c; - } - if (c.IsPK) { - PK = c; - } - } - - HasAutoIncPK = _autoPk != null; - - if (PK != null) { - GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name); - } - else { - // People should not be calling Get/Find without a PK - GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName); - } - } - - public bool HasAutoIncPK { get; private set; } - - public void SetAutoIncPK (object obj, long id) - { - if (_autoPk != null) { - _autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null)); - } - } - - public Column[] InsertColumns { - get { - if (_insertColumns == null) { - _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray (); - } - return _insertColumns; - } - } - - public Column[] InsertOrReplaceColumns { - get { - if (_insertOrReplaceColumns == null) { - _insertOrReplaceColumns = Columns.ToArray (); - } - return _insertOrReplaceColumns; - } - } - - public Column FindColumnWithPropertyName (string propertyName) - { - var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName); - return exact; - } - - public Column FindColumn (string columnName) - { - var exact = Columns.FirstOrDefault (c => c.Name == columnName); - return exact; - } - - PreparedSqlLiteInsertCommand _insertCommand; - string _insertCommandExtra; - - public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, string extra) - { - if (_insertCommand == null) { - _insertCommand = CreateInsertCommand(conn, extra); - _insertCommandExtra = extra; - } - else if (_insertCommandExtra != extra) { - _insertCommand.Dispose(); - _insertCommand = CreateInsertCommand(conn, extra); - _insertCommandExtra = extra; - } - return _insertCommand; - } - - PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra) - { - var cols = InsertColumns; - string insertSql; - if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) - { - insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra); - } - else - { - var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; - - if (replacing) { - cols = InsertOrReplaceColumns; - } - - insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName, - string.Join(",", (from c in cols - select "\"" + c.Name + "\"").ToArray()), - string.Join(",", (from c in cols - select "?").ToArray()), extra); - - } - - var insertCommand = new PreparedSqlLiteInsertCommand(conn); - insertCommand.CommandText = insertSql; - return insertCommand; - } - - protected internal void Dispose() - { - if (_insertCommand != null) { - _insertCommand.Dispose(); - _insertCommand = null; - } - } - - public class Column - { - PropertyInfo _prop; - - public string Name { get; private set; } - - public string PropertyName { get { return _prop.Name; } } - - public Type ColumnType { get; private set; } - - public string Collation { get; private set; } - - public bool IsAutoInc { get; private set; } - public bool IsAutoGuid { get; private set; } - - public bool IsPK { get; private set; } - - public IEnumerable Indices { get; set; } - - public bool IsNullable { get; private set; } - - public int? MaxStringLength { get; private set; } - - public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) - { - var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); - - _prop = prop; - Name = colAttr == null ? prop.Name : colAttr.Name; - //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead - ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; - Collation = Orm.Collation(prop); - - IsPK = Orm.IsPK(prop) || - (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) && - string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); - - var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); - IsAutoGuid = isAuto && ColumnType == typeof(Guid); - IsAutoInc = isAuto && !IsAutoGuid; - - Indices = Orm.GetIndices(prop); - if (!Indices.Any() - && !IsPK - && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) - && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) - ) - { - Indices = new IndexedAttribute[] { new IndexedAttribute() }; - } - IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop)); - MaxStringLength = Orm.MaxStringLength(prop); - } - - public void SetValue (object obj, object val) - { - _prop.SetValue (obj, val, null); - } - - public object GetValue (object obj) - { - return _prop.GetValue (obj, null); - } - } - } - - public static class Orm - { - public const int DefaultMaxStringLength = 140; - public const string ImplicitPkName = "Id"; - public const string ImplicitIndexSuffix = "Id"; - - public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks) - { - string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks) + " "; - - if (p.IsPK) { - decl += "primary key "; - } - if (p.IsAutoInc) { - decl += "autoincrement "; - } - if (!p.IsNullable) { - decl += "not null "; - } - if (!string.IsNullOrEmpty (p.Collation)) { - decl += "collate " + p.Collation + " "; - } - - return decl; - } - - public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks) - { - var clrType = p.ColumnType; - if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) { - return "integer"; - } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) { - return "bigint"; - } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) { - return "float"; - } else if (clrType == typeof(String)) { - int? len = p.MaxStringLength; - - if (len.HasValue) - return "varchar(" + len.Value + ")"; - - return "varchar"; - } else if (clrType == typeof(TimeSpan)) { - return "bigint"; - } else if (clrType == typeof(DateTime)) { - return storeDateTimeAsTicks ? "bigint" : "datetime"; - } else if (clrType == typeof(DateTimeOffset)) { - return "bigint"; -#if !NETFX_CORE - } else if (clrType.IsEnum) { -#else - } else if (clrType.GetTypeInfo().IsEnum) { -#endif - return "integer"; - } else if (clrType == typeof(byte[])) { - return "blob"; - } else if (clrType == typeof(Guid)) { - return "varchar(36)"; - } else { - throw new NotSupportedException ("Don't know about " + clrType); - } - } - - public static bool IsPK (MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true); -#if !NETFX_CORE - return attrs.Length > 0; -#else - return attrs.Count() > 0; -#endif - } - - public static string Collation (MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof(CollationAttribute), true); -#if !NETFX_CORE - if (attrs.Length > 0) { - return ((CollationAttribute)attrs [0]).Value; -#else - if (attrs.Count() > 0) { - return ((CollationAttribute)attrs.First()).Value; -#endif - } else { - return string.Empty; - } - } - - public static bool IsAutoInc (MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true); -#if !NETFX_CORE - return attrs.Length > 0; -#else - return attrs.Count() > 0; -#endif - } - - public static IEnumerable GetIndices(MemberInfo p) - { - var attrs = p.GetCustomAttributes(typeof(IndexedAttribute), true); - return attrs.Cast(); - } - - public static int? MaxStringLength(PropertyInfo p) - { - var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true); -#if !NETFX_CORE - if (attrs.Length > 0) - return ((MaxLengthAttribute)attrs [0]).Value; -#else - if (attrs.Count() > 0) - return ((MaxLengthAttribute)attrs.First()).Value; -#endif - - return null; - } - - public static bool IsMarkedNotNull(MemberInfo p) - { - var attrs = p.GetCustomAttributes (typeof (NotNullAttribute), true); -#if !NETFX_CORE - return attrs.Length > 0; -#else - return attrs.Count() > 0; -#endif - } - } - - public partial class SQLiteCommand - { - SQLiteConnection _conn; - private List _bindings; - - public string CommandText { get; set; } - - internal SQLiteCommand (SQLiteConnection conn) - { - _conn = conn; - _bindings = new List (); - CommandText = ""; - } - - public int ExecuteNonQuery () - { - if (_conn.Trace) { - Debug.WriteLine ("Executing: " + this); - } - - var r = SQLite3.Result.OK; - var stmt = Prepare (); - r = SQLite3.Step (stmt); - Finalize (stmt); - if (r == SQLite3.Result.Done) { - int rowsAffected = SQLite3.Changes (_conn.Handle); - return rowsAffected; - } else if (r == SQLite3.Result.Error) { - string msg = SQLite3.GetErrmsg (_conn.Handle); - throw SQLiteException.New (r, msg); - } - else if (r == SQLite3.Result.Constraint) { - if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle)); - } - } - - throw SQLiteException.New(r, r.ToString()); - } - - public IEnumerable ExecuteDeferredQuery () - { - return ExecuteDeferredQuery(_conn.GetMapping(typeof(T))); - } - - public List ExecuteQuery () - { - return ExecuteDeferredQuery(_conn.GetMapping(typeof(T))).ToList(); - } - - public List ExecuteQuery (TableMapping map) - { - return ExecuteDeferredQuery(map).ToList(); - } - - /// - /// Invoked every time an instance is loaded from the database. - /// - /// - /// The newly created object. - /// - /// - /// This can be overridden in combination with the - /// method to hook into the life-cycle of objects. - /// - /// Type safety is not possible because MonoTouch does not support virtual generic methods. - /// - protected virtual void OnInstanceCreated (object obj) - { - // Can be overridden. - } - - public IEnumerable ExecuteDeferredQuery (TableMapping map) - { - if (_conn.Trace) { - Debug.WriteLine ("Executing Query: " + this); - } - - var stmt = Prepare (); - try - { - var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)]; - - for (int i = 0; i < cols.Length; i++) { - var name = SQLite3.ColumnName16 (stmt, i); - cols [i] = map.FindColumn (name); - } - - while (SQLite3.Step (stmt) == SQLite3.Result.Row) { - var obj = Activator.CreateInstance(map.MappedType); - for (int i = 0; i < cols.Length; i++) { - if (cols [i] == null) - continue; - var colType = SQLite3.ColumnType (stmt, i); - var val = ReadCol (stmt, i, colType, cols [i].ColumnType); - cols [i].SetValue (obj, val); - } - OnInstanceCreated (obj); - yield return (T)obj; - } - } - finally - { - SQLite3.Finalize(stmt); - } - } - - public T ExecuteScalar () - { - if (_conn.Trace) { - Debug.WriteLine ("Executing Query: " + this); - } - - T val = default(T); - - var stmt = Prepare (); - - try - { - var r = SQLite3.Step (stmt); - if (r == SQLite3.Result.Row) { - var colType = SQLite3.ColumnType (stmt, 0); - val = (T)ReadCol (stmt, 0, colType, typeof(T)); - } - else if (r == SQLite3.Result.Done) { - } - else - { - throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle)); - } - } - finally - { - Finalize (stmt); - } - - return val; - } - - public void Bind (string name, object val) - { - _bindings.Add (new Binding { - Name = name, - Value = val - }); - } - - public void Bind (object val) - { - Bind (null, val); - } - - public override string ToString () - { - var parts = new string[1 + _bindings.Count]; - parts [0] = CommandText; - var i = 1; - foreach (var b in _bindings) { - parts [i] = string.Format (" {0}: {1}", i - 1, b.Value); - i++; - } - return string.Join (Environment.NewLine, parts); - } - - Sqlite3Statement Prepare() - { - var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText); - BindAll (stmt); - return stmt; - } - - void Finalize (Sqlite3Statement stmt) - { - SQLite3.Finalize (stmt); - } - - void BindAll (Sqlite3Statement stmt) - { - int nextIdx = 1; - foreach (var b in _bindings) { - if (b.Name != null) { - b.Index = SQLite3.BindParameterIndex (stmt, b.Name); - } else { - b.Index = nextIdx++; - } - - BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks); - } - } - - internal static IntPtr NegativePointer = new IntPtr (-1); - - internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks) - { - if (value == null) { - SQLite3.BindNull (stmt, index); - } else { - if (value is Int32) { - SQLite3.BindInt (stmt, index, (int)value); - } else if (value is String) { - SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer); - } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { - SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is Boolean) { - SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0); - } else if (value is UInt32 || value is Int64) { - SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value)); - } else if (value is Single || value is Double || value is Decimal) { - SQLite3.BindDouble (stmt, index, Convert.ToDouble (value)); - } else if (value is TimeSpan) { - SQLite3.BindInt64(stmt, index, ((TimeSpan)value).Ticks); - } else if (value is DateTime) { - if (storeDateTimeAsTicks) { - SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks); - } - else { - SQLite3.BindText (stmt, index, ((DateTime)value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); - } - } else if (value is DateTimeOffset) { - SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks); -#if !NETFX_CORE - } else if (value.GetType().IsEnum) { -#else - } else if (value.GetType().GetTypeInfo().IsEnum) { -#endif - SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is byte[]){ - SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); - } else if (value is Guid) { - SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); - } else { - throw new NotSupportedException("Cannot store type: " + value.GetType()); - } - } - } - - class Binding - { - public string Name { get; set; } - - public object Value { get; set; } - - public int Index { get; set; } - } - - object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType) - { - if (type == SQLite3.ColType.Null) { - return null; - } else { - if (clrType == typeof(String)) { - return SQLite3.ColumnString (stmt, index); - } else if (clrType == typeof(Int32)) { - return (int)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Boolean)) { - return SQLite3.ColumnInt (stmt, index) == 1; - } else if (clrType == typeof(double)) { - return SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(float)) { - return (float)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(TimeSpan)) { - return new TimeSpan(SQLite3.ColumnInt64(stmt, index)); - } else if (clrType == typeof(DateTime)) { - if (_conn.StoreDateTimeAsTicks) { - return new DateTime (SQLite3.ColumnInt64 (stmt, index)); - } - else { - var text = SQLite3.ColumnString (stmt, index); - return DateTime.Parse (text); - } - } else if (clrType == typeof(DateTimeOffset)) { - return new DateTimeOffset(SQLite3.ColumnInt64 (stmt, index),TimeSpan.Zero); -#if !NETFX_CORE - } else if (clrType.IsEnum) { -#else - } else if (clrType.GetTypeInfo().IsEnum) { -#endif - return SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int64)) { - return SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(UInt32)) { - return (uint)SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(decimal)) { - return (decimal)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(Byte)) { - return (byte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(UInt16)) { - return (ushort)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int16)) { - return (short)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(sbyte)) { - return (sbyte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(byte[])) { - return SQLite3.ColumnByteArray (stmt, index); - } else if (clrType == typeof(Guid)) { - var text = SQLite3.ColumnString(stmt, index); - return new Guid(text); - } else{ - throw new NotSupportedException ("Don't know how to read " + clrType); - } - } - } - } - - /// - /// Since the insert never changed, we only need to prepare once. - /// - public class PreparedSqlLiteInsertCommand : IDisposable - { - public bool Initialized { get; set; } - - protected SQLiteConnection Connection { get; set; } - - public string CommandText { get; set; } - - protected Sqlite3Statement Statement { get; set; } - internal static readonly Sqlite3Statement NullStatement = default(Sqlite3Statement); - - internal PreparedSqlLiteInsertCommand (SQLiteConnection conn) - { - Connection = conn; - } - - public int ExecuteNonQuery (object[] source) - { - if (Connection.Trace) { - Debug.WriteLine ("Executing: " + CommandText); - } - - var r = SQLite3.Result.OK; - - if (!Initialized) { - Statement = Prepare (); - Initialized = true; - } - - //bind the values. - if (source != null) { - for (int i = 0; i < source.Length; i++) { - SQLiteCommand.BindParameter (Statement, i + 1, source [i], Connection.StoreDateTimeAsTicks); - } - } - r = SQLite3.Step (Statement); - - if (r == SQLite3.Result.Done) { - int rowsAffected = SQLite3.Changes (Connection.Handle); - SQLite3.Reset (Statement); - return rowsAffected; - } else if (r == SQLite3.Result.Error) { - string msg = SQLite3.GetErrmsg (Connection.Handle); - SQLite3.Reset (Statement); - throw SQLiteException.New (r, msg); - } else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) { - SQLite3.Reset (Statement); - throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle)); - } else { - SQLite3.Reset (Statement); - throw SQLiteException.New (r, r.ToString ()); - } - } - - protected virtual Sqlite3Statement Prepare () - { - var stmt = SQLite3.Prepare2 (Connection.Handle, CommandText); - return stmt; - } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } - - private void Dispose (bool disposing) - { - if (Statement != NullStatement) { - try { - SQLite3.Finalize (Statement); - } finally { - Statement = NullStatement; - Connection = null; - } - } - } - - ~PreparedSqlLiteInsertCommand () - { - Dispose (false); - } - } - - public abstract class BaseTableQuery - { - protected class Ordering - { - public string ColumnName { get; set; } - public bool Ascending { get; set; } - } - } - - public class TableQuery : BaseTableQuery, IEnumerable - { - public SQLiteConnection Connection { get; private set; } - - public TableMapping Table { get; private set; } - - Expression _where; - List _orderBys; - int? _limit; - int? _offset; - - BaseTableQuery _joinInner; - Expression _joinInnerKeySelector; - BaseTableQuery _joinOuter; - Expression _joinOuterKeySelector; - Expression _joinSelector; - - Expression _selector; - - TableQuery (SQLiteConnection conn, TableMapping table) - { - Connection = conn; - Table = table; - } - - public TableQuery (SQLiteConnection conn) - { - Connection = conn; - Table = Connection.GetMapping (typeof(T)); - } - - public TableQuery Clone () - { - var q = new TableQuery (Connection, Table); - q._where = _where; - q._deferred = _deferred; - if (_orderBys != null) { - q._orderBys = new List (_orderBys); - } - q._limit = _limit; - q._offset = _offset; - q._joinInner = _joinInner; - q._joinInnerKeySelector = _joinInnerKeySelector; - q._joinOuter = _joinOuter; - q._joinOuterKeySelector = _joinOuterKeySelector; - q._joinSelector = _joinSelector; - q._selector = _selector; - return q; - } - - public TableQuery Where (Expression> predExpr) - { - if (predExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)predExpr; - var pred = lambda.Body; - var q = Clone (); - q.AddWhere (pred); - return q; - } else { - throw new NotSupportedException ("Must be a predicate"); - } - } - - public TableQuery Take (int n) - { - var q = Clone (); - q._limit = n; - return q; - } - - public TableQuery Skip (int n) - { - var q = Clone (); - q._offset = n; - return q; - } - - public T ElementAt (int index) - { - return Skip (index).Take (1).First (); - } - - bool _deferred; - public TableQuery Deferred () - { - var q = Clone (); - q._deferred = true; - return q; - } - - public TableQuery OrderBy (Expression> orderExpr) - { - return AddOrderBy (orderExpr, true); - } - - public TableQuery OrderByDescending (Expression> orderExpr) - { - return AddOrderBy (orderExpr, false); - } - - public TableQuery ThenBy(Expression> orderExpr) - { - return AddOrderBy(orderExpr, true); - } - - public TableQuery ThenByDescending(Expression> orderExpr) - { - return AddOrderBy(orderExpr, false); - } - - private TableQuery AddOrderBy (Expression> orderExpr, bool asc) - { - if (orderExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)orderExpr; - - MemberExpression mem = null; - - var unary = lambda.Body as UnaryExpression; - if (unary != null && unary.NodeType == ExpressionType.Convert) { - mem = unary.Operand as MemberExpression; - } - else { - mem = lambda.Body as MemberExpression; - } - - if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { - var q = Clone (); - if (q._orderBys == null) { - q._orderBys = new List (); - } - q._orderBys.Add (new Ordering { - ColumnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name, - Ascending = asc - }); - return q; - } else { - throw new NotSupportedException ("Order By does not support: " + orderExpr); - } - } else { - throw new NotSupportedException ("Must be a predicate"); - } - } - - private void AddWhere (Expression pred) - { - if (_where == null) { - _where = pred; - } else { - _where = Expression.AndAlso (_where, pred); - } - } - - public TableQuery Join ( - TableQuery inner, - Expression> outerKeySelector, - Expression> innerKeySelector, - Expression> resultSelector) - { - var q = new TableQuery (Connection, Connection.GetMapping (typeof (TResult))) { - _joinOuter = this, - _joinOuterKeySelector = outerKeySelector, - _joinInner = inner, - _joinInnerKeySelector = innerKeySelector, - _joinSelector = resultSelector, - }; - return q; - } - - public TableQuery Select (Expression> selector) - { - var q = Clone (); - q._selector = selector; - return q; - } - - private SQLiteCommand GenerateCommand (string selectionList) - { - if (_joinInner != null && _joinOuter != null) { - throw new NotSupportedException ("Joins are not supported."); - } - else { - var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\""; - var args = new List (); - if (_where != null) { - var w = CompileExpr (_where, args); - cmdText += " where " + w.CommandText; - } - if ((_orderBys != null) && (_orderBys.Count > 0)) { - var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ()); - cmdText += " order by " + t; - } - if (_limit.HasValue) { - cmdText += " limit " + _limit.Value; - } - if (_offset.HasValue) { - if (!_limit.HasValue) { - cmdText += " limit -1 "; - } - cmdText += " offset " + _offset.Value; - } - return Connection.CreateCommand (cmdText, args.ToArray ()); - } - } - - class CompileResult - { - public string CommandText { get; set; } - - public object Value { get; set; } - } - - private CompileResult CompileExpr (Expression expr, List queryArgs) - { - if (expr == null) { - throw new NotSupportedException ("Expression is NULL"); - } else if (expr is BinaryExpression) { - var bin = (BinaryExpression)expr; - - var leftr = CompileExpr (bin.Left, queryArgs); - var rightr = CompileExpr (bin.Right, queryArgs); - - //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") - string text; - if (leftr.CommandText == "?" && leftr.Value == null) - text = CompileNullBinaryExpression(bin, rightr); - else if (rightr.CommandText == "?" && rightr.Value == null) - text = CompileNullBinaryExpression(bin, leftr); - else - text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")"; - return new CompileResult { CommandText = text }; - } else if (expr.NodeType == ExpressionType.Call) { - - var call = (MethodCallExpression)expr; - var args = new CompileResult[call.Arguments.Count]; - var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null; - - for (var i = 0; i < args.Length; i++) { - args [i] = CompileExpr (call.Arguments [i], queryArgs); - } - - var sqlCall = ""; - - if (call.Method.Name == "Like" && args.Length == 2) { - sqlCall = "(" + args [0].CommandText + " like " + args [1].CommandText + ")"; - } - else if (call.Method.Name == "Contains" && args.Length == 2) { - sqlCall = "(" + args [1].CommandText + " in " + args [0].CommandText + ")"; - } - else if (call.Method.Name == "Contains" && args.Length == 1) { - if (call.Object != null && call.Object.Type == typeof(string)) { - sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + " || '%'))"; - } - else { - sqlCall = "(" + args [0].CommandText + " in " + obj.CommandText + ")"; - } - } - else if (call.Method.Name == "StartsWith" && args.Length == 1) { - sqlCall = "(" + obj.CommandText + " like (" + args [0].CommandText + " || '%'))"; - } - else if (call.Method.Name == "EndsWith" && args.Length == 1) { - sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + "))"; - } - else if (call.Method.Name == "Equals" && args.Length == 1) { - sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))"; - } else if (call.Method.Name == "ToLower") { - sqlCall = "(lower(" + obj.CommandText + "))"; - } else if (call.Method.Name == "ToUpper") { - sqlCall = "(upper(" + obj.CommandText + "))"; - } else { - sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")"; - } - return new CompileResult { CommandText = sqlCall }; - - } else if (expr.NodeType == ExpressionType.Constant) { - var c = (ConstantExpression)expr; - queryArgs.Add (c.Value); - return new CompileResult { - CommandText = "?", - Value = c.Value - }; - } else if (expr.NodeType == ExpressionType.Convert) { - var u = (UnaryExpression)expr; - var ty = u.Type; - var valr = CompileExpr (u.Operand, queryArgs); - return new CompileResult { - CommandText = valr.CommandText, - Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null - }; - } else if (expr.NodeType == ExpressionType.MemberAccess) { - var mem = (MemberExpression)expr; - - if (mem.Expression!=null && mem.Expression.NodeType == ExpressionType.Parameter) { - // - // This is a column of our table, output just the column name - // Need to translate it if that column name is mapped - // - var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name; - return new CompileResult { CommandText = "\"" + columnName + "\"" }; - } else { - object obj = null; - if (mem.Expression != null) { - var r = CompileExpr (mem.Expression, queryArgs); - if (r.Value == null) { - throw new NotSupportedException ("Member access failed to compile expression"); - } - if (r.CommandText == "?") { - queryArgs.RemoveAt (queryArgs.Count - 1); - } - obj = r.Value; - } - - // - // Get the member value - // - object val = null; - -#if !NETFX_CORE - if (mem.Member.MemberType == MemberTypes.Property) { -#else - if (mem.Member is PropertyInfo) { -#endif - var m = (PropertyInfo)mem.Member; - val = m.GetValue (obj, null); -#if !NETFX_CORE - } else if (mem.Member.MemberType == MemberTypes.Field) { -#else - } else if (mem.Member is FieldInfo) { -#endif -#if SILVERLIGHT - val = Expression.Lambda (expr).Compile ().DynamicInvoke (); -#else - var m = (FieldInfo)mem.Member; - val = m.GetValue (obj); -#endif - } else { -#if !NETFX_CORE - throw new NotSupportedException ("MemberExpr: " + mem.Member.MemberType); -#else - throw new NotSupportedException ("MemberExpr: " + mem.Member.DeclaringType); -#endif - } - - // - // Work special magic for enumerables - // - if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable)) { - var sb = new System.Text.StringBuilder(); - sb.Append("("); - var head = ""; - foreach (var a in (System.Collections.IEnumerable)val) { - queryArgs.Add(a); - sb.Append(head); - sb.Append("?"); - head = ","; - } - sb.Append(")"); - return new CompileResult { - CommandText = sb.ToString(), - Value = val - }; - } - else { - queryArgs.Add (val); - return new CompileResult { - CommandText = "?", - Value = val - }; - } - } - } - throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ()); - } - - static object ConvertTo (object obj, Type t) - { - Type nut = Nullable.GetUnderlyingType(t); - - if (nut != null) { - if (obj == null) return null; - return Convert.ChangeType (obj, nut); - } else { - return Convert.ChangeType (obj, t); - } - } - - /// - /// Compiles a BinaryExpression where one of the parameters is null. - /// - /// The non-null parameter - private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) - { - if (expression.NodeType == ExpressionType.Equal) - return "(" + parameter.CommandText + " is ?)"; - else if (expression.NodeType == ExpressionType.NotEqual) - return "(" + parameter.CommandText + " is not ?)"; - else - throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString()); - } - - string GetSqlName (Expression expr) - { - var n = expr.NodeType; - if (n == ExpressionType.GreaterThan) - return ">"; else if (n == ExpressionType.GreaterThanOrEqual) { - return ">="; - } else if (n == ExpressionType.LessThan) { - return "<"; - } else if (n == ExpressionType.LessThanOrEqual) { - return "<="; - } else if (n == ExpressionType.And) { - return "&"; - } else if (n == ExpressionType.AndAlso) { - return "and"; - } else if (n == ExpressionType.Or) { - return "|"; - } else if (n == ExpressionType.OrElse) { - return "or"; - } else if (n == ExpressionType.Equal) { - return "="; - } else if (n == ExpressionType.NotEqual) { - return "!="; - } else { - throw new NotSupportedException ("Cannot get SQL for: " + n); - } - } - - public int Count () - { - return GenerateCommand("count(*)").ExecuteScalar (); - } - - public int Count (Expression> predExpr) - { - return Where (predExpr).Count (); - } - - public IEnumerator GetEnumerator () - { - if (!_deferred) - return GenerateCommand("*").ExecuteQuery().GetEnumerator(); - - return GenerateCommand("*").ExecuteDeferredQuery().GetEnumerator(); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () - { - return GetEnumerator (); - } - - public T First () - { - var query = Take (1); - return query.ToList().First (); - } - - public T FirstOrDefault () - { - var query = Take (1); - return query.ToList().FirstOrDefault (); - } - } - - public static class SQLite3 - { - public enum Result : int - { - OK = 0, - Error = 1, - Internal = 2, - Perm = 3, - Abort = 4, - Busy = 5, - Locked = 6, - NoMem = 7, - ReadOnly = 8, - Interrupt = 9, - IOError = 10, - Corrupt = 11, - NotFound = 12, - Full = 13, - CannotOpen = 14, - LockErr = 15, - Empty = 16, - SchemaChngd = 17, - TooBig = 18, - Constraint = 19, - Mismatch = 20, - Misuse = 21, - NotImplementedLFS = 22, - AccessDenied = 23, - Format = 24, - Range = 25, - NonDBFile = 26, - Notice = 27, - Warning = 28, - Row = 100, - Done = 101 - } - - public enum ExtendedResult : int - { - IOErrorRead = (Result.IOError | (1 << 8)), - IOErrorShortRead = (Result.IOError | (2 << 8)), - IOErrorWrite = (Result.IOError | (3 << 8)), - IOErrorFsync = (Result.IOError | (4 << 8)), - IOErrorDirFSync = (Result.IOError | (5 << 8)), - IOErrorTruncate = (Result.IOError | (6 << 8)), - IOErrorFStat = (Result.IOError | (7 << 8)), - IOErrorUnlock = (Result.IOError | (8 << 8)), - IOErrorRdlock = (Result.IOError | (9 << 8)), - IOErrorDelete = (Result.IOError | (10 << 8)), - IOErrorBlocked = (Result.IOError | (11 << 8)), - IOErrorNoMem = (Result.IOError | (12 << 8)), - IOErrorAccess = (Result.IOError | (13 << 8)), - IOErrorCheckReservedLock = (Result.IOError | (14 << 8)), - IOErrorLock = (Result.IOError | (15 << 8)), - IOErrorClose = (Result.IOError | (16 << 8)), - IOErrorDirClose = (Result.IOError | (17 << 8)), - IOErrorSHMOpen = (Result.IOError | (18 << 8)), - IOErrorSHMSize = (Result.IOError | (19 << 8)), - IOErrorSHMLock = (Result.IOError | (20 << 8)), - IOErrorSHMMap = (Result.IOError | (21 << 8)), - IOErrorSeek = (Result.IOError | (22 << 8)), - IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)), - IOErrorMMap = (Result.IOError | (24 << 8)), - LockedSharedcache = (Result.Locked | (1 << 8)), - BusyRecovery = (Result.Busy | (1 << 8)), - CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)), - CannotOpenIsDir = (Result.CannotOpen | (2 << 8)), - CannotOpenFullPath = (Result.CannotOpen | (3 << 8)), - CorruptVTab = (Result.Corrupt | (1 << 8)), - ReadonlyRecovery = (Result.ReadOnly | (1 << 8)), - ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)), - ReadonlyRollback = (Result.ReadOnly | (3 << 8)), - AbortRollback = (Result.Abort | (2 << 8)), - ConstraintCheck = (Result.Constraint | (1 << 8)), - ConstraintCommitHook = (Result.Constraint | (2 << 8)), - ConstraintForeignKey = (Result.Constraint | (3 << 8)), - ConstraintFunction = (Result.Constraint | (4 << 8)), - ConstraintNotNull = (Result.Constraint | (5 << 8)), - ConstraintPrimaryKey = (Result.Constraint | (6 << 8)), - ConstraintTrigger = (Result.Constraint | (7 << 8)), - ConstraintUnique = (Result.Constraint | (8 << 8)), - ConstraintVTab = (Result.Constraint | (9 << 8)), - NoticeRecoverWAL = (Result.Notice | (1 << 8)), - NoticeRecoverRollback = (Result.Notice | (2 << 8)) - } - - - public enum ConfigOption : int - { - SingleThread = 1, - MultiThread = 2, - Serialized = 3 - } - -#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE - [DllImport("sqlite3", EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, IntPtr zvfs); - - [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs); - - [DllImport("sqlite3", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)] - public static extern Result EnableLoadExtension (IntPtr db, int onoff); - - [DllImport("sqlite3", EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Close (IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Initialize(); - - [DllImport("sqlite3", EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Shutdown(); - - [DllImport("sqlite3", EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Config (ConfigOption option); - - [DllImport("sqlite3", EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)] - public static extern int SetDirectory (uint directoryType, string directoryPath); - - [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)] - public static extern Result BusyTimeout (IntPtr db, int milliseconds); - - [DllImport("sqlite3", EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)] - public static extern int Changes (IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); - -#if NETFX_CORE - [DllImport ("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)] - public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail); -#endif - - public static IntPtr Prepare2 (IntPtr db, string query) - { - IntPtr stmt; -#if NETFX_CORE - byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query); - var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero); -#else - var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero); -#endif - if (r != Result.OK) { - throw SQLiteException.New (r, GetErrmsg (db)); - } - return stmt; - } - - [DllImport("sqlite3", EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Step (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Reset (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)] - public static extern Result Finalize (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)] - public static extern long LastInsertRowid (IntPtr db); - - [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr Errmsg (IntPtr db); - - public static string GetErrmsg (IntPtr db) - { - return Marshal.PtrToStringUni (Errmsg (db)); - } - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindNull (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindInt (IntPtr stmt, int index, int val); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindInt64 (IntPtr stmt, int index, long val); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindDouble (IntPtr stmt, int index, double val); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)] - public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free); - - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)] - public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)] - public static extern int ColumnCount (IntPtr stmt); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnName (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)] - static extern IntPtr ColumnName16Internal (IntPtr stmt, int index); - public static string ColumnName16(IntPtr stmt, int index) - { - return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index)); - } - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)] - public static extern ColType ColumnType (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)] - public static extern int ColumnInt (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)] - public static extern long ColumnInt64 (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)] - public static extern double ColumnDouble (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnText (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnText16 (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)] - public static extern IntPtr ColumnBlob (IntPtr stmt, int index); - - [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)] - public static extern int ColumnBytes (IntPtr stmt, int index); - - public static string ColumnString (IntPtr stmt, int index) - { - return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index)); - } - - public static byte[] ColumnByteArray (IntPtr stmt, int index) - { - int length = ColumnBytes (stmt, index); - var result = new byte[length]; - if (length > 0) - Marshal.Copy (ColumnBlob (stmt, index), result, 0, length); - return result; - } - - [DllImport ("sqlite3", EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)] - public static extern ExtendedResult ExtendedErrCode (IntPtr db); - - [DllImport ("sqlite3", EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)] - public static extern int LibVersionNumber (); -#else - public static Result Open(string filename, out Sqlite3DatabaseHandle db) - { - return (Result) Sqlite3.sqlite3_open(filename, out db); - } - - public static Result Open(string filename, out Sqlite3DatabaseHandle db, int flags, IntPtr zVfs) - { -#if USE_WP8_NATIVE_SQLITE - return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, ""); -#else - return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, null); -#endif - } - - public static Result Close(Sqlite3DatabaseHandle db) - { - return (Result)Sqlite3.sqlite3_close(db); - } - - public static Result BusyTimeout(Sqlite3DatabaseHandle db, int milliseconds) - { - return (Result)Sqlite3.sqlite3_busy_timeout(db, milliseconds); - } - - public static int Changes(Sqlite3DatabaseHandle db) - { - return Sqlite3.sqlite3_changes(db); - } - - public static Sqlite3Statement Prepare2(Sqlite3DatabaseHandle db, string query) - { - Sqlite3Statement stmt = default(Sqlite3Statement); -#if USE_WP8_NATIVE_SQLITE - var r = Sqlite3.sqlite3_prepare_v2(db, query, out stmt); -#else - stmt = new Sqlite3Statement(); - var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0); -#endif - if (r != 0) - { - throw SQLiteException.New((Result)r, GetErrmsg(db)); - } - return stmt; - } - - public static Result Step(Sqlite3Statement stmt) - { - return (Result)Sqlite3.sqlite3_step(stmt); - } - - public static Result Reset(Sqlite3Statement stmt) - { - return (Result)Sqlite3.sqlite3_reset(stmt); - } - - public static Result Finalize(Sqlite3Statement stmt) - { - return (Result)Sqlite3.sqlite3_finalize(stmt); - } - - public static long LastInsertRowid(Sqlite3DatabaseHandle db) - { - return Sqlite3.sqlite3_last_insert_rowid(db); - } - - public static string GetErrmsg(Sqlite3DatabaseHandle db) - { - return Sqlite3.sqlite3_errmsg(db); - } - - public static int BindParameterIndex(Sqlite3Statement stmt, string name) - { - return Sqlite3.sqlite3_bind_parameter_index(stmt, name); - } - - public static int BindNull(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_bind_null(stmt, index); - } - - public static int BindInt(Sqlite3Statement stmt, int index, int val) - { - return Sqlite3.sqlite3_bind_int(stmt, index, val); - } - - public static int BindInt64(Sqlite3Statement stmt, int index, long val) - { - return Sqlite3.sqlite3_bind_int64(stmt, index, val); - } - - public static int BindDouble(Sqlite3Statement stmt, int index, double val) - { - return Sqlite3.sqlite3_bind_double(stmt, index, val); - } - - public static int BindText(Sqlite3Statement stmt, int index, string val, int n, IntPtr free) - { -#if USE_WP8_NATIVE_SQLITE - return Sqlite3.sqlite3_bind_text(stmt, index, val, n); -#else - return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null); -#endif - } - - public static int BindBlob(Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free) - { -#if USE_WP8_NATIVE_SQLITE - return Sqlite3.sqlite3_bind_blob(stmt, index, val, n); -#else - return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null); -#endif - } - - public static int ColumnCount(Sqlite3Statement stmt) - { - return Sqlite3.sqlite3_column_count(stmt); - } - - public static string ColumnName(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_name(stmt, index); - } - - public static string ColumnName16(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_name(stmt, index); - } - - public static ColType ColumnType(Sqlite3Statement stmt, int index) - { - return (ColType)Sqlite3.sqlite3_column_type(stmt, index); - } - - public static int ColumnInt(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_int(stmt, index); - } - - public static long ColumnInt64(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_int64(stmt, index); - } - - public static double ColumnDouble(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_double(stmt, index); - } - - public static string ColumnText(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_text(stmt, index); - } - - public static string ColumnText16(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_text(stmt, index); - } - - public static byte[] ColumnBlob(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_blob(stmt, index); - } - - public static int ColumnBytes(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_bytes(stmt, index); - } - - public static string ColumnString(Sqlite3Statement stmt, int index) - { - return Sqlite3.sqlite3_column_text(stmt, index); - } - - public static byte[] ColumnByteArray(Sqlite3Statement stmt, int index) - { - return ColumnBlob(stmt, index); - } - - public static Result EnableLoadExtension(Sqlite3DatabaseHandle db, int onoff) - { - return (Result)Sqlite3.sqlite3_enable_load_extension(db, onoff); - } - - public static ExtendedResult ExtendedErrCode(Sqlite3DatabaseHandle db) - { - return (ExtendedResult)Sqlite3.sqlite3_extended_errcode(db); - } -#endif - - public enum ColType : int - { - Integer = 1, - Float = 2, - Text = 3, - Blob = 4, - Null = 5 - } - } -} diff --git a/SQLite4Unity3d/packages/sqlite-net.1.0.8/content/SQLiteAsync.cs b/SQLite4Unity3d/packages/sqlite-net.1.0.8/content/SQLiteAsync.cs deleted file mode 100644 index 79b91cb..0000000 --- a/SQLite4Unity3d/packages/sqlite-net.1.0.8/content/SQLiteAsync.cs +++ /dev/null @@ -1,503 +0,0 @@ -// -// Copyright (c) 2012 Krueger Systems, 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. -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using System.Threading.Tasks; - -namespace SQLite -{ - public partial class SQLiteAsyncConnection - { - SQLiteConnectionString _connectionString; - SQLiteOpenFlags _openFlags; - - public SQLiteAsyncConnection(string databasePath, bool storeDateTimeAsTicks = false) - : this(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) - { - } - - public SQLiteAsyncConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false) - { - _openFlags = openFlags; - _connectionString = new SQLiteConnectionString(databasePath, storeDateTimeAsTicks); - } - - SQLiteConnectionWithLock GetConnection () - { - return SQLiteConnectionPool.Shared.GetConnection (_connectionString, _openFlags); - } - - public Task CreateTableAsync () - where T : new () - { - return CreateTablesAsync (typeof (T)); - } - - public Task CreateTablesAsync () - where T : new () - where T2 : new () - { - return CreateTablesAsync (typeof (T), typeof (T2)); - } - - public Task CreateTablesAsync () - where T : new () - where T2 : new () - where T3 : new () - { - return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3)); - } - - public Task CreateTablesAsync () - where T : new () - where T2 : new () - where T3 : new () - where T4 : new () - { - return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4)); - } - - public Task CreateTablesAsync () - where T : new () - where T2 : new () - where T3 : new () - where T4 : new () - where T5 : new () - { - return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); - } - - public Task CreateTablesAsync (params Type[] types) - { - return Task.Factory.StartNew (() => { - CreateTablesResult result = new CreateTablesResult (); - var conn = GetConnection (); - using (conn.Lock ()) { - foreach (Type type in types) { - int aResult = conn.CreateTable (type); - result.Results[type] = aResult; - } - } - return result; - }); - } - - public Task DropTableAsync () - where T : new () - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.DropTable (); - } - }); - } - - public Task InsertAsync (object item) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Insert (item); - } - }); - } - - public Task UpdateAsync (object item) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Update (item); - } - }); - } - - public Task DeleteAsync (object item) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Delete (item); - } - }); - } - - public Task GetAsync(object pk) - where T : new() - { - return Task.Factory.StartNew(() => - { - var conn = GetConnection(); - using (conn.Lock()) - { - return conn.Get(pk); - } - }); - } - - public Task FindAsync (object pk) - where T : new () - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Find (pk); - } - }); - } - - public Task GetAsync (Expression> predicate) - where T : new() - { - return Task.Factory.StartNew(() => - { - var conn = GetConnection(); - using (conn.Lock()) - { - return conn.Get (predicate); - } - }); - } - - public Task FindAsync (Expression> predicate) - where T : new () - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Find (predicate); - } - }); - } - - public Task ExecuteAsync (string query, params object[] args) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Execute (query, args); - } - }); - } - - public Task InsertAllAsync (IEnumerable items) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.InsertAll (items); - } - }); - } - - public Task UpdateAllAsync (IEnumerable items) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.UpdateAll (items); - } - }); - } - - [Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action) instead.")] - public Task RunInTransactionAsync (Action action) - { - return Task.Factory.StartNew (() => { - var conn = this.GetConnection (); - using (conn.Lock ()) { - conn.BeginTransaction (); - try { - action (this); - conn.Commit (); - } - catch (Exception) { - conn.Rollback (); - throw; - } - } - }); - } - - public Task RunInTransactionAsync(Action action) - { - return Task.Factory.StartNew(() => - { - var conn = this.GetConnection(); - using (conn.Lock()) - { - conn.BeginTransaction(); - try - { - action(conn); - conn.Commit(); - } - catch (Exception) - { - conn.Rollback(); - throw; - } - } - }); - } - - public AsyncTableQuery Table () - where T : new () - { - // - // This isn't async as the underlying connection doesn't go out to the database - // until the query is performed. The Async methods are on the query iteself. - // - var conn = GetConnection (); - return new AsyncTableQuery (conn.Table ()); - } - - public Task ExecuteScalarAsync (string sql, params object[] args) - { - return Task.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - var command = conn.CreateCommand (sql, args); - return command.ExecuteScalar (); - } - }); - } - - public Task> QueryAsync (string sql, params object[] args) - where T : new () - { - return Task>.Factory.StartNew (() => { - var conn = GetConnection (); - using (conn.Lock ()) { - return conn.Query (sql, args); - } - }); - } - } - - // - // TODO: Bind to AsyncConnection.GetConnection instead so that delayed - // execution can still work after a Pool.Reset. - // - public class AsyncTableQuery - where T : new () - { - TableQuery _innerQuery; - - public AsyncTableQuery (TableQuery innerQuery) - { - _innerQuery = innerQuery; - } - - public AsyncTableQuery Where (Expression> predExpr) - { - return new AsyncTableQuery (_innerQuery.Where (predExpr)); - } - - public AsyncTableQuery Skip (int n) - { - return new AsyncTableQuery (_innerQuery.Skip (n)); - } - - public AsyncTableQuery Take (int n) - { - return new AsyncTableQuery (_innerQuery.Take (n)); - } - - public AsyncTableQuery OrderBy (Expression> orderExpr) - { - return new AsyncTableQuery (_innerQuery.OrderBy (orderExpr)); - } - - public AsyncTableQuery OrderByDescending (Expression> orderExpr) - { - return new AsyncTableQuery (_innerQuery.OrderByDescending (orderExpr)); - } - - public Task> ToListAsync () - { - return Task.Factory.StartNew (() => { - using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { - return _innerQuery.ToList (); - } - }); - } - - public Task CountAsync () - { - return Task.Factory.StartNew (() => { - using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { - return _innerQuery.Count (); - } - }); - } - - public Task ElementAtAsync (int index) - { - return Task.Factory.StartNew (() => { - using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { - return _innerQuery.ElementAt (index); - } - }); - } - - public Task FirstAsync () - { - return Task.Factory.StartNew(() => { - using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { - return _innerQuery.First (); - } - }); - } - - public Task FirstOrDefaultAsync () - { - return Task.Factory.StartNew(() => { - using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { - return _innerQuery.FirstOrDefault (); - } - }); - } - } - - public class CreateTablesResult - { - public Dictionary Results { get; private set; } - - internal CreateTablesResult () - { - this.Results = new Dictionary (); - } - } - - class SQLiteConnectionPool - { - class Entry - { - public SQLiteConnectionString ConnectionString { get; private set; } - public SQLiteConnectionWithLock Connection { get; private set; } - - public Entry (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) - { - ConnectionString = connectionString; - Connection = new SQLiteConnectionWithLock (connectionString, openFlags); - } - - public void OnApplicationSuspended () - { - Connection.Dispose (); - Connection = null; - } - } - - readonly Dictionary _entries = new Dictionary (); - readonly object _entriesLock = new object (); - - static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool (); - - /// - /// Gets the singleton instance of the connection tool. - /// - public static SQLiteConnectionPool Shared - { - get - { - return _shared; - } - } - - public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) - { - lock (_entriesLock) { - Entry entry; - string key = connectionString.ConnectionString; - - if (!_entries.TryGetValue (key, out entry)) { - entry = new Entry (connectionString, openFlags); - _entries[key] = entry; - } - - return entry.Connection; - } - } - - /// - /// Closes all connections managed by this pool. - /// - public void Reset () - { - lock (_entriesLock) { - foreach (var entry in _entries.Values) { - entry.OnApplicationSuspended (); - } - _entries.Clear (); - } - } - - /// - /// Call this method when the application is suspended. - /// - /// Behaviour here is to close any open connections. - public void ApplicationSuspended () - { - Reset (); - } - } - - class SQLiteConnectionWithLock : SQLiteConnection - { - readonly object _lockPoint = new object (); - - public SQLiteConnectionWithLock (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags) - : base (connectionString.DatabasePath, openFlags, connectionString.StoreDateTimeAsTicks) - { - } - - public IDisposable Lock () - { - return new LockWrapper (_lockPoint); - } - - private class LockWrapper : IDisposable - { - object _lockPoint; - - public LockWrapper (object lockPoint) - { - _lockPoint = lockPoint; - Monitor.Enter (_lockPoint); - } - - public void Dispose () - { - Monitor.Exit (_lockPoint); - } - } - } -} - diff --git a/SQLite4Unity3d/packages/sqlite-net.1.0.8/sqlite-net.1.0.8.nupkg b/SQLite4Unity3d/packages/sqlite-net.1.0.8/sqlite-net.1.0.8.nupkg deleted file mode 100644 index 37f5f06..0000000 Binary files a/SQLite4Unity3d/packages/sqlite-net.1.0.8/sqlite-net.1.0.8.nupkg and /dev/null differ