├── .editorconfig
├── .github
├── FUNDING.yml
└── workflows
│ └── build.yml
├── .gitignore
├── Directory.Build.props
├── LICENSE.txt
├── Logo-low.png
├── Logo.png
├── Makefile
├── README.md
├── SQLite.sln
├── global.json
├── nuget
├── Logo-low.png
├── SQLite-net-base
│ └── SQLite-net-base.csproj
├── SQLite-net-sqlcipher
│ └── SQLite-net-sqlcipher.csproj
├── SQLite-net-static
│ └── SQLite-net-static.csproj
└── SQLite-net-std
│ └── SQLite-net-std.csproj
├── src
├── AssemblyInfo.cs
├── SQLite.cs
└── SQLiteAsync.cs
└── tests
├── ApiDiff
├── ApiDiff.csproj
└── Program.cs
├── SQLite.Tests.iOS
├── Entitlements.plist
├── Info.plist
├── LaunchScreen.storyboard
├── Main.cs
├── SQLiteTestsiOS.csproj
└── UnitTestAppDelegate.cs
└── SQLite.Tests
├── AsyncTests.cs
├── AttributesTest.cs
├── BackupTest.cs
├── BooleanTest.cs
├── ByteArrayTest.cs
├── CollateTest.cs
├── ConcurrencyTest.cs
├── ContainsTest.cs
├── CreateTableImplicitTest.cs
├── CreateTableTest.cs
├── DateTimeOffsetTest.cs
├── DateTimeTest.cs
├── DbCommandTest.cs
├── DeleteTest.cs
├── DropTableTest.cs
├── EnumCacheTest.cs
├── EnumNullableTest.cs
├── EnumTest.cs
├── EqualsTest.cs
├── ExceptionAssert.cs
├── GuidTests.cs
├── IgnoreTest.cs
├── InheritanceTest.cs
├── InsertTest.cs
├── JoinTest.cs
├── LinqTest.cs
├── MappingTest.cs
├── MigrationTest.cs
├── NotNullAttributeTest.cs
├── NullableTest.cs
├── OpenTests.cs
├── QueryTest.cs
├── ReadmeTest.cs
├── SQLCipherTest.cs
├── SQLite.Tests.csproj
├── ScalarTest.cs
├── SkipTest.cs
├── StringQueryTest.cs
├── TableChangedTest.cs
├── TestDb.cs
├── TimeSpanTest.cs
├── TransactionTest.cs
├── UnicodeTest.cs
└── UniqueTest.cs
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | # Default settings:
7 | # A newline ending every file
8 | # Use 4 spaces as indentation
9 | [*]
10 | insert_final_newline = true
11 | indent_style = space
12 | indent_size = 4
13 | end_of_line = lf
14 |
15 | # C# files
16 | [*.cs]
17 | end_of_line = lf
18 | indent_style = tab
19 | tab_width = 4
20 |
21 | # New line preferences
22 | csharp_new_line_before_open_brace = methods, types
23 | csharp_new_line_before_else = true
24 | csharp_new_line_before_catch = true
25 | csharp_new_line_before_finally = true
26 | csharp_new_line_before_members_in_object_initializers = true
27 | csharp_new_line_before_members_in_anonymous_types = true
28 | csharp_new_line_within_query_expression_clauses = true
29 |
30 | # Indentation preferences
31 | csharp_indent_block_contents = true
32 | csharp_indent_braces = false
33 | csharp_indent_case_contents = true
34 | csharp_indent_switch_labels = true
35 | csharp_indent_labels = flush_left
36 |
37 | # avoid this. unless absolutely necessary
38 | dotnet_style_qualification_for_field = false:suggestion
39 | dotnet_style_qualification_for_property = false:suggestion
40 | dotnet_style_qualification_for_method = false:suggestion
41 | dotnet_style_qualification_for_event = false:suggestion
42 |
43 | # only use var when it's obvious what the variable type is
44 | csharp_style_var_for_built_in_types = true:none
45 | csharp_style_var_when_type_is_apparent = true:none
46 | csharp_style_var_elsewhere = true:suggestion
47 |
48 | # use language keywords instead of BCL types
49 | dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
50 | dotnet_style_predefined_type_for_member_access = true:suggestion
51 |
52 | # name all constant fields using PascalCase
53 | dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
54 | dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
55 | dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
56 |
57 | dotnet_naming_symbols.constant_fields.applicable_kinds = field
58 | dotnet_naming_symbols.constant_fields.required_modifiers = const
59 |
60 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case
61 |
62 | # static fields should have s_ prefix
63 | dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion
64 | dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields
65 | dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style
66 |
67 | dotnet_naming_symbols.static_fields.applicable_kinds = field
68 | dotnet_naming_symbols.static_fields.required_modifiers = static
69 |
70 | dotnet_naming_style.static_prefix_style.required_prefix =
71 | dotnet_naming_style.static_prefix_style.capitalization = camel_case
72 |
73 | # internal and private fields should be _camelCase
74 | dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion
75 | dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields
76 | dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style
77 |
78 | dotnet_naming_symbols.private_internal_fields.applicable_kinds = field
79 | dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
80 |
81 | dotnet_naming_style.camel_case_underscore_style.required_prefix =
82 | dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
83 |
84 | # Code style defaults
85 | dotnet_sort_system_directives_first = true
86 | csharp_preserve_single_line_blocks = true
87 | csharp_preserve_single_line_statements = false
88 |
89 | # Expression-level preferences
90 | dotnet_style_object_initializer = true:suggestion
91 | dotnet_style_collection_initializer = true:suggestion
92 | dotnet_style_explicit_tuple_names = true:suggestion
93 | dotnet_style_coalesce_expression = true:suggestion
94 | dotnet_style_null_propagation = true:suggestion
95 |
96 | # Expression-bodied members
97 | csharp_style_expression_bodied_methods = false:none
98 | csharp_style_expression_bodied_constructors = false:none
99 | csharp_style_expression_bodied_operators = false:none
100 | csharp_style_expression_bodied_properties = true:none
101 | csharp_style_expression_bodied_indexers = true:none
102 | csharp_style_expression_bodied_accessors = true:none
103 |
104 | # Pattern matching
105 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
106 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
107 | csharp_style_inlined_variable_declaration = true:suggestion
108 |
109 | # Null checking preferences
110 | csharp_style_throw_expression = true:suggestion
111 | csharp_style_conditional_delegate_call = true:suggestion
112 |
113 | # Space preferences
114 | csharp_space_after_cast = false
115 | csharp_space_after_colon_in_inheritance_clause = true
116 | csharp_space_after_comma = true
117 | csharp_space_after_dot = false
118 | csharp_space_after_keywords_in_control_flow_statements = true
119 | csharp_space_after_semicolon_in_for_statement = true
120 | csharp_space_around_binary_operators = before_and_after
121 | csharp_space_around_declaration_statements = do_not_ignore
122 | csharp_space_before_colon_in_inheritance_clause = true
123 | csharp_space_before_comma = false
124 | csharp_space_before_dot = false
125 | csharp_space_before_open_square_brackets = false
126 | csharp_space_before_semicolon_in_for_statement = false
127 | csharp_space_between_empty_square_brackets = false
128 | csharp_space_between_method_call_empty_parameter_list_parentheses = false
129 | csharp_space_between_method_call_name_and_opening_parenthesis = true
130 | csharp_space_between_method_call_parameter_list_parentheses = false
131 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
132 | csharp_space_between_method_declaration_name_and_open_parenthesis = true
133 | csharp_space_between_method_declaration_parameter_list_parentheses = false
134 | csharp_space_between_parentheses = false
135 | csharp_space_between_square_brackets = false
136 |
137 | # C++ Files
138 | [*.{cpp,h,in}]
139 | curly_bracket_next_line = true
140 | indent_brace_style = Allman
141 |
142 | # Xml project files
143 | [*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}]
144 | indent_size = 2
145 | end_of_line = crlf
146 | indent_style = space
147 |
148 | # Xml build files
149 | [*.builds]
150 | indent_size = 2
151 |
152 | # Xml files
153 | [*.{xml,stylecop,resx,ruleset}]
154 | indent_size = 2
155 |
156 | # Xml config files
157 | [*.{props,targets,config,nuspec}]
158 | indent_size = 2
159 |
160 | # Shell scripts
161 | [*.sh]
162 | end_of_line = lf
163 | [*.{cmd, bat}]
164 | end_of_line = crlf
165 |
166 | [Makefile]
167 | indent_style = tab
168 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: praeclarum
2 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | branches:
9 | - master
10 |
11 | jobs:
12 | build:
13 |
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 |
18 | - uses: actions/checkout@v1
19 |
20 | - name: Update Versions
21 | env:
22 | VERSION_BUILD: ${{github.run_number}}
23 | run: |
24 | sed -i.bak "s::.$VERSION_BUILD:g" Directory.Build.props
25 |
26 | - name: Set up .NET
27 | uses: actions/setup-dotnet@v4
28 | with:
29 | global-json-file: global.json
30 |
31 | - name: Install Code Coverarage Tool
32 | run: dotnet tool install --global dotnet-reportgenerator-globaltool
33 |
34 | - name: Restore NuGets
35 | run: dotnet restore SQLite.sln
36 |
37 | - name: Build and Test
38 | run: |
39 | set -e
40 | cd tests/SQLite.Tests
41 | dotnet test /p:AltCover=true /p:AltCoverForce=true "/p:AltCoverTypeFilter=SQLite.Tests.*"
42 |
43 | - name: Verify Async API Matches Sync API
44 | run: |
45 | set -e
46 | dotnet run --project tests/ApiDiff/ApiDiff.csproj
47 |
48 | - name: Generate Code Coverage Report
49 | uses: danielpalme/ReportGenerator-GitHub-Action@5.2.4
50 | if: github.event_name == 'push'
51 | with:
52 | reports: 'tests/SQLite.Tests/coverage.xml' # REQUIRED # The coverage reports that should be parsed (separated by semicolon). Globbing is supported.
53 | targetdir: 'CoverageReport' # REQUIRED # The directory where the generated report should be saved.
54 | reporttypes: 'HtmlInline;Cobertura' # The output formats and scope (separated by semicolon) Values: Badges, Clover, Cobertura, CsvSummary, Html, HtmlChart, HtmlInline, HtmlInline_AzurePipelines, HtmlInline_AzurePipelines_Dark, HtmlSummary, JsonSummary, Latex, LatexSummary, lcov, MHtml, PngChart, SonarQube, TeamCitySummary, TextSummary, Xml, XmlSummary
55 | sourcedirs: '' # Optional directories which contain the corresponding source code (separated by semicolon). The source directories are used if coverage report contains classes without path information.
56 | historydir: '' # Optional directory for storing persistent coverage information. Can be used in future reports to show coverage evolution.
57 | plugins: '' # Optional plugin files for custom reports or custom history storage (separated by semicolon).
58 | assemblyfilters: '+SQLite.Tests;-NUnit3.TestAdapter' # Optional list of assemblies that should be included or excluded in the report. Exclusion filters take precedence over inclusion filters. Wildcards are allowed.
59 | classfilters: '+*;-SQLite.Tests.*' # Optional list of classes that should be included or excluded in the report. Exclusion filters take precedence over inclusion filters. Wildcards are allowed.
60 | filefilters: '+*' # Optional list of files that should be included or excluded in the report. Exclusion filters take precedence over inclusion filters. Wildcards are allowed.
61 | verbosity: 'Info' # The verbosity level of the log messages. Values: Verbose, Info, Warning, Error, Off
62 | title: '' # Optional title.
63 | tag: '${{ github.run_number }}_${{ github.run_id }}' # Optional tag or build version.
64 | customSettings: '' # Optional custom settings (separated by semicolon). See: https://github.com/danielpalme/ReportGenerator/wiki/Settings.
65 |
66 | - name: Deploy Code Coverage Report
67 | uses: peaceiris/actions-gh-pages@v3
68 | if: github.event_name == 'push'
69 | with:
70 | github_token: ${{ secrets.GITHUB_TOKEN }}
71 | publish_dir: CoverageReport
72 | destination_dir: coverage
73 | enable_jekyll: true
74 |
75 | - name: Package
76 | if: github.event_name == 'push'
77 | run: |
78 | make nuget
79 |
80 | - uses: actions/upload-artifact@master
81 | if: github.event_name == 'push'
82 | with:
83 | name: Packages
84 | path: PackagesOut
85 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | coverage.*
2 | CoverageReport
3 | .DS_Store
4 | .dropbox.attr
5 | test-results
6 |
7 | /PackagesOut
8 |
9 | ## Ignore Visual Studio temporary files, build results, and
10 | ## files generated by popular Visual Studio add-ons.
11 |
12 | # User-specific files
13 | *.suo
14 | *.user
15 | *.userosscache
16 | *.sln.docstates
17 |
18 | # User-specific files (MonoDevelop/Xamarin Studio)
19 | *.userprefs
20 |
21 | # Build results
22 | [Dd]ebug/
23 | [Dd]ebugPublic/
24 | [Rr]elease/
25 | [Rr]eleases/
26 | x64/
27 | x86/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 |
33 | # Visual Studio 2015 cache/options directory
34 | .vs/
35 | # Uncomment if you have tasks that create the project's static files in wwwroot
36 | #wwwroot/
37 | dist/
38 |
39 | # MSTest test Results
40 | [Tt]est[Rr]esult*/
41 | [Bb]uild[Ll]og.*
42 |
43 | # NUNIT
44 | *.VisualState.xml
45 | TestResult.xml
46 |
47 | # Build Results of an ATL Project
48 | [Dd]ebugPS/
49 | [Rr]eleasePS/
50 | dlldata.c
51 |
52 | # DNX
53 | project.lock.json
54 | project.fragment.lock.json
55 | artifacts/
56 |
57 | *_i.c
58 | *_p.c
59 | *_i.h
60 | *.ilk
61 | *.meta
62 | *.obj
63 | *.pch
64 | *.pdb
65 | *.pgc
66 | *.pgd
67 | *.rsp
68 | *.sbr
69 | *.tlb
70 | *.tli
71 | *.tlh
72 | *.tmp
73 | *.tmp_proj
74 | *.log
75 | *.vspscc
76 | *.vssscc
77 | .builds
78 | *.pidb
79 | *.svclog
80 | *.scc
81 |
82 | # Chutzpah Test files
83 | _Chutzpah*
84 |
85 | # Visual C++ cache files
86 | ipch/
87 | *.aps
88 | *.ncb
89 | *.opendb
90 | *.opensdf
91 | *.sdf
92 | *.cachefile
93 | *.VC.db
94 | *.VC.VC.opendb
95 |
96 | # Visual Studio profiler
97 | *.psess
98 | *.vsp
99 | *.vspx
100 | *.sap
101 |
102 | # TFS 2012 Local Workspace
103 | $tf/
104 |
105 | # Guidance Automation Toolkit
106 | *.gpState
107 |
108 | # ReSharper is a .NET coding add-in
109 | _ReSharper*/
110 | *.[Rr]e[Ss]harper
111 | *.DotSettings.user
112 |
113 | # JustCode is a .NET coding add-in
114 | .JustCode
115 |
116 | # TeamCity is a build add-in
117 | _TeamCity*
118 |
119 | # DotCover is a Code Coverage Tool
120 | *.dotCover
121 |
122 | # NCrunch
123 | _NCrunch_*
124 | .*crunch*.local.xml
125 | nCrunchTemp_*
126 |
127 | # MightyMoose
128 | *.mm.*
129 | AutoTest.Net/
130 |
131 | # Web workbench (sass)
132 | .sass-cache/
133 |
134 | # Installshield output folder
135 | [Ee]xpress/
136 |
137 | # DocProject is a documentation generator add-in
138 | DocProject/buildhelp/
139 | DocProject/Help/*.HxT
140 | DocProject/Help/*.HxC
141 | DocProject/Help/*.hhc
142 | DocProject/Help/*.hhk
143 | DocProject/Help/*.hhp
144 | DocProject/Help/Html2
145 | DocProject/Help/html
146 |
147 | # Click-Once directory
148 | publish/
149 |
150 | # Publish Web Output
151 | *.[Pp]ublish.xml
152 | *.azurePubxml
153 | # TODO: Comment the next line if you want to checkin your web deploy settings
154 | # but database connection strings (with potential passwords) will be unencrypted
155 | #*.pubxml
156 | *.publishproj
157 |
158 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
159 | # checkin your Azure Web App publish settings, but sensitive information contained
160 | # in these scripts will be unencrypted
161 | PublishScripts/
162 |
163 | # NuGet Packages
164 | *.nupkg
165 | # The packages folder can be ignored because of Package Restore
166 | **/packages/*
167 | # except build/, which is used as an MSBuild target.
168 | !**/packages/build/
169 | # Uncomment if necessary however generally it will be regenerated when needed
170 | #!**/packages/repositories.config
171 | # NuGet v3's project.json files produces more ignoreable files
172 | *.nuget.props
173 | *.nuget.targets
174 |
175 | # Microsoft Azure Build Output
176 | csx/
177 | *.build.csdef
178 |
179 | # Microsoft Azure Emulator
180 | ecf/
181 | rcf/
182 |
183 | # Windows Store app package directories and files
184 | AppPackages/
185 | BundleArtifacts/
186 | Package.StoreAssociation.xml
187 | _pkginfo.txt
188 |
189 | # Visual Studio cache files
190 | # files ending in .cache can be ignored
191 | *.[Cc]ache
192 | # but keep track of directories ending in .cache
193 | !*.[Cc]ache/
194 |
195 | # Others
196 | ClientBin/
197 | ~$*
198 | *~
199 | *.dbmdl
200 | *.dbproj.schemaview
201 | *.jfm
202 | *.pfx
203 | *.publishsettings
204 | node_modules/
205 | orleans.codegen.cs
206 |
207 | # Since there are multiple workflows, uncomment next line to ignore bower_components
208 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
209 |
210 |
211 | # RIA/Silverlight projects
212 | Generated_Code/
213 |
214 | # Backup & report files from converting an old project file
215 | # to a newer Visual Studio version. Backup files are not needed,
216 | # because we have git ;-)
217 | _UpgradeReport_Files/
218 | Backup*/
219 | UpgradeLog*.XML
220 | UpgradeLog*.htm
221 |
222 | # SQL Server files
223 | *.mdf
224 | *.ldf
225 |
226 | # Business Intelligence projects
227 | *.rdl.data
228 | *.bim.layout
229 | *.bim_*.settings
230 |
231 | # Microsoft Fakes
232 | FakesAssemblies/
233 |
234 | # GhostDoc plugin setting file
235 | *.GhostDoc.xml
236 |
237 | # Node.js Tools for Visual Studio
238 | .ntvs_analysis.dat
239 |
240 | # Visual Studio 6 build log
241 | *.plg
242 |
243 | # Visual Studio 6 workspace options file
244 | *.opt
245 |
246 | # Visual Studio LightSwitch build output
247 | **/*.HTMLClient/GeneratedArtifacts
248 | **/*.DesktopClient/GeneratedArtifacts
249 | **/*.DesktopClient/ModelManifest.xml
250 | **/*.Server/GeneratedArtifacts
251 | **/*.Server/ModelManifest.xml
252 | _Pvt_Extensions
253 |
254 | # Paket dependency manager
255 | .paket/paket.exe
256 | paket-files/
257 |
258 | # FAKE - F# Make
259 | .fake/
260 |
261 | # JetBrains Rider
262 | .idea/
263 | *.sln.iml
264 |
265 | # CodeRush
266 | .cr/
267 |
268 | # NCrunch
269 | *.ncrunchsolution
270 | *.ncrunchproject
271 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 1.10
4 | beta
5 |
6 | Logo-low.png
7 | https://github.com/praeclarum/sqlite-net
8 | https://github.com/praeclarum/sqlite-net.git
9 | sqlite-net;sqlite;database;orm
10 | LICENSE.txt
11 |
12 | Krueger Systems, Inc.
13 |
14 | true
15 |
16 | true
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) Krueger Systems, Inc.
2 |
3 | All rights reserved.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Logo-low.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/praeclarum/sqlite-net/bf1eb50278d0ace79c3754575b34823cf7fb0934/Logo-low.png
--------------------------------------------------------------------------------
/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/praeclarum/sqlite-net/bf1eb50278d0ace79c3754575b34823cf7fb0934/Logo.png
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 |
2 | SRC=src/SQLite.cs src/SQLiteAsync.cs
3 |
4 | PACKAGES_OUT=$(abspath PackagesOut)
5 |
6 | all: nuget
7 |
8 | nuget: pclnuget basenuget sqlciphernuget staticnuget
9 |
10 | pclnuget: nuget/SQLite-net-std/SQLite-net-std.csproj $(SRC)
11 | dotnet pack -c Release -o $(PACKAGES_OUT) $<
12 |
13 | basenuget: nuget/SQLite-net-base/SQLite-net-base.csproj $(SRC)
14 | dotnet pack -c Release -o $(PACKAGES_OUT) $<
15 |
16 | sqlciphernuget: nuget/SQLite-net-sqlcipher/SQLite-net-sqlcipher.csproj $(SRC)
17 | dotnet pack -c Release -o $(PACKAGES_OUT) $<
18 |
19 | staticnuget: nuget/SQLite-net-static/SQLite-net-static.csproj $(SRC)
20 | dotnet pack -c Release -o $(PACKAGES_OUT) $<
21 |
22 | codecoverage:
23 | cd tests/SQLite.Tests && dotnet test /p:AltCover=true /p:AltCoverForce=true "/p:AltCoverTypeFilter=SQLite.Tests.*" && reportgenerator -reports:coverage.xml -targetdir:./CoverageReport
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # SQLite-net
3 |
4 | [[GitHub Action](https://github.com/praeclarum/sqlite-net/actions)] [[Code Coverage Report](https://praeclarum.org/sqlite-net/coverage/)]
5 |
6 | Use one of these packages:
7 |
8 | | Version | Package | Description |
9 | | ------- | ------- | ----------- |
10 | | [](https://www.nuget.org/packages/sqlite-net-pcl) | [sqlite-net-pcl](https://www.nuget.org/packages/sqlite-net-pcl) | .NET Standard Library |
11 | | [](https://www.nuget.org/packages/sqlite-net-sqlcipher) | [sqlite-net-sqlcipher](https://www.nuget.org/packages/sqlite-net-sqlcipher) | With Encryption Support |
12 | | [](https://www.nuget.org/packages/sqlite-net-static) | [sqlite-net-static](https://www.nuget.org/packages/sqlite-net-static) | Special version that uses P/Invokes to platform-provided sqlite3 |
13 | | [](https://www.nuget.org/packages/sqlite-net-base) | [sqlite-net-base](https://www.nuget.org/packages/sqlite-net-base) | without a SQLitePCLRaw bundle so you can choose your own provider |
14 |
15 | SQLite-net is an open source, minimal library to allow .NET, .NET Core, and Mono applications to store data in
16 | [SQLite 3 databases](http://www.sqlite.org). It was first designed to work with [Xamarin.iOS](http://xamarin.com),
17 | but has since grown up to work on all the platforms (Xamarin.*, .NET, UWP, Azure, etc.).
18 |
19 | SQLite-net was designed as a quick and convenient database layer. Its design follows from these *goals*:
20 |
21 | * Very easy to integrate with existing projects and runs on all the .NET platforms.
22 |
23 | * Thin wrapper over SQLite that is fast and efficient. (This library should not be the performance bottleneck of your queries.)
24 |
25 | * Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.
26 |
27 | * Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)
28 |
29 | ## NuGet Installation
30 |
31 | Install [sqlite-net-pcl](https://www.nuget.org/packages/sqlite-net-pcl) from NuGet.
32 |
33 | **Important:** You will need to add the NuGet package to **both** your *.NET Standard library project* and your *platform-dependent app project*.
34 |
35 | ## Source Installation
36 |
37 | SQLite-net is all contained in 1 file (I know, so cool right?) and is easy to add to your project. Just add [SQLite.cs](https://github.com/praeclarum/sqlite-net/blob/master/src/SQLite.cs) to your project, and you're ready to start creating tables. An asynchronous implementation can be found in [SQLiteAsync.cs](https://github.com/praeclarum/sqlite-net/blob/master/src/SQLiteAsync.cs).
38 |
39 | ## Please Contribute!
40 |
41 | This is an open source project that welcomes contributions/suggestions/bug reports from those who use it. If you have any ideas on how to improve the library, please [post an issue here on GitHub](https://github.com/praeclarum/sqlite-net/issues). Please check out the [How to Contribute](https://github.com/praeclarum/sqlite-net/wiki/How-to-Contribute).
42 |
43 |
44 | # Example Time!
45 |
46 | Please consult the Wiki for, ahem, [complete documentation](https://github.com/praeclarum/sqlite-net/wiki).
47 |
48 | The library contains simple attributes that you can use to control the construction of tables. In a simple stock program, you might use:
49 |
50 | ```csharp
51 | public class Stock
52 | {
53 | [PrimaryKey, AutoIncrement]
54 | public int Id { get; set; }
55 | public string Symbol { get; set; }
56 | }
57 |
58 | public class Valuation
59 | {
60 | [PrimaryKey, AutoIncrement]
61 | public int Id { get; set; }
62 | [Indexed]
63 | public int StockId { get; set; }
64 | public DateTime Time { get; set; }
65 | public decimal Price { get; set; }
66 | [Ignore]
67 | public string IgnoreField { get; set; }
68 | }
69 | ```
70 |
71 | Once you've defined the objects in your model you have a choice of APIs. You can use the "synchronous API" where calls
72 | block one at a time, or you can use the "asynchronous API" where calls do not block. You may care to use the asynchronous
73 | API for mobile applications in order to increase responsiveness.
74 |
75 | Both APIs are explained in the two sections below.
76 |
77 | ## Synchronous API
78 |
79 | Once you have defined your entity, you can automatically generate tables in your database by calling `CreateTable`:
80 |
81 | ```csharp
82 | // Get an absolute path to the database file
83 | var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyData.db");
84 |
85 | var db = new SQLiteConnection(databasePath);
86 | db.CreateTable();
87 | db.CreateTable();
88 | ```
89 |
90 | You can insert rows in the database using `Insert`. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:
91 |
92 | ```csharp
93 | public static void AddStock(SQLiteConnection db, string symbol) {
94 | var stock = new Stock() {
95 | Symbol = symbol
96 | };
97 | db.Insert(stock);
98 | Console.WriteLine("{0} == {1}", stock.Symbol, stock.Id);
99 | }
100 | ```
101 |
102 | Similar methods exist for `Update` and `Delete`.
103 |
104 | The most straightforward way to query for data is using the `Table` method. This can take predicates for constraining via WHERE clauses and/or adding ORDER BY clauses:
105 |
106 | ```csharp
107 | var query = db.Table().Where(v => v.Symbol.StartsWith("A"));
108 |
109 | foreach (var stock in query)
110 | Console.WriteLine("Stock: " + stock.Symbol);
111 | ```
112 |
113 | You can also query the database at a low-level using the `Query` method:
114 |
115 | ```csharp
116 | public static IEnumerable QueryValuations (SQLiteConnection db, Stock stock) {
117 | return db.Query ("select * from Valuation where StockId = ?", stock.Id);
118 | }
119 | ```
120 |
121 | The generic parameter to the `Query` method specifies the type of object to create for each row. It can be one of your table classes, or any other class whose public properties match the column returned by the query. For instance, we could rewrite the above query as:
122 |
123 | ```csharp
124 | public class Val
125 | {
126 | public decimal Money { get; set; }
127 | public DateTime Date { get; set; }
128 | }
129 |
130 | public static IEnumerable QueryVals (SQLiteConnection db, Stock stock) {
131 | return db.Query ("select \"Price\" as \"Money\", \"Time\" as \"Date\" from Valuation where StockId = ?", stock.Id);
132 | }
133 | ```
134 |
135 | You can perform low-level updates of the database using the `Execute` method.
136 |
137 | ## Asynchronous API
138 |
139 | The asynchronous library uses the Task Parallel Library (TPL). As such, normal use of `Task` objects, and the `async` and `await` keywords
140 | will work for you.
141 |
142 | Once you have defined your entity, you can automatically generate tables by calling `CreateTableAsync`:
143 |
144 | ```csharp
145 | // Get an absolute path to the database file
146 | var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyData.db");
147 |
148 | var db = new SQLiteAsyncConnection(databasePath);
149 |
150 | await db.CreateTableAsync();
151 |
152 | Console.WriteLine("Table created!");
153 | ```
154 |
155 | You can insert rows in the database using `Insert`. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:
156 |
157 | ```csharp
158 | var stock = new Stock()
159 | {
160 | Symbol = "AAPL"
161 | };
162 |
163 | await db.InsertAsync(stock);
164 |
165 | Console.WriteLine("Auto stock id: {0}", stock.Id);
166 | ```
167 |
168 | Similar methods exist for `UpdateAsync` and `DeleteAsync`.
169 |
170 | Querying for data is most straightforwardly done using the `Table` method. This will return an `AsyncTableQuery` instance back, whereupon
171 | you can add predicates for constraining via WHERE clauses and/or adding ORDER BY. The database is not physically touched until one of the special
172 | retrieval methods - `ToListAsync`, `FirstAsync`, or `FirstOrDefaultAsync` - is called.
173 |
174 | ```csharp
175 | var query = db.Table().Where(s => s.Symbol.StartsWith("A"));
176 |
177 | var result = await query.ToListAsync();
178 |
179 | foreach (var s in result)
180 | Console.WriteLine("Stock: " + s.Symbol);
181 | ```
182 |
183 | There are a number of low-level methods available. You can also query the database directly via the `QueryAsync` method. Over and above the change
184 | operations provided by `InsertAsync` etc you can issue `ExecuteAsync` methods to change sets of data directly within the database.
185 |
186 | Another helpful method is `ExecuteScalarAsync`. This allows you to return a scalar value from the database easily:
187 |
188 | ```csharp
189 | var count = await db.ExecuteScalarAsync("select count(*) from Stock");
190 |
191 | Console.WriteLine(string.Format("Found '{0}' stock items.", count));
192 | ```
193 |
194 | ## Manual SQL
195 |
196 | **sqlite-net** is normally used as a light ORM (object-relational-mapper) using the methods `CreateTable` and `Table`.
197 | However, you can also use it as a convenient way to manually execute queries.
198 |
199 | Here is an example of creating a table, inserting into it (with a parameterized command), and querying it without using ORM features.
200 |
201 | ```csharp
202 | db.Execute ("create table Stock(Symbol varchar(100) not null)");
203 | db.Execute ("insert into Stock(Symbol) values (?)", "MSFT");
204 | var stocks = db.Query ("select * from Stock");
205 | ```
206 |
207 | ## Using SQLCipher
208 |
209 | You can use an encrypted database by using the [sqlite-net-sqlcipher NuGet package](https://www.nuget.org/packages/sqlite-net-sqlcipher).
210 |
211 | The database key is set in the `SqliteConnectionString` passed to the connection constructor:
212 |
213 | ```csharp
214 | var options = new SQLiteConnectionString(databasePath, true,
215 | key: "password");
216 | var encryptedDb = new SQLiteAsyncConnection(options);
217 | ```
218 |
219 | If you need set pragmas to control the encryption, actions can be passed to the connection string:
220 |
221 | ```csharp
222 | var options2 = new SQLiteConnectionString (databasePath, true,
223 | key: "password",
224 | preKeyAction: db => db.Execute("PRAGMA cipher_default_use_hmac = OFF;"),
225 | postKeyAction: db => db.Execute ("PRAGMA kdf_iter = 128000;"));
226 | var encryptedDb2 = new SQLiteAsyncConnection (options2);
227 | ```
228 |
229 |
230 | ## Thank you!
231 |
232 | Thank you to the .NET community for embracing this project, and thank you to all the contributors who have helped to make this great.
233 |
234 | Thanks also to Tirza van Dijk (@tirzavdijk) for the great logo!
235 |
236 |
--------------------------------------------------------------------------------
/SQLite.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 11.00
3 | # Visual Studio 2010
4 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A0E59A10-7BD0-4554-B133-66FA850159BE}"
5 | ProjectSection(SolutionItems) = preProject
6 | Makefile = Makefile
7 | README.md = README.md
8 | EndProjectSection
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{FECC0E44-E626-49CB-BD8B-0CFBD93FBEFF}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite-net-std", "nuget\SQLite-net-std\SQLite-net-std.csproj", "{081D08D6-10F1-431B-88FE-469FD9FE898C}"
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiDiff", "tests\ApiDiff\ApiDiff.csproj", "{1DEF735C-B973-4ED9-8446-7FFA6D0B410B}"
15 | EndProject
16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite-net-base", "nuget\SQLite-net-base\SQLite-net-base.csproj", "{53D1953C-3641-47D0-BE08-14DB853CC576}"
17 | EndProject
18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite-net-sqlcipher", "nuget\SQLite-net-sqlcipher\SQLite-net-sqlcipher.csproj", "{59DB03EF-E28D-431E-9058-74AF316800EE}"
19 | EndProject
20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite.Tests", "tests\SQLite.Tests\SQLite.Tests.csproj", "{80B66A43-B358-4438-BF06-6351B86B121A}"
21 | EndProject
22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite-net-static", "nuget\SQLite-net-static\SQLite-net-static.csproj", "{7CD60DAE-D505-4C2E-80B3-296556CE711E}"
23 | EndProject
24 | Global
25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
26 | Debug|Any CPU = Debug|Any CPU
27 | Release|Any CPU = Release|Any CPU
28 | Debug|iPhoneSimulator = Debug|iPhoneSimulator
29 | Release|iPhone = Release|iPhone
30 | Release|iPhoneSimulator = Release|iPhoneSimulator
31 | Debug|iPhone = Debug|iPhone
32 | EndGlobalSection
33 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
34 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
35 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Debug|Any CPU.Build.0 = Debug|Any CPU
36 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Release|Any CPU.ActiveCfg = Release|Any CPU
37 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Release|Any CPU.Build.0 = Release|Any CPU
38 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
39 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
40 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Release|iPhone.ActiveCfg = Release|Any CPU
41 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Release|iPhone.Build.0 = Release|Any CPU
42 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
43 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
44 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Debug|iPhone.ActiveCfg = Debug|Any CPU
45 | {081D08D6-10F1-431B-88FE-469FD9FE898C}.Debug|iPhone.Build.0 = Debug|Any CPU
46 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
47 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Debug|Any CPU.Build.0 = Debug|Any CPU
48 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Release|Any CPU.ActiveCfg = Release|Any CPU
49 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Release|Any CPU.Build.0 = Release|Any CPU
50 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
51 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
52 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Release|iPhone.ActiveCfg = Release|Any CPU
53 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Release|iPhone.Build.0 = Release|Any CPU
54 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
55 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
56 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Debug|iPhone.ActiveCfg = Debug|Any CPU
57 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B}.Debug|iPhone.Build.0 = Debug|Any CPU
58 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
59 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Debug|Any CPU.Build.0 = Debug|Any CPU
60 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Release|Any CPU.ActiveCfg = Release|Any CPU
61 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Release|Any CPU.Build.0 = Release|Any CPU
62 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
63 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
64 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Release|iPhone.ActiveCfg = Release|Any CPU
65 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Release|iPhone.Build.0 = Release|Any CPU
66 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
67 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
68 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Debug|iPhone.ActiveCfg = Debug|Any CPU
69 | {53D1953C-3641-47D0-BE08-14DB853CC576}.Debug|iPhone.Build.0 = Debug|Any CPU
70 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
71 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
72 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Release|Any CPU.ActiveCfg = Release|Any CPU
73 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Release|Any CPU.Build.0 = Release|Any CPU
74 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
75 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
76 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Release|iPhone.ActiveCfg = Release|Any CPU
77 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Release|iPhone.Build.0 = Release|Any CPU
78 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
79 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
80 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Debug|iPhone.ActiveCfg = Debug|Any CPU
81 | {59DB03EF-E28D-431E-9058-74AF316800EE}.Debug|iPhone.Build.0 = Debug|Any CPU
82 | {80B66A43-B358-4438-BF06-6351B86B121A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
83 | {80B66A43-B358-4438-BF06-6351B86B121A}.Debug|Any CPU.Build.0 = Debug|Any CPU
84 | {80B66A43-B358-4438-BF06-6351B86B121A}.Release|Any CPU.ActiveCfg = Release|Any CPU
85 | {80B66A43-B358-4438-BF06-6351B86B121A}.Release|Any CPU.Build.0 = Release|Any CPU
86 | {80B66A43-B358-4438-BF06-6351B86B121A}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
87 | {80B66A43-B358-4438-BF06-6351B86B121A}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
88 | {80B66A43-B358-4438-BF06-6351B86B121A}.Release|iPhone.ActiveCfg = Release|Any CPU
89 | {80B66A43-B358-4438-BF06-6351B86B121A}.Release|iPhone.Build.0 = Release|Any CPU
90 | {80B66A43-B358-4438-BF06-6351B86B121A}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
91 | {80B66A43-B358-4438-BF06-6351B86B121A}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
92 | {80B66A43-B358-4438-BF06-6351B86B121A}.Debug|iPhone.ActiveCfg = Debug|Any CPU
93 | {80B66A43-B358-4438-BF06-6351B86B121A}.Debug|iPhone.Build.0 = Debug|Any CPU
94 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
95 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Debug|Any CPU.Build.0 = Debug|Any CPU
96 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Release|Any CPU.ActiveCfg = Release|Any CPU
97 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Release|Any CPU.Build.0 = Release|Any CPU
98 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
99 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
100 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Release|iPhone.ActiveCfg = Release|Any CPU
101 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Release|iPhone.Build.0 = Release|Any CPU
102 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
103 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
104 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Debug|iPhone.ActiveCfg = Debug|Any CPU
105 | {7CD60DAE-D505-4C2E-80B3-296556CE711E}.Debug|iPhone.Build.0 = Debug|Any CPU
106 | EndGlobalSection
107 | GlobalSection(NestedProjects) = preSolution
108 | {1DEF735C-B973-4ED9-8446-7FFA6D0B410B} = {FECC0E44-E626-49CB-BD8B-0CFBD93FBEFF}
109 | {80B66A43-B358-4438-BF06-6351B86B121A} = {FECC0E44-E626-49CB-BD8B-0CFBD93FBEFF}
110 | EndGlobalSection
111 | GlobalSection(MonoDevelopProperties) = preSolution
112 | StartupItem = tests\SQLite.Tests.csproj
113 | Policies = $0
114 | $0.TextStylePolicy = $1
115 | $1.FileWidth = 128
116 | $1.NoTabsAfterNonTabs = True
117 | $1.EolMarker = Unix
118 | $1.scope = text/x-csharp
119 | $0.CSharpFormattingPolicy = $2
120 | $2.NewLinesForBracesInProperties = False
121 | $2.NewLinesForBracesInAccessors = False
122 | $2.NewLinesForBracesInAnonymousMethods = False
123 | $2.NewLinesForBracesInControlBlocks = False
124 | $2.NewLinesForBracesInAnonymousTypes = False
125 | $2.NewLinesForBracesInObjectCollectionArrayInitializers = False
126 | $2.NewLinesForBracesInLambdaExpressionBody = False
127 | $2.scope = text/x-csharp
128 | $2.SpacingAfterMethodDeclarationName = True
129 | $2.SpaceAfterMethodCallName = True
130 | EndGlobalSection
131 | EndGlobal
132 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "9.0.100",
4 | "rollForward": "latestFeature"
5 | }
6 | }
--------------------------------------------------------------------------------
/nuget/Logo-low.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/praeclarum/sqlite-net/bf1eb50278d0ace79c3754575b34823cf7fb0934/nuget/Logo-low.png
--------------------------------------------------------------------------------
/nuget/SQLite-net-base/SQLite-net-base.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0;net8.0;net9.0
5 | SQLite-net
6 | sqlite-net-base
7 | SQLite-net .NET Standard Base Library
8 |
9 | This is a special version of SQLite-net-pcl that does not include a SQLitePCLRaw bundle.
10 | It is meant to give you all the power of SQLite-net but with the freedom to choose your own provider.
11 | Please use the package sqlite-net-pcl if you have no idea what any of this means.
12 |
13 | true
14 |
15 |
16 |
17 | USE_SQLITEPCL_RAW;NO_SQLITEPCL_RAW_BATTERIES;RELEASE
18 | bin\Release\$(TargetFramework)\SQLite-net.xml
19 |
20 |
21 | USE_SQLITEPCL_RAW;NO_SQLITEPCL_RAW_BATTERIES;DEBUG
22 | bin\Debug\$(TargetFramework)\SQLite-net.xml
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | SQLite.cs
31 |
32 |
33 | SQLiteAsync.cs
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/nuget/SQLite-net-sqlcipher/SQLite-net-sqlcipher.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0;net8.0;net9.0
5 | SQLite-net
6 | sqlite-net-sqlcipher
7 | SQLite-net SQLCipher .NET Standard Library
8 |
9 | SQLite-net is an open source and light weight library providing easy SQLite database storage for .NET, Mono, and Xamarin applications.
10 | This version uses SQLitePCLRaw to provide platform independent versions of SQLite with the SQLCipher extension.
11 | This enables secure access to the database with password (key) access.
12 |
13 | sqlite-net;sqlite;database;orm;encryption;sqlcipher
14 | true
15 |
16 |
17 |
18 | USE_SQLITEPCL_RAW;RELEASE
19 | bin\Release\$(TargetFramework)\SQLite-net.xml
20 |
21 |
22 | USE_SQLITEPCL_RAW;DEBUG
23 | bin\Debug\$(TargetFramework)\SQLite-net.xml
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | SQLite.cs
32 |
33 |
34 | SQLiteAsync.cs
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/nuget/SQLite-net-static/SQLite-net-static.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0;net8.0;net9.0
5 | SQLite-net
6 | sqlite-net-static
7 | SQLite-net .NET Standard P/Invoke Library
8 |
9 | SQLite-net is an open source and light weight library providing easy SQLite database storage for .NET, Mono, and Xamarin applications.
10 | This version uses P/Invokes to the "sqlite3" native library provided by the operating system.
11 | This works on Xamarin.iOS, Xamarin.Mac, Wilderness Labs' Meadow, and any other platform that has a "sqlite3" library in the path.
12 |
13 | true
14 |
15 |
16 |
17 | RELEASE
18 | bin\Release\$(TargetFramework)\SQLite-net.xml
19 |
20 |
21 | DEBUG
22 | bin\Debug\$(TargetFramework)\SQLite-net.xml
23 |
24 |
25 |
26 |
27 | SQLite.cs
28 |
29 |
30 | SQLiteAsync.cs
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/nuget/SQLite-net-std/SQLite-net-std.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0;net8.0;net9.0
5 | SQLite-net
6 | sqlite-net-pcl
7 | SQLite-net Official .NET Standard Library
8 |
9 | SQLite-net is an open source and light weight library providing easy SQLite database storage for .NET, Mono, and Xamarin applications.
10 | This version uses SQLitePCLRaw to provide platform independent versions of SQLite.
11 |
12 | true
13 |
14 |
15 |
16 | USE_SQLITEPCL_RAW;RELEASE
17 | bin\Release\$(TargetFramework)\SQLite-net.xml
18 |
19 |
20 | USE_SQLITEPCL_RAW;DEBUG
21 | bin\Debug\$(TargetFramework)\SQLite-net.xml
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 | SQLite.cs
30 |
31 |
32 | SQLiteAsync.cs
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Resources;
2 | using System.Reflection;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 |
6 | // General Information about an assembly is controlled through the following
7 | // set of attributes. Change these attribute values to modify the information
8 | // associated with an assembly.
9 | [assembly: AssemblyTitle("SQLite-net Official Portable Library")]
10 | [assembly: AssemblyDescription("Light weight library providing easy SQLite database storage")]
11 | [assembly: AssemblyConfiguration("")]
12 | [assembly: AssemblyCompany("Krueger Systems, Inc.")]
13 | [assembly: AssemblyProduct("SQLite-net")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 | [assembly: NeutralResourcesLanguage("en")]
17 |
18 | // Version information for an assembly consists of the following four values:
19 | //
20 | // Major Version
21 | // Minor Version
22 | // Build Number
23 | // Revision
24 | //
25 | // You can specify all the values or you can default the Build and Revision Numbers
26 | // by using the '*' as shown below:
27 | // [assembly: AssemblyVersion("1.0.*")]
28 | [assembly: AssemblyVersion("1.0.0.0")]
29 | [assembly: AssemblyFileVersion("1.0.0.0")]
30 |
--------------------------------------------------------------------------------
/tests/ApiDiff/ApiDiff.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0
4 | Exe
5 |
6 |
7 |
8 | SQLite.cs
9 |
10 |
11 | SQLiteAsync.cs
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/tests/ApiDiff/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Reflection;
4 | using System.Linq;
5 | using System.Text.RegularExpressions;
6 | using SQLite;
7 | using ListDiff;
8 |
9 | namespace ApiDiff
10 | {
11 | class Api
12 | {
13 | public string Name;
14 | public string Declaration;
15 | public string Index;
16 |
17 | static readonly Regex task1Re = new Regex (@"System\.Threading\.Tasks\.Task`1\[([^\]]*)\]");
18 | static readonly Regex taskRe = new Regex (@"System\.Threading\.Tasks\.Task(\s*)");
19 |
20 | public Api (MemberInfo member, string nameSuffix)
21 | {
22 | Name = member.Name;
23 | Declaration = member.ToString ();
24 | Index = Declaration.Replace ("AsyncTableQuery`1", "TableQuery`1");
25 |
26 | if (nameSuffix.Length > 0 && Name.EndsWith (nameSuffix)) {
27 | var indexName = Name.Substring (0, Name.IndexOf (nameSuffix));
28 | Index = taskRe
29 | .Replace (task1Re.Replace (Index.Replace (Name, indexName), "$1"), "Void$1")
30 | .Replace ("System.Int32", "Int32");
31 | Name = indexName;
32 | }
33 | }
34 | }
35 |
36 | class Apis
37 | {
38 | public List All;
39 | readonly string nameSuffix;
40 | readonly Type type;
41 |
42 | public static readonly HashSet connectionIgnores = new HashSet {
43 | "RunInTransaction",
44 | "RunInTransactionAsync",
45 | "BeginTransaction",
46 | "SaveTransactionPoint",
47 | "Commit",
48 | "Rollback",
49 | "RollbackTo",
50 | "IsInTransaction",
51 | "Release",
52 | "EndTransaction",
53 |
54 | "BusyTimeout",
55 | "GetBusyTimeout",
56 | "SetBusyTimeoutAsync",
57 |
58 | "GetConnection",
59 | "Handle",
60 |
61 | "Dispose",
62 |
63 | "Table",
64 | "CreateCommand",
65 | "TableChanged",
66 | };
67 |
68 | public static readonly HashSet queryIgnores = new HashSet {
69 | ".ctor",
70 | "Clone",
71 | "Connection",
72 | "Deferred",
73 | "Table",
74 | "GetEnumerator",
75 | };
76 |
77 | public Apis (Type type, HashSet ignores, string nameSuffix = "")
78 | {
79 | this.type = type;
80 | this.nameSuffix = nameSuffix;
81 | All = type.GetMembers (BindingFlags.Public|BindingFlags.Instance)
82 | .Where (x => !ignores.Contains(x.Name))
83 | .Where (x => x.MemberType != MemberTypes.NestedType)
84 | .Where (x => !x.Name.StartsWith("get_") && !x.Name.StartsWith ("set_") && !x.Name.StartsWith ("remove_") && !x.Name.StartsWith ("add_"))
85 | .Select (x => new Api(x, nameSuffix))
86 | .OrderBy (x => x.Index)
87 | .OrderBy (x => x.Name)
88 | .ToList ();
89 | }
90 |
91 | public int DumpComparison (Apis other)
92 | {
93 | Console.ForegroundColor = ConsoleColor.Cyan;
94 | Console.WriteLine ("## " + type.FullName);
95 | Console.WriteLine ();
96 |
97 | var diff = new ListDiff (All, other.All, (x, y) => x.Index == y.Index);
98 |
99 | var n = 0;
100 |
101 | foreach (var a in diff.Actions) {
102 | switch (a.ActionType) {
103 | case ListDiffActionType.Add:
104 | Console.ForegroundColor = ConsoleColor.Green;
105 | Console.WriteLine ($"- [ ] *add* `{a.DestinationItem.Index.Replace('`', '_')}`");
106 | n++;
107 | break;
108 | case ListDiffActionType.Remove:
109 | Console.ForegroundColor = ConsoleColor.Red;
110 | Console.WriteLine ($"- [ ] *remove* `{a.SourceItem.Index.Replace('`', '_')}`");
111 | n++;
112 | break;
113 | case ListDiffActionType.Update:
114 | Console.ForegroundColor = ConsoleColor.Gray;
115 | Console.WriteLine ($"- [x] `{a.SourceItem.Index.Replace('`', '_')}`");
116 | break;
117 | }
118 | }
119 | Console.ResetColor ();
120 | Console.WriteLine ();
121 | Console.WriteLine ($"**{n}** differences");
122 | Console.WriteLine ();
123 |
124 | return n;
125 | }
126 | }
127 |
128 | class MainClass
129 | {
130 | public static int Main (string[] args)
131 | {
132 | var synchronousConnection = new Apis (typeof (SQLiteConnection), Apis.connectionIgnores);
133 | var asynchronousConnection = new Apis (typeof (SQLiteAsyncConnection), Apis.connectionIgnores, "Async");
134 | var n = asynchronousConnection.DumpComparison (synchronousConnection);
135 |
136 | var synchronousQuery = new Apis (typeof (TableQuery<>), Apis.queryIgnores);
137 | var asynchronousQuery = new Apis (typeof (AsyncTableQuery<>), Apis.queryIgnores, "Async");
138 | n += asynchronousQuery.DumpComparison (synchronousQuery);
139 |
140 | return n > 0 ? 1 : 0;
141 | }
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests.iOS/Entitlements.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests.iOS/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleName
6 | SQLite-net
7 | CFBundleIdentifier
8 | com.kruegersystems.sqlite-net
9 | CFBundleShortVersionString
10 | 1.0
11 | CFBundleVersion
12 | 1.0
13 | LSRequiresIPhoneOS
14 |
15 | MinimumOSVersion
16 | 10.0
17 | UIDeviceFamily
18 |
19 | 1
20 | 2
21 |
22 | UISupportedInterfaceOrientations
23 |
24 | UIInterfaceOrientationPortrait
25 | UIInterfaceOrientationLandscapeLeft
26 | UIInterfaceOrientationLandscapeRight
27 |
28 | UILaunchStoryboardName
29 | LaunchScreen
30 | NSAppTransportSecurity
31 |
32 | NSAllowsArbitraryLoads
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests.iOS/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests.iOS/Main.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Collections.Generic;
4 |
5 | using Foundation;
6 | using UIKit;
7 |
8 | namespace SQLite.Tests.iOS
9 | {
10 | public class Application
11 | {
12 | // This is the main entry point of the application.
13 | static void Main(string[] args)
14 | {
15 | // if you want to use a different Application Delegate class from "UnitTestAppDelegate"
16 | // you can specify it here.
17 | UIApplication.Main(args, null, "UnitTestAppDelegate");
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests.iOS/SQLiteTestsiOS.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | iPhoneSimulator
6 | 8.0.30703
7 | 2.0
8 | {81850129-71C3-40C7-A48B-AA5D2C2E365E}
9 | {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
10 | Exe
11 | SQLite.Tests.iOS
12 | SQLiteTestsiOS
13 | Resources
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\iPhoneSimulator\Debug
20 | __UNIFIED__;__MOBILE__;__IOS__;DEBUG;NO_VB
21 | prompt
22 | 4
23 | iPhone Developer
24 | true
25 | true
26 | true
27 | None
28 | x86_64
29 | HttpClientHandler
30 | Default
31 | false
32 | true
33 |
34 |
35 |
36 |
37 | true
38 | bin\iPhone\Release
39 | __UNIFIED__;__MOBILE__;__IOS__;NO_VB
40 | prompt
41 | 4
42 | iPhone Developer
43 | true
44 |
45 |
46 | SdkOnly
47 | ARMv7, ARM64
48 | HttpClientHandler
49 | Default
50 |
51 |
52 |
53 |
54 | true
55 | bin\iPhoneSimulator\Release
56 | __UNIFIED__;__MOBILE__;__IOS__;NO_VB
57 | prompt
58 | 4
59 | iPhone Developer
60 | None
61 | x86_64
62 | HttpClientHandler
63 | Default
64 |
65 |
66 | true
67 | full
68 | false
69 | bin\iPhone\Debug
70 | __UNIFIED__;__MOBILE__;__IOS__;DEBUG;NO_VB
71 | prompt
72 | 4
73 | iPhone Developer
74 | false
75 | true
76 | false
77 | true
78 | true
79 |
80 |
81 | SdkOnly
82 | ARM64
83 | HttpClientHandler
84 | Default
85 | true
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | SQLite.cs
106 |
107 |
108 | SQLiteAsync.cs
109 |
110 |
111 |
112 |
113 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests.iOS/UnitTestAppDelegate.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Collections.Generic;
4 |
5 | using Foundation;
6 | using UIKit;
7 | using MonoTouch.NUnit.UI;
8 |
9 | namespace SQLite.Tests.iOS
10 | {
11 | // The UIApplicationDelegate for the application. This class is responsible for launching the
12 | // User Interface of the application, as well as listening (and optionally responding) to
13 | // application events from iOS.
14 | [Register("UnitTestAppDelegate")]
15 | public partial class UnitTestAppDelegate : UIApplicationDelegate
16 | {
17 | // class-level declarations
18 | UIWindow window;
19 | TouchRunner runner;
20 |
21 | //
22 | // This method is invoked when the application has loaded and is ready to run. In this
23 | // method you should instantiate the window, load the UI into it and then make the window
24 | // visible.
25 | //
26 | // You have 17 seconds to return from this method, or iOS will terminate your application.
27 | //
28 | public override bool FinishedLaunching(UIApplication app, NSDictionary options)
29 | {
30 | // create a new window instance based on the screen size
31 | window = new UIWindow(UIScreen.MainScreen.Bounds);
32 | runner = new TouchRunner(window);
33 |
34 | // register every tests included in the main application/assembly
35 | runner.Add(System.Reflection.Assembly.GetExecutingAssembly());
36 |
37 | window.RootViewController = new UINavigationController(runner.GetViewController());
38 |
39 | // make the window visible
40 | window.MakeKeyAndVisible();
41 |
42 | return true;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/AttributesTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using SQLite;
7 |
8 | #if NETFX_CORE
9 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
10 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
11 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
12 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
13 | #else
14 | using NUnit.Framework;
15 | #endif
16 |
17 | using System.Diagnostics;
18 |
19 | namespace SQLite.Tests
20 | {
21 | [TestFixture]
22 | public class AttributesTest
23 | {
24 | public AttributesTest ()
25 | {
26 | }
27 |
28 | [Test]
29 | public void TestCtors ()
30 | {
31 | Assert.DoesNotThrow (() => new CollationAttribute ("NOCASE"));
32 | Assert.DoesNotThrow (() => new ColumnAttribute ("Bar"));
33 | Assert.DoesNotThrow (() => new IgnoreAttribute ());
34 | Assert.DoesNotThrow (() => new IndexedAttribute ());
35 | Assert.DoesNotThrow (() => new NotNullAttribute ());
36 | Assert.DoesNotThrow (() => new PreserveAttribute ());
37 | Assert.DoesNotThrow (() => new PrimaryKeyAttribute ());
38 | Assert.DoesNotThrow (() => new StoreAsTextAttribute ());
39 | Assert.DoesNotThrow (() => new TableAttribute ("Foo"));
40 | Assert.DoesNotThrow (() => new UniqueAttribute ());
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/BackupTest.cs:
--------------------------------------------------------------------------------
1 | using System.Linq;
2 | using System.Text;
3 | using SQLite;
4 | using System.Threading.Tasks;
5 |
6 | #if NETFX_CORE
7 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
8 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
9 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
10 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
11 | #else
12 | using NUnit.Framework;
13 | #endif
14 |
15 | using System.IO;
16 |
17 | namespace SQLite.Tests
18 | {
19 | [TestFixture]
20 | public class BackupTest
21 | {
22 | [Test]
23 | public async Task BackupOneTable ()
24 | {
25 | var pathSrc = Path.GetTempFileName ();
26 | var pathDest = Path.GetTempFileName ();
27 |
28 | var db = new SQLiteAsyncConnection (pathSrc);
29 | await db.CreateTableAsync ().ConfigureAwait (false);
30 | await db.InsertAsync (new OrderLine { });
31 | var lines = await db.Table ().ToListAsync ();
32 | Assert.AreEqual (1, lines.Count);
33 |
34 | await db.BackupAsync (pathDest);
35 |
36 | var destLen = new FileInfo (pathDest).Length;
37 | Assert.True (destLen >= 4096);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/BooleanTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using SQLite;
7 |
8 | using System.Diagnostics;
9 |
10 | #if NETFX_CORE
11 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
12 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
13 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
14 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
15 | #else
16 | using NUnit.Framework;
17 | #endif
18 |
19 |
20 | namespace SQLite.Tests
21 | {
22 | [TestFixture]
23 | public class BooleanTest
24 | {
25 | public class VO
26 | {
27 | [AutoIncrement, PrimaryKey]
28 | public int ID { get; set; }
29 | public bool Flag { get; set; }
30 | public String Text { get; set; }
31 |
32 | public override string ToString()
33 | {
34 | return string.Format("VO:: ID:{0} Flag:{1} Text:{2}", ID, Flag, Text);
35 | }
36 | }
37 | public class DbAcs : SQLiteConnection
38 | {
39 | public DbAcs(String path)
40 | : base(path)
41 | {
42 | }
43 |
44 | public void buildTable()
45 | {
46 | CreateTable();
47 | }
48 |
49 | public int CountWithFlag(Boolean flag)
50 | {
51 | var cmd = CreateCommand("SELECT COUNT(*) FROM VO Where Flag = ?", flag);
52 | return cmd.ExecuteScalar();
53 | }
54 | }
55 |
56 | [Test]
57 | public void TestBoolean()
58 | {
59 | var tmpFile = TestPath.GetTempFileName();
60 | var db = new DbAcs(tmpFile);
61 | db.buildTable();
62 | for (int i = 0; i < 10; i++)
63 | db.Insert(new VO() { Flag = (i % 3 == 0), Text = String.Format("VO{0}", i) });
64 |
65 | // count vo which flag is true
66 | Assert.AreEqual(4, db.CountWithFlag(true));
67 | Assert.AreEqual(6, db.CountWithFlag(false));
68 |
69 | Debug.WriteLine("VO with true flag:");
70 | foreach (var vo in db.Query("SELECT * FROM VO Where Flag = ?", true))
71 | Debug.WriteLine (vo.ToString ());
72 |
73 | Debug.WriteLine ("VO with false flag:");
74 | foreach (var vo in db.Query("SELECT * FROM VO Where Flag = ?", false))
75 | Debug.WriteLine (vo.ToString ());
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/ByteArrayTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using SQLite;
7 |
8 | #if NETFX_CORE
9 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
10 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
11 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
12 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
13 | #else
14 | using NUnit.Framework;
15 | #endif
16 |
17 |
18 | namespace SQLite.Tests
19 | {
20 | [TestFixture]
21 | public class ByteArrayTest
22 | {
23 | public class ByteArrayClass
24 | {
25 | [PrimaryKey, AutoIncrement]
26 | public int ID { get; set; }
27 |
28 | public byte[] bytes { get; set; }
29 |
30 | public void AssertEquals(ByteArrayClass other)
31 | {
32 | Assert.AreEqual(other.ID, ID);
33 | if (other.bytes == null || bytes == null) {
34 | Assert.IsNull (other.bytes);
35 | Assert.IsNull (bytes);
36 | }
37 | else {
38 | Assert.AreEqual(other.bytes.Length, bytes.Length);
39 | for (var i = 0; i < bytes.Length; i++) {
40 | Assert.AreEqual(other.bytes[i], bytes[i]);
41 | }
42 | }
43 | }
44 | }
45 |
46 | [Test]
47 | [Description("Create objects with various byte arrays and check they can be stored and retrieved correctly")]
48 | public void ByteArrays()
49 | {
50 | //Byte Arrays for comparisson
51 | ByteArrayClass[] byteArrays = new ByteArrayClass[] {
52 | new ByteArrayClass() { bytes = new byte[] { 1, 2, 3, 4, 250, 252, 253, 254, 255 } }, //Range check
53 | new ByteArrayClass() { bytes = new byte[] { 0 } }, //null bytes need to be handled correctly
54 | new ByteArrayClass() { bytes = new byte[] { 0, 0 } },
55 | new ByteArrayClass() { bytes = new byte[] { 0, 1, 0 } },
56 | new ByteArrayClass() { bytes = new byte[] { 1, 0, 1 } },
57 | new ByteArrayClass() { bytes = new byte[] { } }, //Empty byte array should stay empty (and not become null)
58 | new ByteArrayClass() { bytes = null } //Null should be supported
59 | };
60 |
61 | SQLiteConnection database = new SQLiteConnection(TestPath.GetTempFileName());
62 | database.CreateTable();
63 |
64 | //Insert all of the ByteArrayClass
65 | foreach (ByteArrayClass b in byteArrays)
66 | database.Insert(b);
67 |
68 | //Get them back out
69 | ByteArrayClass[] fetchedByteArrays = database.Table().OrderBy(x => x.ID).ToArray();
70 |
71 | Assert.AreEqual(fetchedByteArrays.Length, byteArrays.Length);
72 | //Check they are the same
73 | for (int i = 0; i < byteArrays.Length; i++)
74 | {
75 | byteArrays[i].AssertEquals(fetchedByteArrays[i]);
76 | }
77 | }
78 |
79 | [Test]
80 | [Description("Uses a byte array to find a record")]
81 | public void ByteArrayWhere()
82 | {
83 | //Byte Arrays for comparisson
84 | ByteArrayClass[] byteArrays = new ByteArrayClass[] {
85 | new ByteArrayClass() { bytes = new byte[] { 1, 2, 3, 4, 250, 252, 253, 254, 255 } }, //Range check
86 | new ByteArrayClass() { bytes = new byte[] { 0 } }, //null bytes need to be handled correctly
87 | new ByteArrayClass() { bytes = new byte[] { 0, 0 } },
88 | new ByteArrayClass() { bytes = new byte[] { 0, 1, 0 } },
89 | new ByteArrayClass() { bytes = new byte[] { 1, 0, 1 } },
90 | new ByteArrayClass() { bytes = new byte[] { } }, //Empty byte array should stay empty (and not become null)
91 | new ByteArrayClass() { bytes = null } //Null should be supported
92 | };
93 |
94 | SQLiteConnection database = new SQLiteConnection(TestPath.GetTempFileName());
95 | database.CreateTable();
96 |
97 | byte[] criterion = new byte[] { 1, 0, 1 };
98 |
99 | //Insert all of the ByteArrayClass
100 | int id = 0;
101 | foreach (ByteArrayClass b in byteArrays)
102 | {
103 | database.Insert(b);
104 | if (b.bytes != null && criterion.SequenceEqual(b.bytes))
105 | id = b.ID;
106 | }
107 | Assert.AreNotEqual(0, id, "An ID wasn't set");
108 |
109 | //Get it back out
110 | ByteArrayClass fetchedByteArray = database.Table().Where(x => x.bytes == criterion).First();
111 | Assert.IsNotNull(fetchedByteArray);
112 | //Check they are the same
113 | Assert.AreEqual(id, fetchedByteArray.ID);
114 | }
115 |
116 | [Test]
117 | [Description("Uses a null byte array to find a record")]
118 | public void ByteArrayWhereNull()
119 | {
120 | //Byte Arrays for comparisson
121 | ByteArrayClass[] byteArrays = new ByteArrayClass[] {
122 | new ByteArrayClass() { bytes = new byte[] { 1, 2, 3, 4, 250, 252, 253, 254, 255 } }, //Range check
123 | new ByteArrayClass() { bytes = new byte[] { 0 } }, //null bytes need to be handled correctly
124 | new ByteArrayClass() { bytes = new byte[] { 0, 0 } },
125 | new ByteArrayClass() { bytes = new byte[] { 0, 1, 0 } },
126 | new ByteArrayClass() { bytes = new byte[] { 1, 0, 1 } },
127 | new ByteArrayClass() { bytes = new byte[] { } }, //Empty byte array should stay empty (and not become null)
128 | new ByteArrayClass() { bytes = null } //Null should be supported
129 | };
130 |
131 | SQLiteConnection database = new SQLiteConnection(TestPath.GetTempFileName());
132 | database.CreateTable();
133 |
134 | byte[] criterion = null;
135 |
136 | //Insert all of the ByteArrayClass
137 | int id = 0;
138 | foreach (ByteArrayClass b in byteArrays)
139 | {
140 | database.Insert(b);
141 | if (b.bytes == null)
142 | id = b.ID;
143 | }
144 | Assert.AreNotEqual(0, id, "An ID wasn't set");
145 |
146 | //Get it back out
147 | ByteArrayClass fetchedByteArray = database.Table().Where(x => x.bytes == criterion).First();
148 |
149 | Assert.IsNotNull(fetchedByteArray);
150 | //Check they are the same
151 | Assert.AreEqual(id, fetchedByteArray.ID);
152 | }
153 |
154 | [Test]
155 | [Description("Create A large byte array and check it can be stored and retrieved correctly")]
156 | public void LargeByteArray()
157 | {
158 | const int byteArraySize = 1024 * 1024;
159 | byte[] bytes = new byte[byteArraySize];
160 | for (int i = 0; i < byteArraySize; i++)
161 | bytes[i] = (byte)(i % 256);
162 |
163 | ByteArrayClass byteArray = new ByteArrayClass() { bytes = bytes };
164 |
165 | SQLiteConnection database = new SQLiteConnection(TestPath.GetTempFileName());
166 | database.CreateTable();
167 |
168 | //Insert the ByteArrayClass
169 | database.Insert(byteArray);
170 |
171 | //Get it back out
172 | ByteArrayClass[] fetchedByteArrays = database.Table().ToArray();
173 |
174 | Assert.AreEqual(fetchedByteArrays.Length, 1);
175 |
176 | //Check they are the same
177 | byteArray.AssertEquals(fetchedByteArrays[0]);
178 | }
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/CollateTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using SQLite;
7 |
8 | #if NETFX_CORE
9 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
10 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
11 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
12 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
13 | #else
14 | using NUnit.Framework;
15 | #endif
16 |
17 | using System.Diagnostics;
18 |
19 | namespace SQLite.Tests
20 | {
21 | [TestFixture]
22 | public class CollateTest
23 | {
24 | public class TestObj
25 | {
26 | [AutoIncrement, PrimaryKey]
27 | public int Id { get; set; }
28 |
29 | public string CollateDefault { get; set; }
30 |
31 | [Collation("BINARY")]
32 | public string CollateBinary { get; set; }
33 |
34 | [Collation("RTRIM")]
35 | public string CollateRTrim { get; set; }
36 |
37 | [Collation("NOCASE")]
38 | public string CollateNoCase { get; set; }
39 |
40 | public override string ToString ()
41 | {
42 | return string.Format("[TestObj: Id={0}]", Id);
43 | }
44 | }
45 |
46 | public class TestDb : SQLiteConnection
47 | {
48 | public TestDb(String path)
49 | : base(path)
50 | {
51 | Trace = true;
52 | CreateTable();
53 | }
54 | }
55 |
56 | [Test]
57 | public void Collate()
58 | {
59 | var obj = new TestObj() {
60 | CollateDefault = "Alpha ",
61 | CollateBinary = "Alpha ",
62 | CollateRTrim = "Alpha ",
63 | CollateNoCase = "Alpha ",
64 | };
65 |
66 | var db = new TestDb(TestPath.GetTempFileName());
67 |
68 | db.Insert(obj);
69 |
70 | Assert.AreEqual(1, (from o in db.Table() where o.CollateDefault == "Alpha " select o).Count());
71 | Assert.AreEqual(0, (from o in db.Table() where o.CollateDefault == "ALPHA " select o).Count());
72 | Assert.AreEqual(0, (from o in db.Table() where o.CollateDefault == "Alpha" select o).Count());
73 | Assert.AreEqual(0, (from o in db.Table() where o.CollateDefault == "ALPHA" select o).Count());
74 |
75 | Assert.AreEqual(1, (from o in db.Table() where o.CollateBinary == "Alpha " select o).Count());
76 | Assert.AreEqual(0, (from o in db.Table() where o.CollateBinary == "ALPHA " select o).Count());
77 | Assert.AreEqual(0, (from o in db.Table() where o.CollateBinary == "Alpha" select o).Count());
78 | Assert.AreEqual(0, (from o in db.Table() where o.CollateBinary == "ALPHA" select o).Count());
79 |
80 | Assert.AreEqual(1, (from o in db.Table() where o.CollateRTrim == "Alpha " select o).Count());
81 | Assert.AreEqual(0, (from o in db.Table() where o.CollateRTrim == "ALPHA " select o).Count());
82 | Assert.AreEqual(1, (from o in db.Table() where o.CollateRTrim == "Alpha" select o).Count());
83 | Assert.AreEqual(0, (from o in db.Table() where o.CollateRTrim == "ALPHA" select o).Count());
84 |
85 | Assert.AreEqual(1, (from o in db.Table() where o.CollateNoCase == "Alpha " select o).Count());
86 | Assert.AreEqual(1, (from o in db.Table() where o.CollateNoCase == "ALPHA " select o).Count());
87 | Assert.AreEqual(0, (from o in db.Table() where o.CollateNoCase == "Alpha" select o).Count());
88 | Assert.AreEqual(0, (from o in db.Table() where o.CollateNoCase == "ALPHA" select o).Count());
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/ConcurrencyTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading;
5 | using System.Threading.Tasks;
6 | using System.IO;
7 |
8 | #if NETFX_CORE
9 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
10 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
11 | using TearDown = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestCleanupAttribute;
12 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
13 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
14 | #else
15 | using NUnit.Framework;
16 | #endif
17 |
18 | namespace SQLite.Tests
19 | {
20 | [TestFixture, NUnit.Framework.Ignore("Fails to run on .NET Core 3.1 Mac")]
21 | public class ConcurrencyTest
22 | {
23 | public class TestObj
24 | {
25 | [AutoIncrement, PrimaryKey]
26 | public int Id { get; set; }
27 |
28 | public override string ToString()
29 | {
30 | return string.Format("[TestObj: Id={0}]", Id);
31 | }
32 | }
33 |
34 | public class DbReader
35 | {
36 | private CancellationToken cancellationToken;
37 |
38 | public DbReader(CancellationToken cancellationToken)
39 | {
40 | this.cancellationToken = cancellationToken;
41 | }
42 |
43 | public Task Run()
44 | {
45 | var t = Task.Run(() =>
46 | {
47 | try
48 | {
49 | while (true)
50 | {
51 | //
52 | // NOTE: Change this to readwrite and then it does work ???
53 | // No more IOERROR
54 | //
55 |
56 | var flags = SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadOnly;
57 | #if __IOS__
58 | flags = SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite;
59 | #endif
60 | using (var dbConnection = new DbConnection(flags))
61 | {
62 | var records = dbConnection.Table().ToList();
63 | System.Diagnostics.Debug.WriteLine($"{Environment.CurrentManagedThreadId} Read records: {records.Count}");
64 | }
65 |
66 | // No await so we stay on the same thread
67 | Task.Delay(10).GetAwaiter().GetResult();
68 | cancellationToken.ThrowIfCancellationRequested();
69 | }
70 | }
71 | catch (OperationCanceledException)
72 | {
73 | }
74 | });
75 |
76 | return t;
77 | }
78 |
79 | }
80 |
81 | public class DbWriter
82 | {
83 | private CancellationToken cancellationToken;
84 |
85 | public DbWriter(CancellationToken cancellationToken)
86 | {
87 | this.cancellationToken = cancellationToken;
88 | }
89 |
90 | public Task Run()
91 | {
92 | var t = Task.Run(() =>
93 | {
94 | try
95 | {
96 | while (true)
97 | {
98 | using (var dbConnection = new DbConnection(SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite))
99 | {
100 | System.Diagnostics.Debug.WriteLine($"{Environment.CurrentManagedThreadId} Start insert");
101 |
102 | for (var i = 0; i < 50; i++)
103 | {
104 | var newRecord = new TestObj()
105 | {
106 | };
107 |
108 | dbConnection.Insert(newRecord);
109 | }
110 |
111 | System.Diagnostics.Debug.WriteLine($"{Environment.CurrentManagedThreadId} Inserted records");
112 | }
113 |
114 | // No await so we stay on the same thread
115 | Task.Delay(1).GetAwaiter().GetResult();
116 | cancellationToken.ThrowIfCancellationRequested();
117 | }
118 | }
119 | catch (OperationCanceledException)
120 | {
121 | }
122 | });
123 |
124 | return t;
125 | }
126 |
127 | }
128 |
129 | public class DbConnection : SQLiteConnection
130 | {
131 | private static string DbPath = GetTempFileName();
132 |
133 | private static string GetTempFileName()
134 | {
135 | #if NETFX_CORE
136 | var name = Guid.NewGuid() + ".sqlite";
137 | return Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, name);
138 | #else
139 | return Path.GetTempFileName();
140 | #endif
141 | }
142 |
143 |
144 | public DbConnection(SQLiteOpenFlags openflags) : base(DbPath, openflags)
145 | {
146 | this.BusyTimeout = TimeSpan.FromSeconds(5);
147 | }
148 |
149 | public void CreateTables()
150 | {
151 | CreateTable();
152 | }
153 | }
154 |
155 | [SetUp]
156 | public void Setup()
157 | {
158 | using (var dbConenction = new DbConnection(SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create))
159 | {
160 | dbConenction.CreateTables();
161 | }
162 | }
163 |
164 |
165 | [Test]
166 | public void TestLoad()
167 | {
168 | try
169 | {
170 | //var result = SQLitePCL.raw.sqlite3_threadsafe();
171 | //Assert.AreEqual(2, result);
172 | // Yes it's threadsafe on iOS
173 |
174 | var tokenSource = new CancellationTokenSource();
175 | var tasks = new List();
176 | tasks.Add(new DbReader(tokenSource.Token).Run());
177 | tasks.Add(new DbWriter(tokenSource.Token).Run());
178 |
179 | // Wait 5sec
180 | tokenSource.CancelAfter(5000);
181 |
182 | Task.WhenAll(tasks).GetAwaiter().GetResult();
183 | }
184 | catch (Exception ex)
185 | {
186 | Assert.Fail(ex.ToString());
187 | }
188 | }
189 |
190 | ///
191 | /// Test for issue #761. Because the nature of this test is a race condition,
192 | /// it is not guaranteed to fail if the issue is present. It does appear to
193 | /// fail most of the time, though.
194 | ///
195 | [Test]
196 | public void TestInsertCommandCreation ()
197 | {
198 | using (var dbConnection =
199 | new DbConnection (SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create)) {
200 | var obj1 = new TestObj ();
201 | var obj2 = new TestObj ();
202 | var taskA = Task.Run (() => {
203 | dbConnection.Insert (obj1);
204 | });
205 | var taskB = Task.Run (() => {
206 | dbConnection.Insert (obj2);
207 | });
208 |
209 | Task.WhenAll (taskA, taskB).Wait ();
210 | }
211 | }
212 | }
213 | }
214 |
215 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/ContainsTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using SQLite;
7 |
8 | #if NETFX_CORE
9 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
10 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
11 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
12 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
13 | #else
14 | using NUnit.Framework;
15 | #endif
16 |
17 | using System.Diagnostics;
18 |
19 | namespace SQLite.Tests
20 | {
21 | [TestFixture]
22 | public class ContainsTest
23 | {
24 | public class TestObj
25 | {
26 | [AutoIncrement, PrimaryKey]
27 | public int Id { get; set; }
28 |
29 | public string Name { get; set; }
30 |
31 | public override string ToString ()
32 | {
33 | return string.Format("[TestObj: Id={0}, Name={1}]", Id, Name);
34 | }
35 | }
36 |
37 | public class TestDb : SQLiteConnection
38 | {
39 | public TestDb(String path)
40 | : base(path)
41 | {
42 | CreateTable();
43 | }
44 | }
45 |
46 | [Test]
47 | public void ContainsConstantData()
48 | {
49 | int n = 20;
50 | var cq =from i in Enumerable.Range(1, n)
51 | select new TestObj() {
52 | Name = i.ToString()
53 | };
54 |
55 | var db = new TestDb(TestPath.GetTempFileName());
56 |
57 | db.InsertAll(cq);
58 |
59 | db.Trace = true;
60 |
61 | var tensq = new string[] { "0", "10", "20" };
62 | var tens = (from o in db.Table() where tensq.Contains(o.Name) select o).ToList();
63 | Assert.AreEqual(2, tens.Count);
64 |
65 | var moreq = new string[] { "0", "x", "99", "10", "20", "234324" };
66 | var more = (from o in db.Table() where moreq.Contains(o.Name) select o).ToList();
67 | Assert.AreEqual(2, more.Count);
68 | }
69 |
70 | [Test]
71 | public void ContainsQueriedData()
72 | {
73 | int n = 20;
74 | var cq =from i in Enumerable.Range(1, n)
75 | select new TestObj() {
76 | Name = i.ToString()
77 | };
78 |
79 | var db = new TestDb(TestPath.GetTempFileName());
80 |
81 | db.InsertAll(cq);
82 |
83 | db.Trace = true;
84 |
85 | var tensq = new string[] { "0", "10", "20" };
86 | var tens = (from o in db.Table() where tensq.Contains(o.Name) select o).ToList();
87 | Assert.AreEqual(2, tens.Count);
88 |
89 | var moreq = new string[] { "0", "x", "99", "10", "20", "234324" };
90 | var more = (from o in db.Table() where moreq.Contains(o.Name) select o).ToList();
91 | Assert.AreEqual(2, more.Count);
92 |
93 | // https://github.com/praeclarum/sqlite-net/issues/28
94 | var moreq2 = moreq.ToList ();
95 | var more2 = (from o in db.Table() where moreq2.Contains(o.Name) select o).ToList();
96 | Assert.AreEqual(2, more2.Count);
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/CreateTableImplicitTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 |
6 | #if NETFX_CORE
7 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
8 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
9 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
10 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
11 | #else
12 | using NUnit.Framework;
13 | #endif
14 |
15 | namespace SQLite.Tests
16 | {
17 | [TestFixture]
18 | public class CreateTableImplicitTest
19 | {
20 |
21 | class NoAttributes
22 | {
23 | public int Id { get; set; }
24 | public string AColumn { get; set; }
25 | public int IndexedId { get; set; }
26 | }
27 |
28 | class NoAttributesNoOptions
29 | {
30 | public int Id { get; set; }
31 | public string AColumn { get; set; }
32 | public int IndexedId { get; set; }
33 | }
34 |
35 | class PkAttribute
36 | {
37 | [PrimaryKey]
38 | public int Id { get; set; }
39 | public string AColumn { get; set; }
40 | public int IndexedId { get; set; }
41 | }
42 |
43 | private void CheckPK(TestDb db)
44 | {
45 | for (int i = 1; i <= 10; i++)
46 | {
47 | var na = new NoAttributes { Id = i, AColumn = i.ToString(), IndexedId = 0 };
48 | db.Insert(na);
49 | }
50 | var item = db.Get(2);
51 | Assert.IsNotNull(item);
52 | Assert.AreEqual(2, item.Id);
53 | }
54 |
55 | [Test]
56 | public void WithoutImplicitMapping ()
57 | {
58 | var db = new TestDb ();
59 |
60 | db.CreateTable();
61 |
62 | var mapping = db.GetMapping ();
63 |
64 | Assert.IsNull (mapping.PK, "Should not be a key");
65 |
66 | var column = mapping.Columns[2];
67 | Assert.AreEqual("IndexedId", column.Name);
68 | Assert.IsFalse(column.Indices.Any());
69 | }
70 |
71 | [Test]
72 | public void ImplicitPK()
73 | {
74 | var db = new TestDb();
75 |
76 | db.CreateTable(CreateFlags.ImplicitPK);
77 |
78 | var mapping = db.GetMapping();
79 |
80 | Assert.IsNotNull(mapping.PK);
81 | Assert.AreEqual("Id", mapping.PK.Name);
82 | Assert.IsTrue(mapping.PK.IsPK);
83 | Assert.IsFalse(mapping.PK.IsAutoInc);
84 |
85 | CheckPK(db);
86 | }
87 |
88 |
89 | [Test]
90 | public void ImplicitAutoInc()
91 | {
92 | var db = new TestDb();
93 |
94 | db.CreateTable(CreateFlags.AutoIncPK);
95 |
96 | var mapping = db.GetMapping();
97 |
98 | Assert.IsNotNull(mapping.PK);
99 | Assert.AreEqual("Id", mapping.PK.Name);
100 | Assert.IsTrue(mapping.PK.IsPK);
101 | Assert.IsTrue(mapping.PK.IsAutoInc);
102 | }
103 |
104 | [Test]
105 | public void ImplicitIndex()
106 | {
107 | var db = new TestDb();
108 |
109 | db.CreateTable(CreateFlags.ImplicitIndex);
110 |
111 | var mapping = db.GetMapping();
112 | var column = mapping.Columns[2];
113 | Assert.AreEqual("IndexedId", column.Name);
114 | Assert.IsTrue(column.Indices.Any());
115 | }
116 |
117 | [Test]
118 | public void ImplicitPKAutoInc()
119 | {
120 | var db = new TestDb();
121 |
122 | db.CreateTable(typeof(NoAttributes), CreateFlags.ImplicitPK | CreateFlags.AutoIncPK);
123 |
124 | var mapping = db.GetMapping();
125 |
126 | Assert.IsNotNull(mapping.PK);
127 | Assert.AreEqual("Id", mapping.PK.Name);
128 | Assert.IsTrue(mapping.PK.IsPK);
129 | Assert.IsTrue(mapping.PK.IsAutoInc);
130 | }
131 |
132 | [Test]
133 | public void ImplicitAutoIncAsPassedInTypes()
134 | {
135 | var db = new TestDb();
136 |
137 | db.CreateTable(typeof(PkAttribute), CreateFlags.AutoIncPK);
138 |
139 | var mapping = db.GetMapping();
140 |
141 | Assert.IsNotNull(mapping.PK);
142 | Assert.AreEqual("Id", mapping.PK.Name);
143 | Assert.IsTrue(mapping.PK.IsPK);
144 | Assert.IsTrue(mapping.PK.IsAutoInc);
145 | }
146 |
147 | [Test]
148 | public void ImplicitPkAsPassedInTypes()
149 | {
150 | var db = new TestDb();
151 |
152 | db.CreateTable(typeof(NoAttributes), CreateFlags.ImplicitPK);
153 |
154 | var mapping = db.GetMapping();
155 |
156 | Assert.IsNotNull(mapping.PK);
157 | Assert.AreEqual("Id", mapping.PK.Name);
158 | Assert.IsTrue(mapping.PK.IsPK);
159 | Assert.IsFalse(mapping.PK.IsAutoInc);
160 | }
161 |
162 | [Test]
163 | public void ImplicitPKAutoIncAsPassedInTypes()
164 | {
165 | var db = new TestDb();
166 |
167 | db.CreateTable(typeof(NoAttributes), CreateFlags.ImplicitPK | CreateFlags.AutoIncPK);
168 |
169 | var mapping = db.GetMapping();
170 |
171 | Assert.IsNotNull(mapping.PK);
172 | Assert.AreEqual("Id", mapping.PK.Name);
173 | Assert.IsTrue(mapping.PK.IsPK);
174 | Assert.IsTrue(mapping.PK.IsAutoInc);
175 | }
176 | }
177 | }
178 |
179 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/CreateTableTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 |
4 | #if NETFX_CORE
5 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
6 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
7 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
8 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
9 | #else
10 | using NUnit.Framework;
11 | #endif
12 |
13 |
14 | namespace SQLite.Tests
15 | {
16 | [TestFixture]
17 | public class CreateTableTest
18 | {
19 | class NoPropObject
20 | {
21 | }
22 |
23 | [Test]
24 | public void CreateTypeWithNoProps ()
25 | {
26 | var db = new TestDb ();
27 | Assert.Throws (() => db.CreateTable ());
28 | }
29 |
30 | [Test]
31 | public void CreateThem ()
32 | {
33 | var db = new TestDb ();
34 |
35 | db.CreateTable ();
36 | db.CreateTable ();
37 | db.CreateTable ();
38 | db.CreateTable ();
39 |
40 | VerifyCreations(db);
41 | }
42 |
43 | [Test]
44 | public void CreateAsPassedInTypes ()
45 | {
46 | var db = new TestDb();
47 |
48 | db.CreateTable(typeof(Product));
49 | db.CreateTable(typeof(Order));
50 | db.CreateTable(typeof(OrderLine));
51 | db.CreateTable(typeof(OrderHistory));
52 |
53 | VerifyCreations(db);
54 | }
55 |
56 | [Test]
57 | public void CreateTwice ()
58 | {
59 | var db = new TestDb ();
60 |
61 | db.CreateTable ();
62 | db.CreateTable ();
63 | db.CreateTable ();
64 | db.CreateTable ();
65 | db.CreateTable ();
66 |
67 | VerifyCreations(db);
68 | }
69 |
70 | private static void VerifyCreations(TestDb db)
71 | {
72 | var orderLine = db.GetMapping(typeof(OrderLine));
73 | Assert.AreEqual(6, orderLine.Columns.Length);
74 |
75 | var l = new OrderLine()
76 | {
77 | Status = OrderLineStatus.Shipped
78 | };
79 | db.Insert(l);
80 | var lo = db.Table().First(x => x.Status == OrderLineStatus.Shipped);
81 | Assert.AreEqual(lo.Id, l.Id);
82 | }
83 |
84 | class Issue115_MyObject
85 | {
86 | [PrimaryKey]
87 | public string UniqueId { get; set; }
88 | public byte OtherValue { get; set; }
89 | }
90 |
91 | [Test]
92 | public void Issue115_MissingPrimaryKey ()
93 | {
94 | using (var conn = new TestDb ()) {
95 |
96 | conn.CreateTable ();
97 | conn.InsertAll (from i in Enumerable.Range (0, 10) select new Issue115_MyObject {
98 | UniqueId = i.ToString (),
99 | OtherValue = (byte)(i * 10),
100 | });
101 |
102 | var query = conn.Table ();
103 | foreach (var itm in query) {
104 | itm.OtherValue++;
105 | Assert.AreEqual (1, conn.Update (itm, typeof(Issue115_MyObject)));
106 | }
107 | }
108 | }
109 |
110 | [Table("WantsNoRowId", WithoutRowId = true)]
111 | class WantsNoRowId
112 | {
113 | [PrimaryKey]
114 | public int Id { get; set; }
115 | public string Name { get; set; }
116 | }
117 |
118 | [Table("sqlite_master")]
119 | class SqliteMaster
120 | {
121 | [Column ("type")]
122 | public string Type { get; set; }
123 |
124 | [Column ("name")]
125 | public string Name { get; set; }
126 |
127 | [Column ("tbl_name")]
128 | public string TableName { get; set; }
129 |
130 | [Column ("rootpage")]
131 | public int RootPage { get; set; }
132 |
133 | [Column ("sql")]
134 | public string Sql { get; set; }
135 | }
136 |
137 | [Test]
138 | public void WithoutRowId ()
139 | {
140 | using(var conn = new TestDb ())
141 | {
142 | conn.CreateTable ();
143 | var info = conn.Table().Where(m => m.TableName=="OrderLine").First ();
144 | Assert.That (!info.Sql.Contains ("without rowid"));
145 |
146 | conn.CreateTable ();
147 | info = conn.Table().Where(m => m.TableName=="WantsNoRowId").First ();
148 | Assert.That (info.Sql.Contains ("without rowid"));
149 | }
150 | }
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/DateTimeOffsetTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | #if NETFX_CORE
4 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
5 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
6 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
7 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
8 | #else
9 | using NUnit.Framework;
10 | #endif
11 |
12 | namespace SQLite.Tests
13 | {
14 | [TestFixture]
15 | public class DateTimeOffsetTest
16 | {
17 | class TestObj
18 | {
19 | [PrimaryKey, AutoIncrement]
20 | public int Id { get; set; }
21 |
22 | public string Name { get; set; }
23 | public DateTimeOffset ModifiedTime { get; set; }
24 | }
25 |
26 |
27 | [Test]
28 | public void AsTicks ()
29 | {
30 | var db = new TestDb ();
31 | TestDateTimeOffset (db);
32 | }
33 |
34 |
35 | [Test]
36 | public void AsyncAsTicks ()
37 | {
38 | var db = new SQLiteAsyncConnection (TestPath.GetTempFileName ());
39 | TestAsyncDateTimeOffset (db);
40 | }
41 |
42 | void TestAsyncDateTimeOffset (SQLiteAsyncConnection db)
43 | {
44 | db.CreateTableAsync ().Wait ();
45 |
46 | TestObj o, o2;
47 |
48 | //
49 | // Ticks
50 | //
51 | o = new TestObj {
52 | ModifiedTime = new DateTimeOffset (2012, 1, 14, 3, 2, 1, TimeSpan.Zero),
53 | };
54 | db.InsertAsync (o).Wait ();
55 | o2 = db.GetAsync (o.Id).Result;
56 | Assert.AreEqual (o.ModifiedTime, o2.ModifiedTime);
57 | }
58 |
59 | void TestDateTimeOffset (TestDb db)
60 | {
61 | db.CreateTable ();
62 |
63 | TestObj o, o2;
64 |
65 | //
66 | // Ticks
67 | //
68 | o = new TestObj {
69 | ModifiedTime = new DateTimeOffset (2012, 1, 14, 3, 2, 1, TimeSpan.Zero),
70 | };
71 | db.Insert (o);
72 | o2 = db.Get (o.Id);
73 | Assert.AreEqual (o.ModifiedTime, o2.ModifiedTime);
74 | }
75 |
76 | }
77 | }
78 |
79 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/DateTimeTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading.Tasks;
3 |
4 | #if NETFX_CORE
5 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
6 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
7 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
8 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
9 | #else
10 | using NUnit.Framework;
11 | #endif
12 |
13 | namespace SQLite.Tests
14 | {
15 | [TestFixture]
16 | public class DateTimeTest
17 | {
18 | const string DefaultSQLiteDateTimeString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff";
19 |
20 | class TestObj
21 | {
22 | [PrimaryKey, AutoIncrement]
23 | public int Id { get; set; }
24 |
25 | public string Name { get; set; }
26 | public DateTime ModifiedTime { get; set; }
27 | }
28 |
29 |
30 | [Test]
31 | public void AsTicks ()
32 | {
33 | var dateTime = new DateTime (2012, 1, 14, 3, 2, 1, 234);
34 | var db = new TestDb (storeDateTimeAsTicks: true);
35 | TestDateTime (db, dateTime, dateTime.Ticks.ToString ());
36 | }
37 |
38 | [Test]
39 | public void AsStrings ()
40 | {
41 | var dateTime = new DateTime (2012, 1, 14, 3, 2, 1, 234);
42 | var db = new TestDb (storeDateTimeAsTicks: false);
43 | TestDateTime (db, dateTime, dateTime.ToString (DefaultSQLiteDateTimeString));
44 | }
45 |
46 | [TestCase ("o")]
47 | [TestCase ("MMM'-'dd'-'yyyy' 'HH':'mm':'ss'.'fffffff")]
48 | public void AsCustomStrings (string format)
49 | {
50 | var dateTime = new DateTime (2012, 1, 14, 3, 2, 1, 234);
51 | var db = new TestDb (CustomDateTimeString (format));
52 | TestDateTime (db, dateTime, dateTime.ToString (format, System.Globalization.CultureInfo.InvariantCulture));
53 | }
54 |
55 | [Test]
56 | public void AsyncAsTicks ()
57 | {
58 | var dateTime = new DateTime (2012, 1, 14, 3, 2, 1, 234);
59 | var db = new SQLiteAsyncConnection (TestPath.GetTempFileName (), true);
60 | TestAsyncDateTime (db, dateTime, dateTime.Ticks.ToString ());
61 | }
62 |
63 | [Test]
64 | public void AsyncAsString ()
65 | {
66 | var dateTime = new DateTime (2012, 1, 14, 3, 2, 1, 234);
67 | var db = new SQLiteAsyncConnection (TestPath.GetTempFileName (), false);
68 | TestAsyncDateTime (db, dateTime, dateTime.ToString (DefaultSQLiteDateTimeString));
69 | }
70 |
71 | [TestCase ("o")]
72 | [TestCase ("MMM'-'dd'-'yyyy' 'HH':'mm':'ss'.'fffffff")]
73 | public void AsyncAsCustomStrings (string format)
74 | {
75 | var dateTime = new DateTime (2012, 1, 14, 3, 2, 1, 234);
76 | var db = new SQLiteAsyncConnection (CustomDateTimeString (format));
77 | TestAsyncDateTime (db, dateTime, dateTime.ToString (format,System.Globalization.CultureInfo.InvariantCulture));
78 | }
79 |
80 | SQLiteConnectionString CustomDateTimeString (string dateTimeFormat) => new SQLiteConnectionString (TestPath.GetTempFileName (), SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, false, dateTimeStringFormat: dateTimeFormat);
81 |
82 | void TestAsyncDateTime (SQLiteAsyncConnection db, DateTime dateTime, string expected)
83 | {
84 | db.CreateTableAsync ().Wait ();
85 |
86 | TestObj o, o2;
87 |
88 | //
89 | // Ticks
90 | //
91 | o = new TestObj {
92 | ModifiedTime = dateTime,
93 | };
94 | db.InsertAsync (o).Wait ();
95 | o2 = db.GetAsync (o.Id).Result;
96 | Assert.AreEqual (o.ModifiedTime, o2.ModifiedTime);
97 |
98 | var stored = db.ExecuteScalarAsync ("SELECT ModifiedTime FROM TestObj;").Result;
99 | Assert.AreEqual (expected, stored);
100 | }
101 |
102 | void TestDateTime (TestDb db, DateTime dateTime, string expected)
103 | {
104 | db.CreateTable ();
105 |
106 | TestObj o, o2;
107 |
108 | //
109 | // Ticks
110 | //
111 | o = new TestObj {
112 | ModifiedTime = dateTime,
113 | };
114 | db.Insert (o);
115 | o2 = db.Get (o.Id);
116 | Assert.AreEqual (o.ModifiedTime, o2.ModifiedTime);
117 |
118 | var stored = db.ExecuteScalar ("SELECT ModifiedTime FROM TestObj;");
119 | Assert.AreEqual (expected, stored);
120 | }
121 |
122 | class NullableDateObj
123 | {
124 | public DateTime? Time { get; set; }
125 | }
126 |
127 | [Test]
128 | public async Task LinqNullable ()
129 | {
130 | foreach (var option in new[] { true, false }) {
131 | var db = new SQLiteAsyncConnection (TestPath.GetTempFileName (), option);
132 | await db.CreateTableAsync ().ConfigureAwait (false);
133 |
134 | var epochTime = new DateTime (1970, 1, 1);
135 |
136 | await db.InsertAsync (new NullableDateObj { Time = epochTime });
137 | await db.InsertAsync (new NullableDateObj { Time = new DateTime (1980, 7, 23) });
138 | await db.InsertAsync (new NullableDateObj { Time = null });
139 | await db.InsertAsync (new NullableDateObj { Time = new DateTime (2019, 1, 23) });
140 |
141 | var res = await db.Table ().Where (x => x.Time == epochTime).ToListAsync ();
142 | Assert.AreEqual (1, res.Count);
143 |
144 | res = await db.Table ().Where (x => x.Time > epochTime).ToListAsync ();
145 | Assert.AreEqual (2, res.Count);
146 | }
147 | }
148 | }
149 | }
150 |
151 |
--------------------------------------------------------------------------------
/tests/SQLite.Tests/DbCommandTest.cs:
--------------------------------------------------------------------------------
1 | using System.Linq;
2 | using System.Text;
3 | using SQLite;
4 | using System.Threading.Tasks;
5 | using System.IO;
6 |
7 | #if NETFX_CORE
8 | using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
9 | using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
10 | using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
11 | using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
12 | #else
13 | using NUnit.Framework;
14 | #endif
15 |
16 | namespace SQLite.Tests
17 | {
18 | [TestFixture]
19 | public class DbCommandTest
20 | {
21 | [Test]
22 | public void QueryCommand()
23 | {
24 | var db = new SQLiteConnection (Path.GetTempFileName(), true);
25 | db.CreateTable();
26 | var b = new Product();
27 | db.Insert(b);
28 |
29 | var test = db.CreateCommand("select * from Product")
30 | .ExecuteDeferredQuery(new TableMapping(typeof(Product))).ToList();
31 |
32 |
33 | Assert.AreEqual (test.Count, 1);
34 | }
35 |
36 | #region Issue #1048
37 |
38 | [Test]
39 | public void QueryCommandCastToObject()
40 | {
41 | var db = new SQLiteConnection (Path.GetTempFileName(), true);
42 | db.CreateTable();
43 | var b = new Product();
44 | db.Insert(b);
45 |
46 | var test = db.CreateCommand("select * from Product")
47 | .ExecuteDeferredQuery