Repository: litedb-org/LiteDB
Branch: master
Commit: c9d78eb90085
Files: 418
Total size: 4.8 MB
Directory structure:
gitextract_mf5hhct9/
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ ├── feature_request.md
│ └── question.md
├── .gitignore
├── CODE_OF_CONDUCT.md
├── ConsoleApp1/
│ ├── ConsoleApp1.csproj
│ ├── Program.cs
│ └── Tools/
│ ├── Faker.Names.cs
│ └── Faker.cs
├── LICENSE
├── LiteDB/
│ ├── Client/
│ │ ├── Database/
│ │ │ ├── Collections/
│ │ │ │ ├── Aggregate.cs
│ │ │ │ ├── Delete.cs
│ │ │ │ ├── Find.cs
│ │ │ │ ├── Include.cs
│ │ │ │ ├── Index.cs
│ │ │ │ ├── Insert.cs
│ │ │ │ ├── Update.cs
│ │ │ │ └── Upsert.cs
│ │ │ ├── ILiteCollection.cs
│ │ │ ├── ILiteDatabase.cs
│ │ │ ├── ILiteQueryable.cs
│ │ │ ├── ILiteRepository.cs
│ │ │ ├── LiteCollection.cs
│ │ │ ├── LiteDatabase.cs
│ │ │ ├── LiteQueryable.cs
│ │ │ └── LiteRepository.cs
│ │ ├── Mapper/
│ │ │ ├── Attributes/
│ │ │ │ ├── BsonCtorAttribute.cs
│ │ │ │ ├── BsonFieldAttribute.cs
│ │ │ │ ├── BsonIdAttribute.cs
│ │ │ │ ├── BsonIgnoreAttribute.cs
│ │ │ │ └── BsonRefAttribute.cs
│ │ │ ├── BsonMapper.Deserialize.cs
│ │ │ ├── BsonMapper.GetEntityMapper.cs
│ │ │ ├── BsonMapper.Serialize.cs
│ │ │ ├── BsonMapper.cs
│ │ │ ├── EntityBuilder.cs
│ │ │ ├── EntityMapper.cs
│ │ │ ├── Linq/
│ │ │ │ ├── LinqExpressionVisitor.cs
│ │ │ │ ├── ParameterExpressionVisitor.cs
│ │ │ │ └── TypeResolver/
│ │ │ │ ├── BsonValueResolver.cs
│ │ │ │ ├── ConvertResolver.cs
│ │ │ │ ├── DateTimeResolver.cs
│ │ │ │ ├── EnumerableResolver.cs
│ │ │ │ ├── GuidResolver.cs
│ │ │ │ ├── ICollectionResolver.cs
│ │ │ │ ├── ITypeResolver.cs
│ │ │ │ ├── MathResolver.cs
│ │ │ │ ├── NullableResolver.cs
│ │ │ │ ├── NumberResolver.cs
│ │ │ │ ├── ObjectIdResolver.cs
│ │ │ │ ├── RegexResolver.cs
│ │ │ │ └── StringResolver.cs
│ │ │ ├── MemberMapper.cs
│ │ │ ├── Reflection/
│ │ │ │ ├── Reflection.Expression.cs
│ │ │ │ └── Reflection.cs
│ │ │ └── TypeNameBinder/
│ │ │ ├── DefaultTypeNameBinder.cs
│ │ │ └── ITypeNameBinder.cs
│ │ ├── Shared/
│ │ │ ├── SharedDataReader.cs
│ │ │ └── SharedEngine.cs
│ │ ├── SqlParser/
│ │ │ ├── Commands/
│ │ │ │ ├── Begin.cs
│ │ │ │ ├── Checkpoint.cs
│ │ │ │ ├── Commit.cs
│ │ │ │ ├── Create.cs
│ │ │ │ ├── Delete.cs
│ │ │ │ ├── Drop.cs
│ │ │ │ ├── Insert.cs
│ │ │ │ ├── ParseLists.cs
│ │ │ │ ├── Pragma.cs
│ │ │ │ ├── Rebuild.cs
│ │ │ │ ├── Rename.cs
│ │ │ │ ├── Rollback.cs
│ │ │ │ ├── Select.cs
│ │ │ │ └── Update.cs
│ │ │ └── SqlParser.cs
│ │ ├── Storage/
│ │ │ ├── ILiteStorage.cs
│ │ │ ├── LiteFileInfo.cs
│ │ │ ├── LiteFileStream.Read.cs
│ │ │ ├── LiteFileStream.Write.cs
│ │ │ ├── LiteFileStream.cs
│ │ │ └── LiteStorage.cs
│ │ └── Structures/
│ │ ├── ConnectionString.cs
│ │ ├── ConnectionType.cs
│ │ ├── Query.cs
│ │ └── QueryAny.cs
│ ├── Document/
│ │ ├── Bson/
│ │ │ └── BsonSerializer.cs
│ │ ├── BsonArray.cs
│ │ ├── BsonAutoId.cs
│ │ ├── BsonDocument.cs
│ │ ├── BsonType.cs
│ │ ├── BsonValue.cs
│ │ ├── DataReader/
│ │ │ ├── BsonDataReader.cs
│ │ │ ├── BsonDataReaderExtensions.cs
│ │ │ └── IBsonDataReader.cs
│ │ ├── Expression/
│ │ │ ├── BsonExpression.cs
│ │ │ ├── Methods/
│ │ │ │ ├── Aggregate.cs
│ │ │ │ ├── DataTypes.cs
│ │ │ │ ├── Date.cs
│ │ │ │ ├── Math.cs
│ │ │ │ ├── Misc.cs
│ │ │ │ └── String.cs
│ │ │ └── Parser/
│ │ │ ├── BsonExpressionAttributes.cs
│ │ │ ├── BsonExpressionFunctions.cs
│ │ │ ├── BsonExpressionOperators.cs
│ │ │ ├── BsonExpressionParser.cs
│ │ │ ├── BsonExpressionType.cs
│ │ │ ├── DocumentScope.cs
│ │ │ └── ExpressionContext.cs
│ │ ├── Json/
│ │ │ ├── JsonReader.cs
│ │ │ ├── JsonSerializer.cs
│ │ │ └── JsonWriter.cs
│ │ └── ObjectId.cs
│ ├── Engine/
│ │ ├── Disk/
│ │ │ ├── DiskReader.cs
│ │ │ ├── DiskService.cs
│ │ │ ├── MemoryCache.cs
│ │ │ ├── Serializer/
│ │ │ │ ├── BufferReader.cs
│ │ │ │ └── BufferWriter.cs
│ │ │ ├── StreamFactory/
│ │ │ │ ├── FileStreamFactory.cs
│ │ │ │ ├── IStreamFactory.cs
│ │ │ │ ├── StreamFactory.cs
│ │ │ │ └── StreamPool.cs
│ │ │ └── Streams/
│ │ │ ├── AesStream.cs
│ │ │ ├── ConcurrentStream.cs
│ │ │ └── TempStream.cs
│ │ ├── Engine/
│ │ │ ├── Collection.cs
│ │ │ ├── Delete.cs
│ │ │ ├── Index.cs
│ │ │ ├── Insert.cs
│ │ │ ├── Pragma.cs
│ │ │ ├── Query.cs
│ │ │ ├── Rebuild.cs
│ │ │ ├── Recovery.cs
│ │ │ ├── Sequence.cs
│ │ │ ├── SystemCollections.cs
│ │ │ ├── Transaction.cs
│ │ │ ├── Update.cs
│ │ │ ├── Upgrade.cs
│ │ │ └── Upsert.cs
│ │ ├── EnginePragmas.cs
│ │ ├── EngineSettings.cs
│ │ ├── EngineState.cs
│ │ ├── FileReader/
│ │ │ ├── FileReaderError.cs
│ │ │ ├── FileReaderV7.cs
│ │ │ ├── FileReaderV8.cs
│ │ │ ├── IFileReader.cs
│ │ │ ├── IndexInfo.cs
│ │ │ └── Legacy/
│ │ │ ├── AesEncryption.cs
│ │ │ ├── BsonReader.cs
│ │ │ └── ByteReader.cs
│ │ ├── ILiteEngine.cs
│ │ ├── LiteEngine.cs
│ │ ├── Pages/
│ │ │ ├── BasePage.cs
│ │ │ ├── CollectionPage.cs
│ │ │ ├── DataPage.cs
│ │ │ ├── HeaderPage.cs
│ │ │ └── IndexPage.cs
│ │ ├── Pragmas.cs
│ │ ├── Query/
│ │ │ ├── IndexQuery/
│ │ │ │ ├── Index.cs
│ │ │ │ ├── IndexAll.cs
│ │ │ │ ├── IndexEquals.cs
│ │ │ │ ├── IndexIn.cs
│ │ │ │ ├── IndexLike.cs
│ │ │ │ ├── IndexRange.cs
│ │ │ │ ├── IndexScan.cs
│ │ │ │ └── IndexVirtual.cs
│ │ │ ├── Lookup/
│ │ │ │ ├── DatafileLookup.cs
│ │ │ │ ├── IDocumentLookup.cs
│ │ │ │ └── IndexKeyLoader.cs
│ │ │ ├── Pipeline/
│ │ │ │ ├── BasePipe.cs
│ │ │ │ ├── DocumentCacheEnumerable.cs
│ │ │ │ ├── GroupByPipe.cs
│ │ │ │ └── QueryPipe.cs
│ │ │ ├── Query.cs
│ │ │ ├── QueryExecutor.cs
│ │ │ ├── QueryOptimization.cs
│ │ │ └── Structures/
│ │ │ ├── GroupBy.cs
│ │ │ ├── IndexCost.cs
│ │ │ ├── OrderBy.cs
│ │ │ ├── QueryPlan.cs
│ │ │ └── Select.cs
│ │ ├── Services/
│ │ │ ├── CollectionService.cs
│ │ │ ├── DataService.cs
│ │ │ ├── IndexService.cs
│ │ │ ├── LockService.cs
│ │ │ ├── RebuildService.cs
│ │ │ ├── SnapShot.cs
│ │ │ ├── TransactionMonitor.cs
│ │ │ ├── TransactionService.cs
│ │ │ └── WalIndexService.cs
│ │ ├── Sort/
│ │ │ ├── SortContainer.cs
│ │ │ ├── SortDisk.cs
│ │ │ └── SortService.cs
│ │ ├── Structures/
│ │ │ ├── CollectionIndex.cs
│ │ │ ├── CursorInfo.cs
│ │ │ ├── DataBlock.cs
│ │ │ ├── Done.cs
│ │ │ ├── FileOrigin.cs
│ │ │ ├── IndexNode.cs
│ │ │ ├── LockMode.cs
│ │ │ ├── PageAddress.cs
│ │ │ ├── PageBuffer.cs
│ │ │ ├── PagePosition.cs
│ │ │ ├── Pragma.cs
│ │ │ ├── RebuildOptions.cs
│ │ │ ├── TransactionPages.cs
│ │ │ └── TransactionState.cs
│ │ └── SystemCollections/
│ │ ├── Register.cs
│ │ ├── SysCols.cs
│ │ ├── SysDatabase.cs
│ │ ├── SysDump.cs
│ │ ├── SysFile.cs
│ │ ├── SysFileCsv.cs
│ │ ├── SysFileJson.cs
│ │ ├── SysIndexes.cs
│ │ ├── SysOpenCursors.cs
│ │ ├── SysPageList.cs
│ │ ├── SysQuery.cs
│ │ ├── SysSequences.cs
│ │ ├── SysSnapshots.cs
│ │ ├── SysTransactions.cs
│ │ └── SystemCollection.cs
│ ├── LiteDB.csproj
│ ├── LiteDB.snk
│ └── Utils/
│ ├── AsyncManualResetEvent.cs
│ ├── BufferSlice.cs
│ ├── Collation.cs
│ ├── Constants.cs
│ ├── Encoding.cs
│ ├── ExtendedLengthHelper.cs
│ ├── Extensions/
│ │ ├── BufferExtensions.cs
│ │ ├── BufferSliceExtensions.cs
│ │ ├── DateExtensions.cs
│ │ ├── DictionaryExtensions.cs
│ │ ├── EnumerableExtensions.cs
│ │ ├── ExpressionExtensions.cs
│ │ ├── HashSetExtensions.cs
│ │ ├── IOExceptionExtensions.cs
│ │ ├── LinqExtensions.cs
│ │ ├── StopWatchExtensions.cs
│ │ ├── StreamExtensions.cs
│ │ ├── StringExtensions.cs
│ │ └── TypeInfoExtensions.cs
│ ├── FileHelper.cs
│ ├── LCID.cs
│ ├── LiteException.cs
│ ├── MimeTypeConverter.cs
│ ├── Pool/
│ │ └── BucketHelper.cs
│ ├── Randomizer.cs
│ ├── Result.cs
│ ├── Tokenizer.cs
│ └── TryCatch.cs
├── LiteDB.Benchmarks/
│ ├── Benchmarks/
│ │ ├── BenchmarkBase.cs
│ │ ├── Constants.cs
│ │ ├── Deletion/
│ │ │ └── DeletionBenchmark.cs
│ │ ├── Generator/
│ │ │ └── FileMetaDataGenerationDatabaseBenchmark.cs
│ │ ├── Insertion/
│ │ │ ├── InsertionBasicBenchmark.cs
│ │ │ ├── InsertionIgnoreExpressionPropertyBenchmark.cs
│ │ │ └── InsertionInMemoryBenchmark.cs
│ │ └── Queries/
│ │ ├── QueryAllBenchmark.cs
│ │ ├── QueryCompoundIndexBenchmark.cs
│ │ ├── QueryCountBenchmark.cs
│ │ ├── QueryIgnoreExpressionPropertiesBenchmark.cs
│ │ ├── QueryMultipleParametersBenchmark.cs
│ │ ├── QuerySimpleIndexBenchmarks.cs
│ │ └── QueryWithDateTimeOffsetBenchmark.cs
│ ├── LiteDB.Benchmarks.csproj
│ ├── Models/
│ │ ├── FileMetaBase.cs
│ │ ├── FileMetaWithExclusion.cs
│ │ └── Generators/
│ │ └── FileMetaGenerator.cs
│ └── Program.cs
├── LiteDB.Shell/
│ ├── Commands/
│ │ ├── Close.cs
│ │ ├── Ed.cs
│ │ ├── Help.cs
│ │ ├── IShellCommand.cs
│ │ ├── Open.cs
│ │ ├── Pretty.cs
│ │ ├── Quit.cs
│ │ ├── Run.cs
│ │ ├── ShowCollections.cs
│ │ └── Version.cs
│ ├── LiteDB.Shell.csproj
│ ├── Program.cs
│ ├── Properties/
│ │ └── launchSettings.json
│ ├── Shell/
│ │ ├── Display.cs
│ │ ├── Env.cs
│ │ ├── InputCommand.cs
│ │ └── ShellProgram.cs
│ └── Utils/
│ ├── OptionSet.cs
│ ├── StringExtensions.cs
│ └── StringScanner.cs
├── LiteDB.Stress/
│ ├── Examples/
│ │ ├── test-01.xml
│ │ └── test-02.xml
│ ├── LiteDB.Stress.csproj
│ ├── Program.cs
│ ├── Properties/
│ │ └── launchSettings.json
│ └── Test/
│ ├── ITaskItem.cs
│ ├── InsertField.cs
│ ├── InsertTaskItem.cs
│ ├── SqlTaskItem.cs
│ ├── TestExecution.cs
│ ├── TestFile.cs
│ ├── ThreadInfo.cs
│ └── TimeSpanEx.cs
├── LiteDB.Tests/
│ ├── Database/
│ │ ├── AutoId_Tests.cs
│ │ ├── ConnectionString_Tests.cs
│ │ ├── Contains_Tests.cs
│ │ ├── Create_Database_Tests.cs
│ │ ├── Crud_Tests.cs
│ │ ├── Database_Pragmas_Tests.cs
│ │ ├── DbRef_Include_Tests.cs
│ │ ├── DbRef_Index_Tests.cs
│ │ ├── DbRef_Interface_Tests.cs
│ │ ├── DeleteMany_Tests.cs
│ │ ├── Delete_By_Name_Tests.cs
│ │ ├── DocumentUpgrade_Tests.cs
│ │ ├── Document_Size_Tests.cs
│ │ ├── FindAll_Tests.cs
│ │ ├── IndexMultiKeyLinq_Tests.cs
│ │ ├── IndexSortAndFilter_Tests.cs
│ │ ├── MultiKey_Mapper_Tests.cs
│ │ ├── NonIdPoco_Tests.cs
│ │ ├── PredicateBuilder_Tests.cs
│ │ ├── Query_Min_Max_Tests.cs
│ │ ├── Site_Tests.cs
│ │ ├── Snapshot_Upgrade_Tests.cs
│ │ ├── Storage_Tests.cs
│ │ ├── Upgrade_Tests.cs
│ │ └── Writing_While_Reading_Test.cs
│ ├── Document/
│ │ ├── Bson_Tests.cs
│ │ ├── Case_Insensitive_Tests.cs
│ │ ├── Decimal_Tests.cs
│ │ ├── Implicit_Tests.cs
│ │ ├── Json_Tests.cs
│ │ └── ObjectId_Tests.cs
│ ├── Engine/
│ │ ├── Collation_Tests.cs
│ │ ├── Create_Database_Tests.cs
│ │ ├── Crypto_Tests.cs
│ │ ├── DropCollection_Tests.cs
│ │ ├── Index_Tests.cs
│ │ ├── ParallelQuery_Tests.cs
│ │ ├── Rebuild_Crash_Tests.cs
│ │ ├── Rebuild_Tests.cs
│ │ ├── Recursion_Tests.cs
│ │ ├── Transactions_Tests.cs
│ │ ├── Update_Tests.cs
│ │ └── UserVersion_Tests.cs
│ ├── Expressions/
│ │ ├── Expressions_Exec_Tests.cs
│ │ └── Expressions_Tests.cs
│ ├── Internals/
│ │ ├── Aes_Tests.cs
│ │ ├── BasePage_Tests.cs
│ │ ├── BufferWriter_Tests.cs
│ │ ├── CacheAsync_Tests.cs
│ │ ├── Cache_Tests.cs
│ │ ├── Disk_Tests.cs
│ │ ├── Document_Tests.cs
│ │ ├── ExtendedLength_Tests.cs
│ │ ├── Extensions_Test.cs
│ │ ├── FreePage_Tests.cs
│ │ ├── FreeSlot_Tests.cs
│ │ ├── HeaderPage_Tests.cs
│ │ ├── Pragma_Tests.cs
│ │ └── Sort_Tests.cs
│ ├── Issues/
│ │ ├── Issue1585_Tests.cs
│ │ ├── Issue1651_Tests.cs
│ │ ├── Issue1695_Tests.cs
│ │ ├── Issue1701_Tests.cs
│ │ ├── Issue1838_Tests.cs
│ │ ├── Issue1860_Tests.cs
│ │ ├── Issue1865_Tests.cs
│ │ ├── Issue2112_Tests.cs
│ │ ├── Issue2127_Tests.cs
│ │ ├── Issue2129_Tests.cs
│ │ ├── Issue2265_Tests.cs
│ │ ├── Issue2298_Tests.cs
│ │ ├── Issue2417_Tests.cs
│ │ ├── Issue2458_Tests.cs
│ │ ├── Issue2471_Test.cs
│ │ ├── Issue2487_Tests.cs
│ │ ├── Issue2494_Tests.cs
│ │ ├── Issue2506_Tests.cs
│ │ ├── Issue2534_Tests.cs
│ │ ├── Issue2570_Tests.cs
│ │ └── Pull2468_Tests.cs
│ ├── LiteDB.Tests.csproj
│ ├── Mapper/
│ │ ├── CustomInterface_Tests.cs
│ │ ├── CustomMappingCtor_Tests.cs
│ │ ├── CustomMapping_Tests.cs
│ │ ├── DbRefAbstract_Tests.cs
│ │ ├── Dictionary_Tests.cs
│ │ ├── Enum_Tests.cs
│ │ ├── GenericMap_Tests.cs
│ │ ├── LinqBsonExpression_Tests.cs
│ │ ├── LinqEval_Tests.cs
│ │ ├── Mapper_Tests.cs
│ │ ├── Records_Tests.cs
│ │ └── StructField_Tests.cs
│ ├── Query/
│ │ ├── Aggregate_Tests.cs
│ │ ├── Data/
│ │ │ ├── PersonGroupByData.cs
│ │ │ └── PersonQueryData.cs
│ │ ├── GroupBy_Tests.cs
│ │ ├── Include_Tests.cs
│ │ ├── OrderBy_Tests.cs
│ │ ├── QueryApi_Tests.cs
│ │ ├── Select_Tests.cs
│ │ └── Where_Tests.cs
│ ├── Resources/
│ │ ├── person.json
│ │ └── zip.json
│ ├── Utils/
│ │ ├── AssertEx.cs
│ │ ├── DataGen.cs
│ │ ├── Faker.Names.cs
│ │ ├── Faker.cs
│ │ ├── LiteEngineExtensions.cs
│ │ ├── Models/
│ │ │ ├── Person.cs
│ │ │ └── Zip.cs
│ │ └── TempFile.cs
│ └── xunit.runner.json
├── LiteDB.sln
├── README.md
└── appveyor.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ''
---
**Version**
Which LiteDB version/OS/.NET framework version are you using. **(REQUIRED)**
**Describe the bug**
A clear and concise description of what the bug is.
**Code to Reproduce**
Write a small snippet to isolate your bug and could be possible to our team test. **(REQUIRED)**
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots/Stacktrace**
If applicable, add screenshots/stacktrace
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: "[SUGGESTION]"
labels: suggestion
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/ISSUE_TEMPLATE/question.md
================================================
---
name: Question
about: Write your question about LiteDB
title: "[QUESTION]"
labels: question
assignees: ''
---
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# MacOS files
.DS_Store
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
x64/
build/
bld/
[Bb]in/
[Oo]bj/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
#NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
.vs
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding addin-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# NuGet Packages Directory
packages/
## TODO: If the tool you use requires repositories.config uncomment the next line
#!packages/repositories.config
# Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
# This line needs to be after the ignore of the build folder (and the packages folder if the line above has been uncommented)
!packages/build/
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
/WebShell/Properties/PublishProfiles/*.pubxml
/WebShell/App_Data
# Nuget 3.0 Files
*.lock.json
*.nuget.props
*.nuget.targets
# Intellij
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/dictionaries
.idea/libraries
# User-specific configurations
.idea/libraries/
.idea/.name
.idea/compiler.xml
.idea/copyright/profiles_settings.xml
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/vcs.xml
.idea/jsLibraryMappings.xml
.idea/datasources.xml
.idea/dataSources.ids
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
### JetBrains+all Patch ###
# Ignores the whole idea folder
# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360
.idea/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
/LiteDB.BadJsonTest
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[Discord](https://discord.gg/u8seFBH9Zu).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
================================================
FILE: ConsoleApp1/ConsoleApp1.csproj
================================================
Exe
net8.0
enable
enable
================================================
FILE: ConsoleApp1/Program.cs
================================================
using LiteDB;
using LiteDB.Engine;
using System.Reflection.Emit;
using System.Reflection.PortableExecutable;
var password = "46jLz5QWd5fI3m4LiL2r";
var path = $"C:\\LiteDB\\Examples\\CrashDB_{DateTime.Now.Ticks}.db";
var settings = new EngineSettings
{
AutoRebuild = true,
Filename = path,
Password = password
};
var data = Enumerable.Range(1, 10_000).Select(i => new BsonDocument
{
["_id"] = i,
["name"] = Faker.Fullname(),
["age"] = Faker.Age(),
["created"] = Faker.Birthday(),
["lorem"] = Faker.Lorem(5, 25)
}).ToArray();
try
{
using (var db = new LiteEngine(settings))
{
#if DEBUG
db.SimulateDiskWriteFail = (page) =>
{
var p = new BasePage(page);
if (p.PageID == 248)
{
page.Write((uint)123123123, 8192-4);
}
};
#endif
db.Pragma("USER_VERSION", 123);
db.EnsureIndex("col1", "idx_age", "$.age", false);
db.Insert("col1", data, BsonAutoId.Int32);
db.Insert("col2", data, BsonAutoId.Int32);
var col1 = db.Query("col1", Query.All()).ToList().Count;
var col2 = db.Query("col2", Query.All()).ToList().Count;
Console.WriteLine("Inserted Col1: " + col1);
Console.WriteLine("Inserted Col2: " + col2);
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
Console.WriteLine("Recovering database...");
using (var db = new LiteEngine(settings))
{
var col1 = db.Query("col1", Query.All()).ToList().Count;
var col2 = db.Query("col2", Query.All()).ToList().Count;
Console.WriteLine($"Col1: {col1}");
Console.WriteLine($"Col2: {col2}");
var errors = new BsonArray(db.Query("_rebuild_errors", Query.All()).ToList()).ToString();
Console.WriteLine("Errors: " + errors);
}
/*
var errors = new List();
var fr = new FileReaderV8(settings, errors);
fr.Open();
var pragmas = fr.GetPragmas();
var cols = fr.GetCollections().ToArray();
var indexes = fr.GetIndexes(cols[0]);
var docs1 = fr.GetDocuments("col1").ToArray();
var docs2 = fr.GetDocuments("col2").ToArray();
Console.WriteLine("Recovered Col1: " + docs1.Length);
Console.WriteLine("Recovered Col2: " + docs2.Length);
Console.WriteLine("# Errors: ");
errors.ForEach(x => Console.WriteLine($"PageID: {x.PageID}/{x.Origin}/#{x.Position}[{x.Collection}]: " + x.Message));
*/
Console.WriteLine("\n\nEnd.");
Console.ReadKey();
================================================
FILE: ConsoleApp1/Tools/Faker.Names.cs
================================================
internal static partial class Faker
{
private static string[] _maleNames =
{
"Adeildo", "Adailton", "Abel", "Adelar", "Adelino", "Abilio", "Adilson", "Adenildo", "Adenir", "Adenilson", "Adenilton", "Adevaldo", "Abner", "Adir", "Adair", "Abimael", "Abraao", "Adrian", "Adson", "Acacio", "Adelso", "Adalto", "Adalberto", "Adolfo", "Adelmo", "Adao", "Adauto", "Ademar", "Ademilson", "Ademilton", "Ademir", "Admilson", "Adonias", "Adriano", "Adriel", "Aecio", "Eder", "Edio", "Edson", "Elcio", "Aldo", "Euler", "Eli", "Helio", "Luiz", "Alison", "Alisson", "Eliton", "Elmo", "Elso", "Elson", "Ailton", "Eron", "Ezio", "Everton", "Afonso", "Afranio", "Agenor", "Aguinaldo", "Agnaldo", "Agostinho", "Iago", "Alan", "Elder", "Airton", "Laecio", "Eliel", "Elielson", "Laercio", "Laerte", "Elielton", "Elian", "Elias", "Alaor", "Aldair", "Aldeci", "Aldir", "Aldemar", "Aldemir", "Aldenir", "Alberi", "Alberico", "Albert", "Albertino", "Alberto", "Albino", "Alcir", "Alceu", "Alcides", "Alcimar", "Alcindo", "Alcino", "Leandro", "Alexandre", "Alessandro", "Alecsandro", "Alef", "Elimar", "Elenildo", "Alencar", "Lenilson", "Elenilton", "Heleno", "Leomar", "Leonidas", "Leoni", "Alesandro", "Alexander", "Alexsandro", "Levi", "Alex", "Alexsander", "Alfredo", "Algusto", "Eliandro", "Lidio", "Alicio", "Eliezer", "Alife", "Olimpio", "Elinaldo", "Lindomar", "Lino", "Eliomar", "Alipio", "Alirio", "Elisandro", "Aluisio", "Elismar", "Elivaldo", "Elivan", "Elivelton", "Eliseu", "Allan", "Allison", "Almir", "Almiro", "Eloi", "Aloisio", "Alonso", "Altair", "Altamir", "Altamiro", "Altino", "Luan", "Luciano", "Lucio", "Alvaro", "Elves", "Alvino", "Elvio", "Elvis", "Amadeu", "Amado", "Amilton", "Amarildo", "Amaro", "Amauri", "Americo", "Anilson", "Anilton", "Anildo", "Ananias", "Anastacio", "Ancelmo", "Anderson", "Andeson", "Andre", "Andrei", "Andrew", "Anesio", "Angelo", "Anibal", "Anisio", "Antoni", "Anselmo", "Antenor", "Antonio", "Antoniel", "Antonino", "Aparecido", "Aquiles", "Ariel", "Aroldo", "Arilson", "Arlei", "Argemiro", "Ari", "Ariovaldo", "Aristeu", "Aristides", "Arivaldo", "Arlindo", "Armando", "Armindo", "Arnaldo", "Arno", "Artur", "Assis", "Ataide", "Atila", "Augusto", "Augustinho", "Aurelio", "Avelino", "Baltazar", "Bartolomeu", "Dejair", "Dalton", "Dalmir", "Belmiro", "Dilson", "Denilson", "Dener", "Benedito", "Denir", "Benicio", "Denis", "Denison", "Denivaldo", "Benjamin", "Bento", "Derli", "Bernado", "Bernardo", "Braian", "Breno", "Diomar", "Dione", "Bryan", "Braulio", "Braz", "Brendo", "Bruno", "Cesar", "Caetano", "Kaue", "Kaik", "Kaike", "Kayky", "Celson", "Caio", "Caique", "Cairo", "Cleber", "Celio", "Cleison", "Cleiton", "Kelvin", "Camilo", "Candido", "Carlito", "Carlo", "Carlos", "Cassiano", "Cassio", "Caua", "Kauan", "Clesio", "Cleito", "Celso", "Charles", "Christian", "Cicero", "Ciro", "Clebson", "Cleilton", "Cleilson", "Clayton", "Claudir", "Claudio", "Claudecir", "Claudemir", "Claudenir", "Claudinei", "Claudino", "Claudiomar", "Claudiomiro", "Claudionor", "Cleberson", "Clecio", "Cleidson", "Clemente", "Cleomar", "Cleverson", "Cleverton", "Clodoaldo", "Cloves", "Clovis", "Cosme", "Cosmo", "Cristian", "Cristiano", "Crispim", "Cristofer", "Cristovao", "Custodio", "Decio", "Delcio", "Delio", "Dalmo", "Damiao", "Daniel", "Danilo", "Darci", "Darlei", "Dario", "Darlan", "Davi", "David", "Davison", "Dijalma", "Deivid", "Deivide", "Deivison", "Demetrio", "Deusdete", "Deusimar", "Devair", "Devanir", "Devid", "Diego", "Diogo", "Dionata", "Dionatan", "Diones", "Dionei", "Douglas", "Dimas", "Diogenes", "Dionisio", "Dirceu", "Dirlei", "Divino", "Djalma", "Doglas", "Domingo", "Domingos", "Donato", "Donizete", "Dorival", "Durval", "Edenilson", "Ederson", "Hebert", "Edison", "Hector", "Edilson", "Edilton", "Edcarlos", "Edemar", "Edesio", "Edevaldo", "Edgar", "Edicarlos", "Edigar", "Edimar", "Edimilson", "Edinilson", "Edinaldo", "Edinei", "Edivaldo", "Edivan", "Edmar", "Edmilson", "Edmundo", "Ednilson", "Ednaldo", "Ednei", "Edno", "Eduardo", "Edvaldo", "Edvan", "Egidio", "Igor", "Inaldo", "Heitor", "Hilario", "Leo", "Leonildo", "Leonardo", "Leonel", "Olivio", "Emanuel", "Emerson", "Emidio", "Emilio", "Enilson", "Enio", "Enivaldo", "Enzo", "Enoque", "Henry", "Henrique", "Eraldo", "Erasmo", "Herbert", "Ercilio", "Hercules", "Eric", "Erike", "Erick", "Erico", "Ericson", "Erli", "Erinaldo", "Erique", "Erison", "Erisvaldo", "Erivaldo", "Erivelton", "Erivan", "Hermes", "Herminio", "Ernandes", "Ernando", "Ernane", "Ernani", "Ernesto", "Eronildo", "Esdras", "Ezequias", "Ezequiel", "Esmael", "Esmeraldo", "Espedito", "Estevan", "Estevao", "Eudes", "Euclides", "Eugenio", "Ulisses", "Eurico", "Euripedes", "Euzebio", "Evaldo", "Evanildo", "Evandro", "Evangelista", "Evaristo", "Evilasio", "Everaldo", "Everson", "Ewerton", "Expedito", "Fabiano", "Fabio", "Fabricio", "Fagner", "Fausto", "Fco", "Feliciano", "Felipe", "Filipi", "Felix", "Fellipe", "Fernando", "Francisco", "Firmino", "Flaviano", "Flavio", "Floriano", "Florisvaldo", "Fracisco", "Frank", "Franciel", "Franklin", "Francico", "Francimar", "Francinaldo", "Francinei", "Francis", "Franciso", "Francivaldo", "Franisco", "Franscisco", "Fransisco", "Fred", "Frederico", "Fredson", "Jadir", "Gabriel", "Jader", "Jadiel", "Joel", "Jair", "Jairo", "Jaison", "Gilberto", "Gileno", "Juliano", "Julho", "Gilvan", "Jamil", "Jandir", "Jarbas", "Jardel", "Gaspar", "Gleison", "Gleisson", "Jean", "Jeanderson", "Jedson", "Jeferson", "Jefersson", "Jefeson", "Gildo", "Gilmar", "Gilso", "Gilson", "Jailton", "Geison", "Julio", "Genildo", "Genilson", "Genesio", "Genival", "Genivaldo", "Gentil", "George", "Jeova", "Geovan", "Geovane", "Geovani", "Geraldo", "Jeremias", "Jerferson", "Jerfeson", "Jerry", "Germano", "Geronimo", "Gerson", "Gervasio", "Jesiel", "Jesse", "Jesuino", "Jesus", "Getulio", "Guilherme", "Gustavo", "Gian", "Guido", "Gildasio", "Julian", "Giovane", "Giovani", "Givaldo", "Givanildo", "Gledson", "Glauber", "Glaucio", "Glauco", "Gleidson", "Julimar", "Jobson", "Goncalo", "Jorge", "Gregori", "Gregorio", "Gutemberg", "Ian", "Icaro", "Iran", "Iranildo", "Ismael", "Israel", "Italo", "Itamar", "Iure", "Yuri", "Ivaldo", "Ivan", "Ivair", "Ivo", "Odilon", "Omar", "Homero", "Onofre", "Horacio", "Orivaldo", "Orlando", "Orlei", "Oseias", "Osmar", "Otavio", "Oziel", "Osorio", "Uanderson", "Ubirajara", "Ubiratan", "Hudson", "Ueslei", "Hugo", "Humberto", "Lauro", "Inacio", "Irineu", "Isac", "Isael", "Isaias", "Isaque", "Izaquiel", "Ismar", "Ivanildo", "Ivanilson", "Ivonaldo", "Jadson", "Jaci", "Jacinto", "Jackson", "Jaco", "Jacson", "Jadilson", "Jaime", "Jamerson", "James", "Janiel", "Janilson", "Janderson", "Janio", "Januario", "Jason", "Joao", "John", "Jonas", "Jonata", "Jonatan", "Jonatas", "Jhone", "Jones", "Jhony", "Jonilson", "Jordan", "Jose", "Juan", "Junior", "Joab", "Joabe", "Joacir", "Joaquim", "Joares", "Jocelio", "Jocimar", "Josiel", "Josafa", "Joseildo", "Joseilton", "Josimar", "Joselio", "Joselito", "Josemar", "Josemir", "Josenildo", "Josenilson", "Josenilton", "Josevaldo", "Josias", "Josinaldo", "Josival", "Josivaldo", "Josivan", "Josue", "Juarez", "Jucelino", "Jucelio", "Jucimar", "Jurandir", "Juscelino", "Justino", "Juvenal", "Kennedy", "Kevin", "Keven", "Lazaro", "Laudelino", "Lauri", "Laurindo", "Leonan", "Leopoldo", "Lincon", "Lorran", "Lorenco", "Lorenzo", "Lorival", "Lorivaldo", "Lourenco", "Lourival", "Luca", "Lucas", "Lucca", "Lucinei", "Lucivaldo", "Madson", "Maciel", "Macelo", "Maxuel", "Macio", "Mailson", "Milton", "Magno", "Maik", "Maike", "Maico", "Maicon", "Manoel", "Marciel", "Marcelino", "Marcelo", "Marcilio", "Marciano", "Marcio", "Marco", "Marcondes", "Marcone", "Marconi", "Marcos", "Marcus", "Mariano", "Marlon", "Marinaldo", "Marino", "Mario", "Marivaldo", "Martin", "Martinho", "Martins", "Mateus", "Matias", "Maurilio", "Mauri", "Mauricio", "Mauro", "Max", "Maxsuel", "Maxwell", "Messias", "Micael", "Michel", "Miguel", "Miqueias", "Misael", "Moacir", "Moiseis", "Moises", "Murilo", "Nadson", "Noel", "Nildo", "Nelio", "Nelson", "Nilton", "Nilo", "Nelso", "Narciso", "Nazareno", "Natal", "Natalicio", "Natalino", "Natan", "Natanael", "Nei", "Nivaldo", "Neri", "Nestor", "Newton", "Nicolas", "Nicolau", "Noe", "Nonato", "Norberto", "Odair", "Olavo", "Oliveira", "Oscar", "Oseas", "Osias", "Osni", "Osvaldo", "Oswaldo", "Otacilio", "Otaviano", "Otoniel", "Pablo", "Paulino", "Paulo", "Patrik", "Patricio", "Patrick", "Pedro", "Peterson", "Pierre", "Pietro", "Plinio", "Raul", "Railson", "Railton", "Rene", "Rafael", "Rai", "Raian", "Railan", "Rildo", "Rian", "Raimundo", "Ralf", "Ramiro", "Ramon", "Rangel", "Reginaldo", "Regis", "Rui", "Reinaldo", "Reinan", "Rivaldo", "Renildo", "Renilson", "Renan", "Renato", "Robson", "Rodnei", "Rodolfo", "Rodrigo", "Roger", "Romulo", "Ronan", "Roni", "Ruan", "Ribamar", "Ricardo", "Richard", "Riquelme", "Roberio", "Robert", "Roberto", "Roberval", "Robison", "Rodinei", "Rogerio", "Romildo", "Romilson", "Romario", "Romero", "Romeu", "Roniel", "Ronaldo", "Ronilson", "Ronald", "Rone", "Ronivon", "Ronivaldo", "Roque", "Rosalino", "Rosalvo", "Rosenildo", "Rosinaldo", "Rosivaldo", "Rubem", "Rubens", "Rudimar", "Rudinei", "Sabino", "Sadi", "Saul", "Saulo", "Saimon", "Salatiel", "Selio", "Salomao", "Salvador", "Silvino", "Silvio", "Samuel", "Samir", "Sandoval", "Sandro", "Santiago", "Santo", "Santos", "Savio", "Sebastiao", "Zenildo", "Sergio", "Severino", "Sidinei", "Sidnei", "Silas", "Silvano", "Silverio", "Silvestre", "Simao", "Sinesio", "Sinval", "Sivaldo", "Tadeu", "Tiago", "Tales", "Talis", "Talisson", "Taylor", "Tainan", "Tulio", "Talison", "Talles", "Telmo", "Tarcisio", "Tauan", "Theo", "Teodoro", "Tomas", "Toni", "Vilson", "Vagner", "Valber", "Valdo", "Valdemir", "Valdenir", "Valderi", "Valdir", "Valcir", "Valdeci", "Valdeli", "Valdemar", "Valdemiro", "Valdenor", "Valdevino", "Valdinei", "Valdivino", "Valdomiro", "Valentim", "Valerio", "Valmir", "Valmor", "Volnei", "Valter", "Vanilson", "Vanildo", "Vander", "Vandir", "Vanderlan", "Vanderlei", "Vanderson", "Vando", "Venancio", "Vicente", "Victor", "Vinicio", "Vinicios", "Vinicius", "Virgilio", "Vital", "Vitor", "Vitorio", "Vivaldo", "Vladimir", "Washington", "Wagner", "Wilson", "Wilton", "Walace", "Wilhan", "Welder", "Waldir", "Waldemar", "Welington", "Welinton", "Walison", "Walisson", "Weliton", "Wilker", "Wallace", "Willan", "Willy", "Wellington", "Wallison", "Welliton", "Walmir", "Walter", "Wander", "Wanderlei", "Wanderson", "Warley", "Weber", "Wederson", "Wedson", "Weligton", "Willian", "Welligton", "Wellinton", "Wemerson", "Wendel", "Wender", "Wendell", "Wenderson", "Wesley", "Weslen", "Weslley", "Weverton", "Wilian", "Willians", "Zacarias", "Zaqueu"
};
private static string[] _femaleNames =
{
"Aline", "Adelia", "Adelina", "Adelma", "Abigail", "Adalgisa", "Adelaide", "Adria", "Adriana", "Adriane", "Adriele", "Adrieli", "Edi", "Edna", "Eliane", "Elen", "Lia", "Eliana", "Elida", "Elita", "Ilma", "Erica", "Agata", "Agda", "Agnes", "Aida", "Aide", "Aila", "Alana", "Iolanda", "Elane", "Alani", "Ilka", "Ilda", "Ildete", "Leda", "Lene", "Leila", "Lili", "Elza", "Iana", "Iane", "Iara", "Laci", "Ladir", "Laiane", "Alaide", "Eliani", "Laisa", "Laise", "Lara", "Lauane", "Albertina", "Albina", "Alcilene", "Alcione", "Aldenora", "Lea", "Leandra", "Alessandra", "Leci", "Leia", "Leide", "Lidiana", "Lidiane", "Lina", "Luiza", "Luize", "Lilia", "Liliane", "Helena", "Leni", "Elenice", "Lenilda", "Lenira", "Lenise", "Elenita", "Alesandra", "Alexandrina", "Alexia", "Leticia", "Alexsandra", "Olga", "Liandra", "Laira", "Lidia", "Alice", "Alicia", "Eliene", "Eliete", "Ligia", "Lilian", "Olinda", "Alini", "Elisandra", "Elizane", "Elisangela", "Elizete", "Elisia", "Elissandra", "Elizabete", "Lisiane", "Leilane", "Ellen", "Almira", "Almerinda", "Eloa", "Heloisa", "Eloise", "Lorrane", "Alzenir", "Alzira", "Luana", "Luane", "Lucelia", "Luci", "Lucilene", "Lucimar", "Luma", "Luzia", "Luzinete", "Alvina", "Elvira", "Amelia", "Amanda", "Amara", "Ana", "Ane", "Anieli", "Analia", "Anelise", "Anair", "Analice", "Ananda", "Andrelina", "Andrea", "Andrieli", "Andreia", "Andriele", "Andreza", "Andressa", "Anny", "Anesia", "Angela", "Angelica", "Angelina", "Angelita", "Anisia", "Anita", "Antonia", "Antonieta", "Aparecida", "Araci", "Ariana", "Ariane", "Ariele", "Arlene", "Arlete", "Arlinda", "Arminda", "Augusta", "Aurea", "Aurilene", "Aurelina", "Aurora", "Avani", "Barbara", "Beatriz", "Delia", "Deli", "Deliane", "Deolinda", "Dalila", "Dilma", "Delmira", "Dilza", "Benedita", "Denise", "Berenice", "Bernadete", "Betania", "Bianca", "Brenda", "Diana", "Diane", "Dina", "Diva", "Brena", "Bruna", "Cacilda", "Keila", "Kelen", "Kaline", "Kailane", "Kele", "Cilene", "Kiara", "Cleide", "Keli", "Keliane", "Kelly", "Celina", "Celita", "Celma", "Camila", "Camile", "Camili", "Camilla", "Camille", "Camilly", "Candida", "Karen", "Carol", "Carla", "Karina", "Karine", "Carolaine", "Carolina", "Caroline", "Carmelita", "Carmem", "Cassia", "Cassiana", "Cassiane", "Catarina", "Katia", "Katiane", "Katiana", "Kauana", "Kauane", "Kauany", "Cecilia", "Celia", "Cleane", "Cleci", "Cleia", "Celeste", "Cleusa", "Clelia", "Kenia", "Kesia", "Kessia", "Chaiane", "Sheila", "Charlene", "Shirley", "Shirlene", "Cibele", "Cicera", "Clea", "Cintia", "Cirlei", "Cirlene", "Clara", "Clarice", "Clarissa", "Clarisse", "Claudete", "Claudia", "Claudenice", "Claudiana", "Claudiane", "Claudineia", "Cleidiane", "Clemilda", "Cleonice", "Cleunice", "Clotilde", "Conceicao", "Corina", "Cosma", "Cremilda", "Creuza", "Cristiane", "Crislaine", "Crislane", "Cristiana", "Cristina", "Cristine", "Dagmar", "Daiana", "Daiane", "Dara", "Daiani", "Dulce", "Dalva", "Dayse", "Delci", "Dulcineia", "Dalvina", "Damaris", "Damiana", "Daniela", "Dandara", "Danielle", "Danielly", "Daniele", "Danieli", "Daniella", "Danubia", "Darlene", "Debora", "Deise", "Deisiane", "Dejanira", "Deusa", "Dienifer", "Dinalva", "Dirce", "Divina", "Dolores", "Domingas", "Dora", "Doraci", "Doralice", "Durvalina", "Ediane", "Edilma", "Edilza", "Edila", "Edilaine", "Edilane", "Edilene", "Edileuza", "Edite", "Edina", "Edinalva", "Edineia", "Edineide", "Edith", "Edivania", "Edjane", "Ednalva", "Edneia", "Eduarda", "Edvania", "Efigenia", "Ida", "Ide", "Isa", "Iva", "Leonice", "Leonilda", "Leonor", "Leonora", "Eleuza", "Liduina", "Liliana", "Lindalva", "Lindinalva", "Elizabeth", "Elizabeti", "Elisama", "Elivania", "Livia", "Lorraine", "Luara", "Lucia", "Luciana", "Luciane", "Luciene", "Luziane", "Luzimar", "Emanuela", "Emanuele", "Emanuelle", "Emanuelly", "Emanueli", "Emile", "Emily", "Emilly", "Emilia", "Enilda", "Enedina", "Eni", "Ercilia", "Erminia", "Ernestina", "Erondina", "Esmeralda", "Estefane", "Estefani", "Estefania", "Estela", "Estelita", "Ester", "Etelvina", "Eugenia", "Eunice", "Eurides", "Eva", "Eveline", "Evanir", "Evanilda", "Evely", "Evelin", "Evellyn", "Expedita", "Fabia", "Fabiana", "Fabiane", "Fabiola", "Fabricia", "Fatima", "Filomena", "Fernanda", "Flavia", "Flaviana", "Flaviane", "Flora", "Florinda", "Franciele", "Francilene", "Francieli", "Franciane", "Francine", "Francineide", "Francinete", "Francisca", "Gabriela", "Gabriele", "Gabrieli", "Gabriella", "Gabrielle", "Gabrielly", "Jaiane", "Gilda", "Juliana", "Gilvania", "Janete", "Gardenia", "Jeane", "Juli", "Julha", "Juliane", "Gilza", "Geisa", "Geise", "Gisela", "Gislaine", "Gislane", "Gisele", "Gislene", "Giseli", "Geisiane", "Giselle", "Julia", "Gleice", "Juliene", "Genilda", "Geneci", "Jenefer", "Geni", "Jenifer", "Georgia", "Georgina", "Geovana", "Geralda", "Geraldina", "Gerlane", "Gerusa", "Jesica", "Jesuina", "Gessi", "Jessica", "Giovana", "Jaine", "Gildete", "Gleide", "Guilhermina", "Gilmara", "Gilvanete", "Guiomar", "Girlene", "Giselda", "Giselia", "Glaucia", "Gleiciane", "Glenda", "Gloria", "Jordana", "Gorete", "Graca", "Graciele", "Gracilene", "Graciela", "Graziela", "Graziele", "Grazieli", "Greice", "Ianca", "Yasmin", "Ieda", "Ingred", "Ingrid", "Ingride", "Ingridi", "Ione", "Irene", "Iris", "Irma", "Isabela", "Isadora", "Isis", "Ivana", "Ivone", "Odete", "Ondina", "Hortencia", "Hosana", "Osmarina", "Otilia", "Idalina", "Laura", "Inacia", "Ines", "Iracema", "Iraci", "Iracilda", "Iria", "Irani", "Iraneide", "Ireni", "Isabel", "Isabele", "Isabeli", "Isabella", "Isabelle", "Isabelly", "Izilda", "Isolina", "Isamara", "Isaura", "Ivete", "Ivanilda", "Ivani", "Ivanice", "Ivaneide", "Ivanilde", "Ivanete", "Ivania", "Ivoni", "Ivoneide", "Ivonete", "Jakeline", "Jaciane", "Jaciara", "Jacilene", "Jacinta", "Jacira", "Jackeline", "Jacqueline", "Jamile", "Jamili", "Jane", "Janiele", "Janaina", "Jandira", "Jani", "Janine", "Janice", "Jaqueline", "Joana", "Joice", "Josi", "Joaquina", "Joceli", "Jocilene", "Jocelia", "Joise", "Juliete", "Jordania", "Jorgina", "Josilda", "Josiane", "Joselia", "Joseane", "Joselma", "Josefa", "Josefina", "Josina", "Joselaine", "Josiele", "Joseli", "Josilene", "Joselina", "Joselita", "Josenilda", "Josenir", "Josiene", "Josimara", "Josineide", "Josinete", "Jovelina", "Juceli", "Jucileide", "Jucilene", "Jucelia", "Juciara", "Jucimara", "Judite", "Julieta", "Junia", "Juraci", "Jurema", "Jussara", "Justina", "Kellen", "Kemili", "Ketlen", "Ketley", "Ketlin", "Larisa", "Larissa", "Lazara", "Laudiceia", "Laurinda", "Laurita", "Lavinia", "Leontina", "Lorrana", "Lindaura", "Lorrany", "Lorena", "Lurdes", "Luciele", "Lucileide", "Lucila", "Lucicleide", "Lucidalva", "Lucileia", "Lucimara", "Lucimeire", "Lucinda", "Lucineia", "Lucineide", "Lucinete", "Lucivania", "Ludimila", "Ludmila", "Luna", "Luzineide", "Maria", "Madalena", "Maila", "Milene", "Mercia", "Magali", "Magda", "Magna", "Magnolia", "Mara", "Maiara", "Maira", "Maiana", "Maiane", "Milena", "Maisa", "Malvina", "Manuela", "Manuele", "Marilda", "Marilza", "Mariana", "Mariane", "Marli", "Marlise", "Marluce", "Marlucia", "Marcelina", "Marcela", "Marcele", "Marceli", "Marcilene", "Marcilia", "Marcia", "Marciana", "Marlene", "Marluci", "Mari", "Margareth", "Margarete", "Margarida", "Mariangela", "Maricelia", "Marla", "Mariele", "Marilena", "Marilia", "Marieta", "Marina", "Marileia", "Marileide", "Marlete", "Marinalva", "Marineide", "Marines", "Marinete", "Marisa", "Marise", "Marizete", "Maristela", "Marivalda", "Marta", "Martinha", "Matilde", "Maura", "Maurina", "Meire", "Mirele", "Miria", "Mirian", "Mireli", "Melissa", "Mercedes", "Micaela", "Micaele", "Micaeli", "Michele", "Michelle", "Michelli", "Micheli", "Mirela", "Mirella", "Mirtes", "Monalisa", "Monica", "Monique", "Morgana", "Nara", "Nadir", "Nadia", "Nadja", "Neila", "Neli", "Noelia", "Nelma", "Nilza", "Nagila", "Naiara", "Nair", "Naiana", "Naiane", "Nilce", "Nilda", "Nilde", "Nilva", "Naira", "Nelci", "Nelsi", "Nanci", "Nazare", "Natasha", "Natiele", "Natali", "Natalia", "Natalie", "Natalina", "Neide", "Nina", "Neiva", "Nivia", "Nilzete", "Neusa", "Nicole", "Nicoli", "Nicolly", "Nilceia", "Nivea", "Noemi", "Noemia", "Norma", "Nubia", "Odilia", "Odila", "Osvaldina", "Paula", "Poliane", "Palmira", "Paloma", "Pamela", "Patricia", "Poliana", "Paulina", "Pedrina", "Perla", "Pietra", "Pricila", "Priscila", "Priscilla", "Queila", "Quesia", "Quiteria", "Rachel", "Rafaela", "Rafaele", "Rafaella", "Raiane", "Raissa", "Raiana", "Raiani", "Raila", "Railane", "Railda", "Raimunda", "Riana", "Rainara", "Raine", "Raisa", "Raniele", "Raquel", "Rebeca", "Rejane", "Regiane", "Regina", "Renilda", "Renata", "Reni", "Rubia", "Rute", "Rita", "Roberta", "Rogeria", "Romilda", "Rosa", "Roseli", "Rosilda", "Rosiane", "Rosilane", "Rosileide", "Rosilene", "Rosalia", "Rosalina", "Rosana", "Rosane", "Rosani", "Rosangela", "Rosania", "Rosaria", "Rose", "Roseane", "Rosimeire", "Roselaine", "Rosemar", "Rosemary", "Rosemeire", "Rosemere", "Rosemeri", "Rosenilda", "Roseni", "Rosi", "Rosicleia", "Rosicleide", "Rosimar", "Rosimari", "Rosimere", "Rosimeri", "Rosinei", "Rosineia", "Rosineide", "Rosinete", "Ruth", "Ruti", "Sara", "Sabrina", "Suelen", "Sueli", "Zila", "Suiane", "Zaira", "Zuleide", "Silene", "Salete", "Zelia", "Suelaine", "Zelina", "Zelita", "Selma", "Zulmira", "Silva", "Silvana", "Silvani", "Silvania", "Silvia", "Silvina", "Samia", "Samila", "Samanta", "Samara", "Samira", "Sandy", "Sandra", "Santa", "Santina", "Sebastiana", "Zilda", "Suellen", "Silmara", "Zenaide", "Zeneide", "Zeni", "Zenilda", "Severina", "Sibele", "Sidneia", "Sulamita", "Solange", "Silvane", "Simone", "Simoni", "Sinara", "Sintia", "Sirlei", "Sirlene", "Socorro", "Sofia", "Sonia", "Soraia", "Zoraide", "Stefane", "Stefani", "Stephanie", "Stela", "Zuleica", "Suzana", "Suzane", "Suzete", "Suzi", "Tabata", "Taciana", "Taciane", "Taiana", "Taiane", "Taila", "Taina", "Tainara", "Tais", "Taisa", "Taise", "Tailane", "Talia", "Taline", "Telma", "Taine", "Taissa", "Talita", "Tamara", "Tamires", "Tamiris", "Tania", "Tassia", "Tatiana", "Tatiane", "Tatiele", "Tauane", "Tauani", "Tereza", "Terezinha", "Tifani", "Tuane", "Tuani", "Vilma", "Valda", "Valdenice", "Valdilene", "Valdina", "Valdira", "Valdelice", "Valdete", "Valdineia", "Valdirene", "Valentina", "Valeria", "Valesca", "Valmira", "Valquiria", "Vanilda", "Vania", "Vanda", "Vanderleia", "Vani", "Vaneide", "Vanesa", "Vanessa", "Vanusa", "Vanuzia", "Vera", "Veridiana", "Veronica", "Vicentina", "Victoria", "Virginia", "Vitalina", "Vitoria", "Vivian", "Viviane", "Wilma", "Wanda", "Wanessa", "Zumira"
};
private static string[] _surNames =
{
"Smith", "Johnson", "Jones", "Williams", "Brown", "Lee", "Khan", "Singh", "Kumar", "Miller", "Davis", "Wilson", "Taylor", "Thomas", "Garcia", "Anderson", "Sharma", "Martin", "Rodriguez", "Ali", "White", "Jackson", "Thompson", "Moore", "Ahmed", "Martinez", "Lopez", "Harris", "Patel", "King", "Walker", "Hernandez", "Clark", "Lewis", "Robinson", "Young", "Gonzalez", "Hall", "Wright", "Scott", "Perez", "Green", "Allen", "Tan", "Shah", "Roberts", "Adams", "Nguyen", "James", "Hill", "Baker", "Campbell", "Wong", "Sanchez", "Evans", "Cruz", "Gupta", "Chan", "Mitchell", "Carter", "Reyes", "Nelson", "Edwards", "Rivera", "Parker", "Turner", "Phillips", "Lim", "Murphy", "Stewart", "Collins", "Jain", "Torres", "Morris", "Santos", "Kelly", "Morgan", "Cooper", "Ramirez", "Flores", "Bell", "Cook", "Wood", "Rogers", "Ramos", "Watson", "Ward", "Diaz", "Bailey", "Rose", "Ahmad", "Hughes", "Bennett", "Love", "Kim", "Mohamed", "Gomez", "Mendoza", "Gray", "Richardson", "Ross", "Cox", "Chen", "Reed", "Brooks", "Peterson", "Howard", "Price", "Gonzales", "Ng", "Fernandez", "Russell", "Foster", "Murray", "Long", "Black", "Graham", "Jenkins", "Harrison", "Alexander", "Fisher", "Morales", "Ryan", "Henderson", "Stevens", "Powell", "Butler", "Hamilton", "Marshall", "Perry", "Jordan", "George", "Barnes", "Cole", "Kennedy", "West", "Simpson", "Mcdonald", "Sullivan", "Reynolds", "Ortiz", "Shaw", "Hassan", "Castillo", "Ellis", "Myers", "Wallace", "Sanders", "Gibson", "Rahman", "Marie", "Hunter", "Fox", "Joseph", "Wang", "Gutierrez", "Li", "Hayes", "Clarke", "Tran", "Patterson", "Henry", "Ford", "Coleman", "Mason", "Richards", "Simmons", "Castro", "Robertson", "Gordon", "Woods", "Grant", "Griffin", "Paul", "Silva", "Roy", "Stone", "John", "Hunt", "Webb", "Wells", "Knight", "Johnston", "Palmer", "Mills", "Alvarez", "Burns", "Holmes", "Davies", "Andrews", "Reid", "Hussain", "Matthews", "Peters", "David", "Porter", "Bryant", "Dixon", "Santiago", "Ferguson", "Freeman", "Lawrence", "Ruiz", "Reddy", "Agarwal", "Crawford", "Jimenez", "Ray", "Malik", "Obrien", "Armstrong", "Verma", "Spencer", "Raj", "Walsh", "Elliott", "Hart", "Kaur", "Tucker", "Ho", "Daniels", "Ibrahim", "Owens", "Meyer", "Morrison", "Warren", "Dunn", "Payne", "Hansen", "Lane", "Chapman", "Romero", "Jacobs", "May", "Chavez", "Francis", "Bradley", "Liu", "Boyd", "Man", "Berry", "Duncan", "Stephens", "Gill", "Mohammed", "Medina", "Harvey", "Daniel", "Lam", "Burke", "Arora", "Cunningham", "Das", "Hicks", "Schmidt", "Gardner", "Hudson", "Yang", "Riley", "Yadav", "Olson", "Davidson", "Dean", "Day", "Hawkins", "Bautista", "Cohen", "Park", "Wagner", "Arnold", "Rice", "Lin", "Mishra", "Carroll", "Lynch", "Mehta", "Joshi", "Vargas", "Lynn", "Washington", "Moreno", "Harper", "Oliver", "Carr", "Shrestha", "Aguilar", "Zhang", "Nichols", "Williamson", "Austin", "Ong", "Snyder", "Villanueva", "Vasquez", "Willis", "Wheeler", "Jensen", "Islam", "Herrera", "Lucas", "Bishop", "Douglas", "Lawson", "Macdonald", "Hasan", "Newman", "Le", "Gilbert", "Greene", "Pierce", "Yu", "Salazar", "Chang", "Pearson", "Burton", "Kelley", "Mendez", "Watkins", "Lau", "Mann", "Barrett", "Wu", "Perkins", "Walters", "Carpenter", "Dawson", "Banks", "Franklin", "Barker", "Little", "Curtis", "Hanson", "Weaver", "Hoffman", "Miranda", "Ismail", "Holland", "Angel", "Fuller", "Montgomery", "Page", "Valdez", "Hossain", "Mccarthy", "Fletcher", "Guzman", "Doyle", "Lambert", "Saunders", "Oconnor", "Larson", "Nair", "Carlson", "Lowe", "Stanley", "Shaikh", "Simon", "Howell", "Fowler", "Chambers", "Watts", "Huang", "Quinn", "Patil", "Chua", "Craig", "Munoz", "Anthony", "Rana", "Weber", "Charles", "Cheng", "Michael", "Bates", "Sims", "Rao", "Hopkins", "Marquez", "Gregory", "Cross", "Pandey", "Tang", "Ball", "Stevenson", "Blake", "Rai", "Fleming", "Sutton", "Mercado", "Navarro", "Cameron", "Wade", "Schneider", "Pena", "Soto", "Welch", "Mccoy", "Hardy", "Jennings", "Alam", "Steele", "Delgado", "Benson", "Leung", "Abdullah", "Lloyd", "Mckenzie", "Chong", "Miles", "Beck", "Bowman", "Vega", "Webster", "Parsons", "Ortega", "Schultz", "Leonard", "Higgins", "Owen", "Garrett", "Brewer", "Newton", "Kapoor", "Fitzgerald", "Cortez", "Ann", "Norris", "Wilkinson", "Barnett", "Chauhan", "Nunez", "Potter", "Padilla", "Agrawal", "Aquino", "Gallagher", "Pham", "Burgess", "Lyons", "Moss", "Sharp", "Warner", "Cheung", "Srivastava", "Iqbal", "Prasad", "Fernandes", "Fields", "Garza", "Dennis", "Holt", "Oneill", "Luna", "Rhodes", "Keller", "Vazquez", "Moon", "Estrada", "Reeves", "Acosta", "Prince", "Lai", "Rowe", "Farmer", "Guerrero", "Blair", "Wolf", "Garg", "Moran", "Becker", "Brady", "Caldwell", "Law", "Terry", "Barber", "Rios", "Powers", "Marsh", "Hale", "Baldwin", "Molina", "Todd", "Manning", "Neal", "Patrick", "Logan", "Maxwell", "Klein", "Yap", "Hammond", "Haynes", "Francisco", "Walton", "Vincent", "Mclaughlin", "Bowen", "Richard", "Thornton", "Waters", "Bush", "Aziz", "Goodwin", "Mclean", "Cabrera", "Parks", "Nicole", "Atkinson", "Chin", "Chung", "Sandoval", "Frank", "Barton", "Omar", "Osborne", "Bond", "Shepherd", "Chandler", "Lang", "Figueroa", "Kay", "Rodgers", "Alvarado", "Norman", "Fernando", "Flynn", "Desai", "Thomson", "Horton", "Nicholson", "Fraser", "Casey", "Maldonado", "Cummings", "Nash", "Wolfe", "Serrano", "Kerr", "Thakur", "French", "Amin", "Rojas", "Christensen", "Shop", "Tyler", "Mack", "Malone", "Ang", "Townsend", "Abbas", "Pereira", "Samuel", "Sweet", "Farrell", "Tiwari", "Robbins", "Dominguez", "Gibbs", "Contreras", "Hogan", "Graves", "Solomon", "Shelton", "Sam", "Buchanan", "Brennan", "Bruce", "Chowdhury", "Fischer", "Ma", "Griffith", "Mcgee", "Suarez", "Lo", "Erickson", "Cool", "Goodman", "Yates", "Christian", "Choi", "Butt", "Byrne", "Swanson", "Schwartz", "Bird", "Byrd", "Frazier", "Morton", "Vaughn", "Low", "Olsen", "Summers", "Goh", "Petersen", "Soni", "Sinha", "Perera", "Booth", "Anand", "Garner", "Pineda", "Campos", "Baxter", "Bryan", "Mckay", "Harrington", "Jay", "Mcdaniel", "Wall", "Ramsey", "Chow", "Barry", "Lamb", "Robles", "Fuentes", "Valencia", "Lu", "Leblanc", "Stokes", "Drake", "Mckinney", "Kamal", "Briggs", "Curry", "Muhammad", "Glover", "Cannon", "Mejia", "Carey", "Grace", "Duran", "Ghosh", "Colon", "Roman", "Ingram", "Guy", "Avila", "Mahmoud", "Thapa", "Kane", "Hodges", "Leon", "Adam", "Pratt", "Raza", "Pearce", "Khalid", "Gabriel", "Saad", "Chu", "Rosales", "Kent", "Mcguire", "Nolan", "Clayton", "Wise", "Costa", "Savage", "Tate", "Manuel", "Chandra", "Jacob", "Abraham", "Mcbride", "Adel", "Mccormick", "Chaudhary", "Frost", "Sherman", "Harding", "Sparks", "Abbott", "Mullins", "Larsen", "Zimmerman", "Dee", "Norton", "Franco", "Skinner", "Hanna", "Carson", "Rodrigues", "Gurung", "Stephenson", "Griffiths", "Wilkins", "Bauer", "Shetty", "Goyal", "Dsouza", "Malhotra", "Bansal", "Hubbard", "Kemp", "Pope", "Saini", "Jose", "Reese", "Kirk", "Hampton", "Hines", "Soriano", "Preston", "Ferreira", "Aggarwal", "Poole", "Hutchinson", "Johns", "Burnett", "Bowers", "Short", "Snow", "Moody", "Randall", "Power", "Choudhary", "Joy", "Noble", "Foley", "Sinclair", "Harmon", "Mathews", "Solis", "House", "Rock", "Aja", "Rich", "Babu", "Mueller", "Jack", "Buckley", "Gross", "Tolentino", "Benjamin", "Rosario", "Small", "Ayala", "Pacheco", "Monroe", "Best", "Shukla", "Houston", "Espinoza", "Maria", "Bhatia", "Enriquez", "Schroeder", "Mcintyre", "Heath", "Kramer", "Kirby", "Levy", "Mohan", "Lara", "Saeed", "Dalton", "Han", "Chase", "Mathew", "Ling", "Cain", "Gates", "Holloway", "Gee", "Muller", "Adkins", "Calderon", "Sheikh", "Bartlett", "Joe", "Patton", "Hood", "Strickland", "Collier", "Santana", "Odonnell", "Atkins", "Marks", "Duffy", "Allison", "Velez", "Mcintosh", "Hancock", "Krishna", "Ocampo", "Sun", "Dillon", "Saleh", "Cooke", "Fitzpatrick", "Saxena", "Conway", "Hong", "Maher", "Khanna", "Wijaya", "Mcleod", "Sweeney", "Conner", "Valentine", "Andrade", "Floyd", "Moses", "Kulkarni", "Wilcox", "Camacho", "Krishnan", "Underwood", "Berg", "Dyer", "Prakash", "Elizabeth", "Mcmahon", "Velasquez", "Blue", "Cullen", "Bass", "Velasco", "Roth", "Koh", "Sutherland", "Flowers", "Morrow", "Hartman", "Tanner", "Boyle", "Brock", "Aguirre", "Ballard", "Dizon", "Cobb", "Domingo", "Siddiqui", "Shields", "Nielsen", "Stuart", "Peter", "Bear", "Massey", "Bernard", "Raymond", "Sawyer", "Samson", "Howe", "Dickson", "Cat", "Wyatt", "Leong", "Salinas", "Ashraf", "Antonio", "Zamora", "Bradford", "English", "Forbes", "York", "Middleton", "Meyers", "Joyce", "Reilly", "Davenport", "B", "Mohammad", "Bradshaw", "Walter", "Gomes", "Bee", "Hodge", "Smart", "Ashley", "Jean", "Valenzuela", "Mcmillan", "Javier", "Xu", "Greer", "Said", "Uddin", "Anwar", "Spence", "Donovan", "Horn", "Hobbs", "Barr", "Lindsey", "Whitehead", "Montoya", "Russo", "Jefferson", "Guerra", "Alex", "Villa", "Weiss", "Ansari", "Rivas", "Raja", "Andersen", "Mohd", "Copeland", "M", "Rehman", "Bridges", "Go", "Teo", "Mittal", "Vaughan", "Ram", "Kang", "Browne", "Shannon", "Carrillo", "Hess", "Jane", "Huynh", "Rashid", "Sheppard", "Saha", "Sampson", "S", "Mark", "Decker", "Goel", "Osman", "Haddad", "Slater", "Anne", "Gould", "Mcgrath", "Bentley", "Giles", "Keith", "Ferrer", "Donnelly", "Salas", "Knox", "Mostafa", "Whitaker", "Strong", "Pascual", "Peralta", "Eaton", "Starr", "Jarvis", "Singleton", "Daly", "Khoury", "Lindsay", "Mac", "Doherty", "Cervantes", "Gandhi", "Koch", "Mackenzie", "Yee", "Stark", "Archer", "Winter", "Dale", "Stafford", "Hurst", "Phelps", "Leach", "Winters", "Bhardwaj", "Humphrey", "Felix", "Gillespie", "Jha", "Hewitt", "Salah", "Khalil", "Salvador", "Connolly", "Cochran", "Qureshi", "Oconnell", "Woodward", "Shaffer", "Bhatt", "Church", "Donaldson", "Tam", "Albert", "Espinosa", "Oliveira", "Castaneda", "Nixon", "Jo", "Lozano", "Sim", "Grimes", "Clements", "Mccann", "Cardenas", "Landry", "Mustafa", "Delacruz", "Juarez", "Roach", "Mcdowell", "Hurley"
};
private static string[] _lorem =
{
"Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "Suspendisse", "tempus", "sapien", "maximus", "dictum", "pretium", "tellus", "dui", "tincidunt", "massa", "lobortis", "pellentesque", "dolor", "ligula", "et", "nulla"
};
private static string[] _departments =
{
"Legal", "Marketing", "Business Development", "Services", "Support", "Human Resources", "Sales", "Product Management", "Engineering", "Training", "Accounting", "Research and Development"
};
private static string[] _jobTitles =
{
"Sales Representative", "Structural Engineer", "Payment Adjustment Coordinator", "Senior Editor", "Nurse Practicioner", "Occupational Therapist", "Director of Sales", "Safety Technician", "Account Executive", "Marketing Manager", "Food Chemist", "Civil Engineer", "Associate Professor", "Statistician", "Research Nurse", "Data Coordinator", "Chief Design Engineer", "Computer Systems Analyst", "Environmental Tech", "Administrative Officer", "Social Worker", "Executive Secretary", "Help Desk", "Analyst Programmer", "Developer", "Programmer Analyst", "Software Test Engineer", "Biostatistician", "Office Assistant", "Systems Administrator", "Automation Specialist", "Analog Circuit Design manager", "Structural Analysis Engineer", "Technical Writer", "Software Engineer", "Budget/Accounting Analyst IV", "GIS Technical Architect", "Speech Pathologist", "Research Assistant", "Nuclear Power Engineer", "Quality Control Specialist", "General Manager", "Accountant", "Account Coordinator", "Operator", "Junior Executive", "Geological Engineer", "Recruiting Manager", "Financial Analyst", "Marketing Assistant", "Electrical Engineer", "Internal Auditor", "Paralegal", "Senior Developer", "VP Quality Control", "Media Manager", "Senior Sales Associate", "Product Engineer", "Quality Engineer", "VP Marketing", "Health Coach", "Legal Assistant", "Dental Hygienist", "Information Systems Manager", "Pharmacist", "Desktop Support Technician", "Staff Scientist", "Project Manager", "Technician", "Mechanical Systems Engineer", "Assistant Manager", "Assistant Media Planner", "Teacher", "Registered Nurse", "Sales Associate", "Geologist", "Physical Therapy Assistant"
};
private static string[] _countries =
{
"Afghanistan", "land Islands", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain", "Bahamas", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia, Plurinational State of", "Bonaire, Sint Eustatius and Saba", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cte d'Ivoire", "Croatia", "Cuba", "Curaao", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran, Islamic Republic of", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova, Republic of", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestine, State of", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Runion", "Romania", "Russian Federation", "Rwanda", "Saint Barthlemy", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin (French part)", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela, Bolivarian Republic of", "Viet Nam", "Virgin Islands, British", "Virgin Islands, U.S.", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe"
};
private static string[] _languages =
{
"English", "Mandarin Chinese", "Hindi", "Spanish", "French", "Standard Arabic", "Bengali", "Russian", "Portuguese", "Indonesian", "Urdu", "Standard German", "Japanese", "Swahili", "Marathi", "Telugu", "Western Punjabi", "Wu Chinese", "Tamil", "Turkish", "Korean", "Vietnamese", "Yue Chinese", "Javanese", "Italian", "Egyptian Spoken Arabic", "Hausa", "Thai", "Gujarati", "Kannada", "Iranian Persian", "Bhojpuri", "Southern Min Chinese", "Hakka Chinese", "Jinyu Chinese", "Filipino", "Burmese", "Polish", "Yoruba", "Odia", "Malayalam ", "Xiang Chinese", "Maithili", "Ukrainian", "Moroccan Spoken Arabic", "Eastern Punjabi", "Sunda", "Algerian Spoken Arabic", "Sundanese Spoken Arabic", "Nigerian Pidgin", "Zulu", "Igbo", "Amharic", "Northern Uzbek", "Sindhi", "North Levantine Spoken Arabic", "Nepali", "Romanian", "Tagalog", "Dutch", "Sa'idi Spoken Arabic", "Gan Chinese", "Northern Pashto", "Magahi", "Saraiki", "Xhosa", "Malay", "Khmer", "Afrikaans", "Sinhala", "Somali", "Chhattisgarhi", "Cebuano", "Mesopotamian Spoken Arabic", "Assamese", "Northeastern Thai", "Northern Kurdish", "Hijazi Spoken Arabic", "Nigerian Fulfulde", "Bavarian", "Bamanankan", "South Azerbaijani", "Northern Sotho", "Setswana", "Souther Sotho", "Czech", "Greek", "Chittagonian", "Kazakh", "Swedish", "Deccan", "Hungarian", "Jula", "Sadri", "Kinyarwanda", "Cameroonian Pidgin", "Sylheti", "South Levantine Spoken Arabic", "Tunisian Spoken Arabic", "Sanaani Spoken Arabic"
};
private static string[] _skuDigits =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "R", "S", "T", "U", "W", "X", "Y", "Z"
};
}
================================================
FILE: ConsoleApp1/Tools/Faker.cs
================================================
using LiteDB;
internal static partial class Faker
{
private static Random _random = new Random(420);
public static string Fullname()
{
var names = _random.NextBool() ? _maleNames : _femaleNames;
return names[_random.Next(names.Length - 1)] + " " + _surNames[_random.Next(_surNames.Length - 1)];
}
public static int Age()
{
return _random.Next(18, 96);
}
public static DateTime Birthday()
{
var oldest = DateTime.Today.AddYears(-110).Ticks;
var now = DateTime.Now.Ticks;
var range = now - oldest;
var date = new DateTime(oldest + _random.NextLong(0, range));
return date;
}
public static string Lorem(int size, int end = -1)
{
return string.Join(" ", Enumerable.Range(1, end == -1 ? size : _random.Next(size, end))
.Select(x => _lorem[_random.Next(_lorem.Length - 1)]));
}
public static int Next(int start, int end)
{
return _random.Next(start, end);
}
public static double NextDouble(double start, double end)
{
return start + (_random.NextDouble() * (end - start));
}
// https://stackoverflow.com/a/13095144/3286260
public static long NextLong(this Random random, long min, long max)
{
if (max <= min)
throw new ArgumentOutOfRangeException("max", "max must be > min!");
//Working with ulong so that modulo works correctly with values > long.MaxValue
ulong uRange = (ulong)(max - min);
//Prevent a modolo bias; see https://stackoverflow.com/a/10984975/238419
//for more information.
//In the worst case, the expected number of calls is 2 (though usually it's
//much closer to 1) so this loop doesn't really hurt performance at all.
ulong ulongRand;
do
{
byte[] buf = new byte[8];
random.NextBytes(buf);
ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
} while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);
return (long)(ulongRand % uRange) + min;
}
public static bool NextBool(this Random random)
{
return random.NextSingle() >= 0.5;
}
public static string Departments() => _departments[_random.Next(0, _departments.Length - 1)];
internal static BsonValue Created()
{
var oldest = DateTime.Today.AddYears(-5).Ticks;
var now = DateTime.Now.Ticks;
var range = now - oldest;
var date = new DateTime(oldest + _random.NextLong(0, range));
return date;
}
public static string Language() => _departments[_random.Next(0, _departments.Length - 1)];
public static string Department() => _departments[_random.Next(0, _departments.Length - 1)];
public static string Country() => _countries[_random.Next(0, _countries.Length - 1)];
public static string Job() => _jobTitles[_random.Next(0, _jobTitles.Length - 1)];
internal static string SkuNumber() =>
string.Join("", Enumerable.Range(1, 8).Select(x => _skuDigits[_random.Next(0, _skuDigits.Length - 1)]));
}
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014-2022 Mauricio David
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: LiteDB/Client/Database/Collections/Aggregate.cs
================================================
using System;
using System.Linq;
using System.Linq.Expressions;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
#region Count
///
/// Get document count in collection
///
public int Count()
{
// do not use indexes - collections has DocumentCount property
return this.Query().Count();
}
///
/// Get document count in collection using predicate filter expression
///
public int Count(BsonExpression predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
return this.Query().Where(predicate).Count();
}
///
/// Get document count in collection using predicate filter expression
///
public int Count(string predicate, BsonDocument parameters) => this.Count(BsonExpression.Create(predicate, parameters));
///
/// Get document count in collection using predicate filter expression
///
public int Count(string predicate, params BsonValue[] args) => this.Count(BsonExpression.Create(predicate, args));
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
public int Count(Expression> predicate) => this.Count(_mapper.GetExpression(predicate));
///
/// Get document count in collection using predicate filter expression
///
public int Count(Query query) => new LiteQueryable(_engine, _mapper, _collection, query).Count();
#endregion
#region LongCount
///
/// Get document count in collection
///
public long LongCount()
{
return this.Query().LongCount();
}
///
/// Get document count in collection using predicate filter expression
///
public long LongCount(BsonExpression predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
return this.Query().Where(predicate).LongCount();
}
///
/// Get document count in collection using predicate filter expression
///
public long LongCount(string predicate, BsonDocument parameters) => this.LongCount(BsonExpression.Create(predicate, parameters));
///
/// Get document count in collection using predicate filter expression
///
public long LongCount(string predicate, params BsonValue[] args) => this.LongCount(BsonExpression.Create(predicate, args));
///
/// Get document count in collection using predicate filter expression
///
public long LongCount(Expression> predicate) => this.LongCount(_mapper.GetExpression(predicate));
///
/// Get document count in collection using predicate filter expression
///
public long LongCount(Query query) => new LiteQueryable(_engine, _mapper, _collection, query).Count();
#endregion
#region Exists
///
/// Get true if collection contains at least 1 document that satisfies the predicate expression
///
public bool Exists(BsonExpression predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
return this.Query().Where(predicate).Exists();
}
///
/// Get true if collection contains at least 1 document that satisfies the predicate expression
///
public bool Exists(string predicate, BsonDocument parameters) => this.Exists(BsonExpression.Create(predicate, parameters));
///
/// Get true if collection contains at least 1 document that satisfies the predicate expression
///
public bool Exists(string predicate, params BsonValue[] args) => this.Exists(BsonExpression.Create(predicate, args));
///
/// Get true if collection contains at least 1 document that satisfies the predicate expression
///
public bool Exists(Expression> predicate) => this.Exists(_mapper.GetExpression(predicate));
///
/// Get true if collection contains at least 1 document that satisfies the predicate expression
///
public bool Exists(Query query) => new LiteQueryable(_engine, _mapper, _collection, query).Exists();
#endregion
#region Min/Max
///
/// Returns the min value from specified key value in collection
///
public BsonValue Min(BsonExpression keySelector)
{
if (string.IsNullOrEmpty(keySelector)) throw new ArgumentNullException(nameof(keySelector));
var doc = this.Query()
.OrderBy(keySelector)
.Select(keySelector)
.ToDocuments()
.First();
// return first field of first document
return doc[doc.Keys.First()];
}
///
/// Returns the min value of _id index
///
public BsonValue Min() => this.Min("_id");
///
/// Returns the min value from specified key value in collection
///
public K Min(Expression> keySelector)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
var expr = _mapper.GetExpression(keySelector);
var value = this.Min(expr);
return (K)_mapper.Deserialize(typeof(K), value);
}
///
/// Returns the max value from specified key value in collection
///
public BsonValue Max(BsonExpression keySelector)
{
if (string.IsNullOrEmpty(keySelector)) throw new ArgumentNullException(nameof(keySelector));
var doc = this.Query()
.OrderByDescending(keySelector)
.Select(keySelector)
.ToDocuments()
.First();
// return first field of first document
return doc[doc.Keys.First()];
}
///
/// Returns the max _id index key value
///
public BsonValue Max() => this.Max("_id");
///
/// Returns the last/max field using a linq expression
///
public K Max(Expression> keySelector)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
var expr = _mapper.GetExpression(keySelector);
var value = this.Max(expr);
return (K)_mapper.Deserialize(typeof(K), value);
}
#endregion
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Delete.cs
================================================
using System;
using System.Linq.Expressions;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Delete a single document on collection based on _id index. Returns true if document was deleted
///
public bool Delete(BsonValue id)
{
if (id == null || id.IsNull) throw new ArgumentNullException(nameof(id));
return _engine.Delete(_collection, new [] { id }) == 1;
}
///
/// Delete all documents inside collection. Returns how many documents was deleted. Run inside current transaction
///
public int DeleteAll()
{
return _engine.DeleteMany(_collection, null);
}
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
public int DeleteMany(BsonExpression predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
return _engine.DeleteMany(_collection, predicate);
}
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
public int DeleteMany(string predicate, BsonDocument parameters) => this.DeleteMany(BsonExpression.Create(predicate, parameters));
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
public int DeleteMany(string predicate, params BsonValue[] args) => this.DeleteMany(BsonExpression.Create(predicate, args));
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
public int DeleteMany(Expression> predicate) => this.DeleteMany(_mapper.GetExpression(predicate));
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Find.cs
================================================
using LiteDB.Engine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Return a new LiteQueryable to build more complex queries
///
public ILiteQueryable Query()
{
return new LiteQueryable(_engine, _mapper, _collection, new Query()).Include(_includes);
}
#region Find
///
/// Find documents inside a collection using predicate expression.
///
public IEnumerable Find(BsonExpression predicate, int skip = 0, int limit = int.MaxValue)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
return this.Query()
.Include(_includes)
.Where(predicate)
.Skip(skip)
.Limit(limit)
.ToEnumerable();
}
///
/// Find documents inside a collection using query definition.
///
public IEnumerable Find(Query query, int skip = 0, int limit = int.MaxValue)
{
if (query == null) throw new ArgumentNullException(nameof(query));
if (skip != 0) query.Offset = skip;
if (limit != int.MaxValue) query.Limit = limit;
return new LiteQueryable(_engine, _mapper, _collection, query)
.ToEnumerable();
}
///
/// Find documents inside a collection using predicate expression.
///
public IEnumerable Find(Expression> predicate, int skip = 0, int limit = int.MaxValue) => this.Find(_mapper.GetExpression(predicate), skip, limit);
#endregion
#region FindById + One + All
///
/// Find a document using Document Id. Returns null if not found.
///
public T FindById(BsonValue id)
{
if (id == null || id.IsNull) throw new ArgumentNullException(nameof(id));
return this.Find(BsonExpression.Create("_id = @0", id)).FirstOrDefault();
}
///
/// Find the first document using predicate expression. Returns null if not found
///
public T FindOne(BsonExpression predicate) => this.Find(predicate).FirstOrDefault();
///
/// Find the first document using predicate expression. Returns null if not found
///
public T FindOne(string predicate, BsonDocument parameters) => this.FindOne(BsonExpression.Create(predicate, parameters));
///
/// Find the first document using predicate expression. Returns null if not found
///
public T FindOne(BsonExpression predicate, params BsonValue[] args) => this.FindOne(BsonExpression.Create(predicate, args));
///
/// Find the first document using predicate expression. Returns null if not found
///
public T FindOne(Expression> predicate) => this.FindOne(_mapper.GetExpression(predicate));
///
/// Find the first document using defined query structure. Returns null if not found
///
public T FindOne(Query query) => this.Find(query).FirstOrDefault();
///
/// Returns all documents inside collection order by _id index.
///
public IEnumerable FindAll() => this.Query().Include(_includes).ToEnumerable();
#endregion
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Include.cs
================================================
using System;
using System.Linq;
using System.Linq.Expressions;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
/// Returns a new Collection with this action included
///
public ILiteCollection Include(Expression> keySelector)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
var path = _mapper.GetExpression(keySelector);
return this.Include(path);
}
///
/// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
/// Returns a new Collection with this action included
///
public ILiteCollection Include(BsonExpression keySelector)
{
if (string.IsNullOrEmpty(keySelector)) throw new ArgumentNullException(nameof(keySelector));
// cloning this collection and adding this include
var newcol = new LiteCollection(_collection, _autoId, _engine, _mapper);
newcol._includes.AddRange(_includes);
newcol._includes.Add(keySelector);
return newcol;
}
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Index.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Index name - unique name for this collection
/// Create a custom expression function to be indexed
/// If is a unique index
public bool EnsureIndex(string name, BsonExpression expression, bool unique = false)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
if (expression == null) throw new ArgumentNullException(nameof(expression));
return _engine.EnsureIndex(_collection, name, expression, unique);
}
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Document field/expression
/// If is a unique index
public bool EnsureIndex(BsonExpression expression, bool unique = false)
{
if (expression == null) throw new ArgumentNullException(nameof(expression));
var name = Regex.Replace(expression.Source, @"[^a-z0-9]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
return this.EnsureIndex(name, expression, unique);
}
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
public bool EnsureIndex(Expression> keySelector, bool unique = false)
{
var expression = this.GetIndexExpression(keySelector);
return this.EnsureIndex(expression, unique);
}
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// Index name - unique name for this collection
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
public bool EnsureIndex(string name, Expression> keySelector, bool unique = false)
{
var expression = this.GetIndexExpression(keySelector);
return this.EnsureIndex(name, expression, unique);
}
///
/// Get index expression based on LINQ expression. Convert IEnumerable in MultiKey indexes
///
private BsonExpression GetIndexExpression(Expression> keySelector)
{
var expression = _mapper.GetIndexExpression(keySelector);
if (typeof(K).IsEnumerable() && expression.IsScalar == true)
{
if (expression.Type == BsonExpressionType.Path)
{
// convert LINQ expression that returns an IEnumerable but expression returns a single value
// `x => x.Phones` --> `$.Phones[*]`
// works only if exression is a simple path
expression = expression.Source + "[*]";
}
else
{
throw new LiteException(0, $"Expression `{expression.Source}` must return a enumerable expression");
}
}
return expression;
}
///
/// Drop index and release slot for another index
///
public bool DropIndex(string name)
{
return _engine.DropIndex(_collection, name);
}
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Insert.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Insert a new entity to this collection. Document Id must be a new value in collection - Returns document Id
///
public BsonValue Insert(T entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
var doc = _mapper.ToDocument(entity);
var removed = this.RemoveDocId(doc);
_engine.Insert(_collection, new[] { doc }, _autoId);
var id = doc["_id"];
// checks if must update _id value in entity
if (removed)
{
_id.Setter(entity, id.RawValue);
}
return id;
}
///
/// Insert a new document to this collection using passed id value.
///
public void Insert(BsonValue id, T entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
if (id == null || id.IsNull) throw new ArgumentNullException(nameof(id));
var doc = _mapper.ToDocument(entity);
doc["_id"] = id;
_engine.Insert(_collection, new [] { doc }, _autoId);
}
///
/// Insert an array of new documents to this collection. Document Id must be a new value in collection. Can be set buffer size to commit at each N documents
///
public int Insert(IEnumerable entities)
{
if (entities == null) throw new ArgumentNullException(nameof(entities));
return _engine.Insert(_collection, this.GetBsonDocs(entities), _autoId);
}
///
/// Implements bulk insert documents in a collection. Usefull when need lots of documents.
///
[Obsolete("Use normal Insert()")]
public int InsertBulk(IEnumerable entities, int batchSize = 5000)
{
if (entities == null) throw new ArgumentNullException(nameof(entities));
return _engine.Insert(_collection, this.GetBsonDocs(entities), _autoId);
}
///
/// Convert each T document in a BsonDocument, setting autoId for each one
///
private IEnumerable GetBsonDocs(IEnumerable documents)
{
foreach (var document in documents)
{
var doc = _mapper.ToDocument(document);
var removed = this.RemoveDocId(doc);
yield return doc;
if (removed && _id != null)
{
_id.Setter(document, doc["_id"].RawValue);
}
}
}
///
/// Remove document _id if contains a "empty" value (checks for autoId bson type)
///
private bool RemoveDocId(BsonDocument doc)
{
if (_id != null && doc.TryGetValue("_id", out var id))
{
// check if exists _autoId and current id is "empty"
if ((_autoId == BsonAutoId.Int32 && (id.IsInt32 && id.AsInt32 == 0)) ||
(_autoId == BsonAutoId.ObjectId && (id.IsNull || (id.IsObjectId && id.AsObjectId == ObjectId.Empty))) ||
(_autoId == BsonAutoId.Guid && id.IsGuid && id.AsGuid == Guid.Empty) ||
(_autoId == BsonAutoId.Int64 && id.IsInt64 && id.AsInt64 == 0))
{
// in this cases, remove _id and set new value after
doc.Remove("_id");
return true;
}
}
return false;
}
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Update.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Update a document in this collection. Returns false if not found document in collection
///
public bool Update(T entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
// get BsonDocument from object
var doc = _mapper.ToDocument(entity);
return _engine.Update(_collection, new BsonDocument[] { doc }) > 0;
}
///
/// Update a document in this collection. Returns false if not found document in collection
///
public bool Update(BsonValue id, T entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
if (id == null || id.IsNull) throw new ArgumentNullException(nameof(id));
// get BsonDocument from object
var doc = _mapper.ToDocument(entity);
// set document _id using id parameter
doc["_id"] = id;
return _engine.Update(_collection, new BsonDocument[] { doc }) > 0;
}
///
/// Update all documents
///
public int Update(IEnumerable entities)
{
if (entities == null) throw new ArgumentNullException(nameof(entities));
return _engine.Update(_collection, entities.Select(x => _mapper.ToDocument(x)));
}
///
/// Update many documents based on transform expression. This expression must return a new document that will be replaced over current document (according with predicate).
/// Eg: col.UpdateMany("{ Name: UPPER($.Name), Age }", "_id > 0")
///
public int UpdateMany(BsonExpression transform, BsonExpression predicate)
{
if (transform == null) throw new ArgumentNullException(nameof(transform));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
if (transform.Type != BsonExpressionType.Document)
{
throw new ArgumentException("Extend expression must return a document. Eg: `col.UpdateMany('{ Name: UPPER(Name) }', 'Age > 10')`");
}
return _engine.UpdateMany(_collection, transform, predicate);
}
///
/// Update many document based on merge current document with extend expression. Use your class with initializers.
/// Eg: col.UpdateMany(x => new Customer { Name = x.Name.ToUpper(), Salary: 100 }, x => x.Name == "John")
///
public int UpdateMany(Expression> extend, Expression> predicate)
{
if (extend == null) throw new ArgumentNullException(nameof(extend));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
var ext = _mapper.GetExpression(extend);
var pred = _mapper.GetExpression(predicate);
if (ext.Type != BsonExpressionType.Document)
{
throw new ArgumentException("Extend expression must return an anonymous class to be merge with entities. Eg: `col.UpdateMany(x => new { Name = x.Name.ToUpper() }, x => x.Age > 10)`");
}
return _engine.UpdateMany(_collection, ext, pred);
}
}
}
================================================
FILE: LiteDB/Client/Database/Collections/Upsert.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using static LiteDB.Constants;
namespace LiteDB
{
public partial class LiteCollection
{
///
/// Insert or Update a document in this collection.
///
public bool Upsert(T entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
return this.Upsert(new T[] { entity }) == 1;
}
///
/// Insert or Update all documents
///
public int Upsert(IEnumerable entities)
{
if (entities == null) throw new ArgumentNullException(nameof(entities));
return _engine.Upsert(_collection, this.GetBsonDocs(entities), _autoId);
}
///
/// Insert or Update a document in this collection.
///
public bool Upsert(BsonValue id, T entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
if (id == null || id.IsNull) throw new ArgumentNullException(nameof(id));
// get BsonDocument from object
var doc = _mapper.ToDocument(entity);
// set document _id using id parameter
doc["_id"] = id;
return _engine.Upsert(_collection, new[] { doc }, _autoId) > 0;
}
}
}
================================================
FILE: LiteDB/Client/Database/ILiteCollection.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace LiteDB
{
public interface ILiteCollection
{
///
/// Get collection name
///
string Name { get; }
///
/// Get collection auto id type
///
BsonAutoId AutoId { get; }
///
/// Getting entity mapper from current collection. Returns null if collection are BsonDocument type
///
EntityMapper EntityMapper { get; }
///
/// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
/// Returns a new Collection with this action included
///
ILiteCollection Include(Expression> keySelector);
///
/// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
/// Returns a new Collection with this action included
///
ILiteCollection Include(BsonExpression keySelector);
///
/// Insert or Update a document in this collection.
///
bool Upsert(T entity);
///
/// Insert or Update all documents
///
int Upsert(IEnumerable entities);
///
/// Insert or Update a document in this collection.
///
bool Upsert(BsonValue id, T entity);
///
/// Update a document in this collection. Returns false if not found document in collection
///
bool Update(T entity);
///
/// Update a document in this collection. Returns false if not found document in collection
///
bool Update(BsonValue id, T entity);
///
/// Update all documents
///
int Update(IEnumerable entities);
///
/// Update many documents based on transform expression. This expression must return a new document that will be replaced over current document (according with predicate).
/// Eg: col.UpdateMany("{ Name: UPPER($.Name), Age }", "_id > 0")
///
int UpdateMany(BsonExpression transform, BsonExpression predicate);
///
/// Update many document based on merge current document with extend expression. Use your class with initializers.
/// Eg: col.UpdateMany(x => new Customer { Name = x.Name.ToUpper(), Salary: 100 }, x => x.Name == "John")
///
int UpdateMany(Expression> extend, Expression> predicate);
///
/// Insert a new entity to this collection. Document Id must be a new value in collection - Returns document Id
///
BsonValue Insert(T entity);
///
/// Insert a new document to this collection using passed id value.
///
void Insert(BsonValue id, T entity);
///
/// Insert an array of new documents to this collection. Document Id must be a new value in collection. Can be set buffer size to commit at each N documents
///
int Insert(IEnumerable entities);
///
/// Implements bulk insert documents in a collection. Usefull when need lots of documents.
///
int InsertBulk(IEnumerable entities, int batchSize = 5000);
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Index name - unique name for this collection
/// Create a custom expression function to be indexed
/// If is a unique index
bool EnsureIndex(string name, BsonExpression expression, bool unique = false);
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Document field/expression
/// If is a unique index
bool EnsureIndex(BsonExpression expression, bool unique = false);
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
bool EnsureIndex(Expression> keySelector, bool unique = false);
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// Index name - unique name for this collection
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
bool EnsureIndex(string name, Expression> keySelector, bool unique = false);
///
/// Drop index and release slot for another index
///
bool DropIndex(string name);
///
/// Return a new LiteQueryable to build more complex queries
///
ILiteQueryable Query();
///
/// Find documents inside a collection using predicate expression.
///
IEnumerable Find(BsonExpression predicate, int skip = 0, int limit = int.MaxValue);
///
/// Find documents inside a collection using query definition.
///
IEnumerable Find(Query query, int skip = 0, int limit = int.MaxValue);
///
/// Find documents inside a collection using predicate expression.
///
IEnumerable Find(Expression> predicate, int skip = 0, int limit = int.MaxValue);
///
/// Find a document using Document Id. Returns null if not found.
///
T FindById(BsonValue id);
///
/// Find the first document using predicate expression. Returns null if not found
///
T FindOne(BsonExpression predicate);
///
/// Find the first document using predicate expression. Returns null if not found
///
T FindOne(string predicate, BsonDocument parameters);
///
/// Find the first document using predicate expression. Returns null if not found
///
T FindOne(BsonExpression predicate, params BsonValue[] args);
///
/// Find the first document using predicate expression. Returns null if not found
///
T FindOne(Expression> predicate);
///
/// Find the first document using defined query structure. Returns null if not found
///
T FindOne(Query query);
///
/// Returns all documents inside collection order by _id index.
///
IEnumerable FindAll();
///
/// Delete a single document on collection based on _id index. Returns true if document was deleted
///
bool Delete(BsonValue id);
///
/// Delete all documents inside collection. Returns how many documents was deleted. Run inside current transaction
///
int DeleteAll();
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
int DeleteMany(BsonExpression predicate);
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
int DeleteMany(string predicate, BsonDocument parameters);
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
int DeleteMany(string predicate, params BsonValue[] args);
///
/// Delete all documents based on predicate expression. Returns how many documents was deleted
///
int DeleteMany(Expression> predicate);
///
/// Get document count using property on collection.
///
int Count();
///
/// Count documents matching a query. This method does not deserialize any document. Needs indexes on query expression
///
int Count(BsonExpression predicate);
///
/// Count documents matching a query. This method does not deserialize any document. Needs indexes on query expression
///
int Count(string predicate, BsonDocument parameters);
///
/// Count documents matching a query. This method does not deserialize any document. Needs indexes on query expression
///
int Count(string predicate, params BsonValue[] args);
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
int Count(Expression> predicate);
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
int Count(Query query);
///
/// Get document count using property on collection.
///
long LongCount();
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
long LongCount(BsonExpression predicate);
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
long LongCount(string predicate, BsonDocument parameters);
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
long LongCount(string predicate, params BsonValue[] args);
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
long LongCount(Expression> predicate);
///
/// Count documents matching a query. This method does not deserialize any documents. Needs indexes on query expression
///
long LongCount(Query query);
///
/// Returns true if query returns any document. This method does not deserialize any document. Needs indexes on query expression
///
bool Exists(BsonExpression predicate);
///
/// Returns true if query returns any document. This method does not deserialize any document. Needs indexes on query expression
///
bool Exists(string predicate, BsonDocument parameters);
///
/// Returns true if query returns any document. This method does not deserialize any document. Needs indexes on query expression
///
bool Exists(string predicate, params BsonValue[] args);
///
/// Returns true if query returns any document. This method does not deserialize any document. Needs indexes on query expression
///
bool Exists(Expression> predicate);
///
/// Returns true if query returns any document. This method does not deserialize any document. Needs indexes on query expression
///
bool Exists(Query query);
///
/// Returns the min value from specified key value in collection
///
BsonValue Min(BsonExpression keySelector);
///
/// Returns the min value of _id index
///
BsonValue Min();
///
/// Returns the min value from specified key value in collection
///
K Min(Expression> keySelector);
///
/// Returns the max value from specified key value in collection
///
BsonValue Max(BsonExpression keySelector);
///
/// Returns the max _id index key value
///
BsonValue Max();
///
/// Returns the last/max field using a linq expression
///
K Max(Expression> keySelector);
}
}
================================================
FILE: LiteDB/Client/Database/ILiteDatabase.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using LiteDB.Engine;
namespace LiteDB
{
public interface ILiteDatabase : IDisposable
{
///
/// Get current instance of BsonMapper used in this database instance (can be BsonMapper.Global)
///
BsonMapper Mapper { get; }
///
/// Returns a special collection for storage files/stream inside datafile. Use _files and _chunks collection names. FileId is implemented as string. Use "GetStorage" for custom options
///
ILiteStorage FileStorage { get; }
///
/// Get a collection using a entity class as strong typed document. If collection does not exits, create a new one.
///
/// Collection name (case insensitive)
/// Define autoId data type (when object contains no id field)
ILiteCollection GetCollection(string name, BsonAutoId autoId = BsonAutoId.ObjectId);
///
/// Get a collection using a name based on typeof(T).Name (BsonMapper.ResolveCollectionName function)
///
ILiteCollection GetCollection();
///
/// Get a collection using a name based on typeof(T).Name (BsonMapper.ResolveCollectionName function)
///
ILiteCollection GetCollection(BsonAutoId autoId);
///
/// Get a collection using a generic BsonDocument. If collection does not exits, create a new one.
///
/// Collection name (case insensitive)
/// Define autoId data type (when document contains no _id field)
ILiteCollection GetCollection(string name, BsonAutoId autoId = BsonAutoId.ObjectId);
///
/// Initialize a new transaction. Transaction are created "per-thread". There is only one single transaction per thread.
/// Return true if transaction was created or false if current thread already in a transaction.
///
bool BeginTrans();
///
/// Commit current transaction
///
bool Commit();
///
/// Rollback current transaction
///
bool Rollback();
///
/// Get new instance of Storage using custom FileId type, custom "_files" collection name and custom "_chunks" collection. LiteDB support multiples file storages (using different files/chunks collection names)
///
ILiteStorage GetStorage(string filesCollection = "_files", string chunksCollection = "_chunks");
///
/// Get all collections name inside this database.
///
IEnumerable GetCollectionNames();
///
/// Checks if a collection exists on database. Collection name is case insensitive
///
bool CollectionExists(string name);
///
/// Drop a collection and all data + indexes
///
bool DropCollection(string name);
///
/// Rename a collection. Returns false if oldName does not exists or newName already exists
///
bool RenameCollection(string oldName, string newName);
///
/// Execute SQL commands and return as data reader.
///
IBsonDataReader Execute(TextReader commandReader, BsonDocument parameters = null);
///
/// Execute SQL commands and return as data reader
///
IBsonDataReader Execute(string command, BsonDocument parameters = null);
///
/// Execute SQL commands and return as data reader
///
IBsonDataReader Execute(string command, params BsonValue[] args);
///
/// Do database checkpoint. Copy all commited transaction from log file into datafile.
///
void Checkpoint();
///
/// Rebuild all database to remove unused pages - reduce data file
///
long Rebuild(RebuildOptions options = null);
///
/// Get value from internal engine variables
///
BsonValue Pragma(string name);
///
/// Set new value to internal engine variables
///
BsonValue Pragma(string name, BsonValue value);
///
/// Get/Set database user version - use this version number to control database change model
///
int UserVersion { get; set; }
///
/// Get/Set database timeout - this timeout is used to wait for unlock using transactions
///
TimeSpan Timeout { get; set; }
///
/// Get/Set if database will deserialize dates in UTC timezone or Local timezone (default: Local)
///
bool UtcDate { get; set; }
///
/// Get/Set database limit size (in bytes). New value must be equals or larger than current database size
///
long LimitSize { get; set; }
///
/// Get/Set in how many pages (8 Kb each page) log file will auto checkpoint (copy from log file to data file). Use 0 to manual-only checkpoint (and no checkpoint on dispose)
/// Default: 1000 pages
///
int CheckpointSize { get; set; }
///
/// Get database collection (this options can be changed only in rebuild proces)
///
Collation Collation { get; }
}
}
================================================
FILE: LiteDB/Client/Database/ILiteQueryable.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LiteDB
{
public interface ILiteQueryable : ILiteQueryableResult
{
ILiteQueryable Include(BsonExpression path);
ILiteQueryable Include(List paths);
ILiteQueryable Include(Expression> path);
ILiteQueryable Where(BsonExpression predicate);
ILiteQueryable Where(string predicate, BsonDocument parameters);
ILiteQueryable Where(string predicate, params BsonValue[] args);
ILiteQueryable Where(Expression> predicate);
ILiteQueryable OrderBy(BsonExpression keySelector, int order = 1);
ILiteQueryable OrderBy(Expression> keySelector, int order = 1);
ILiteQueryable OrderByDescending(BsonExpression keySelector);
ILiteQueryable OrderByDescending(Expression> keySelector);
ILiteQueryable GroupBy(BsonExpression keySelector);
ILiteQueryable Having(BsonExpression predicate);
ILiteQueryableResult Select(BsonExpression selector);
ILiteQueryableResult Select(Expression> selector);
}
public interface ILiteQueryableResult
{
ILiteQueryableResult Limit(int limit);
ILiteQueryableResult Skip(int offset);
ILiteQueryableResult Offset(int offset);
ILiteQueryableResult ForUpdate();
BsonDocument GetPlan();
IBsonDataReader ExecuteReader();
IEnumerable ToDocuments();
IEnumerable ToEnumerable();
List ToList();
T[] ToArray();
int Into(string newCollection, BsonAutoId autoId = BsonAutoId.ObjectId);
T First();
T FirstOrDefault();
T Single();
T SingleOrDefault();
int Count();
long LongCount();
bool Exists();
}
}
================================================
FILE: LiteDB/Client/Database/ILiteRepository.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace LiteDB
{
public interface ILiteRepository : IDisposable
{
///
/// Get database instance
///
ILiteDatabase Database { get; }
///
/// Insert a new document into collection. Document Id must be a new value in collection - Returns document Id
///
BsonValue Insert(T entity, string collectionName = null);
///
/// Insert an array of new documents into collection. Document Id must be a new value in collection. Can be set buffer size to commit at each N documents
///
int Insert(IEnumerable entities, string collectionName = null);
///
/// Update a document into collection. Returns false if not found document in collection
///
bool Update(T entity, string collectionName = null);
///
/// Update all documents
///
int Update(IEnumerable entities, string collectionName = null);
///
/// Insert or Update a document based on _id key. Returns true if insert entity or false if update entity
///
bool Upsert(T entity, string collectionName = null);
///
/// Insert or Update all documents based on _id key. Returns entity count that was inserted
///
int Upsert(IEnumerable entities, string collectionName = null);
///
/// Delete entity based on _id key
///
bool Delete(BsonValue id, string collectionName = null);
///
/// Delete entity based on Query
///
int DeleteMany(BsonExpression predicate, string collectionName = null);
///
/// Delete entity based on predicate filter expression
///
int DeleteMany(Expression> predicate, string collectionName = null);
///
/// Returns new instance of LiteQueryable that provides all method to query any entity inside collection. Use fluent API to apply filter/includes an than run any execute command, like ToList() or First()
///
ILiteQueryable Query(string collectionName = null);
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Index name - unique name for this collection
/// Create a custom expression function to be indexed
/// If is a unique index
/// Collection Name
bool EnsureIndex(string name, BsonExpression expression, bool unique = false, string collectionName = null);
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Create a custom expression function to be indexed
/// If is a unique index
/// Collection Name
bool EnsureIndex(BsonExpression expression, bool unique = false, string collectionName = null);
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
/// Collection Name
bool EnsureIndex(Expression> keySelector, bool unique = false, string collectionName = null);
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// Index name - unique name for this collection
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
/// Collection Name
bool EnsureIndex(string name, Expression> keySelector, bool unique = false, string collectionName = null);
///
/// Search for a single instance of T by Id. Shortcut from Query.SingleById
///
T SingleById(BsonValue id, string collectionName = null);
///
/// Execute Query[T].Where(predicate).ToList();
///
List Fetch(BsonExpression predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).ToList();
///
List Fetch(Expression> predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).First();
///
T First(BsonExpression predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).First();
///
T First(Expression> predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).FirstOrDefault();
///
T FirstOrDefault(BsonExpression predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).FirstOrDefault();
///
T FirstOrDefault(Expression> predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).Single();
///
T Single(BsonExpression predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).Single();
///
T Single(Expression> predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).SingleOrDefault();
///
T SingleOrDefault(BsonExpression predicate, string collectionName = null);
///
/// Execute Query[T].Where(predicate).SingleOrDefault();
///
T SingleOrDefault(Expression> predicate, string collectionName = null);
}
}
================================================
FILE: LiteDB/Client/Database/LiteCollection.cs
================================================
using LiteDB.Engine;
using System;
using System.Collections.Generic;
using static LiteDB.Constants;
namespace LiteDB
{
public sealed partial class LiteCollection : ILiteCollection
{
private readonly string _collection;
private readonly ILiteEngine _engine;
private readonly List _includes;
private readonly BsonMapper _mapper;
private readonly EntityMapper _entity;
private readonly MemberMapper _id;
private readonly BsonAutoId _autoId;
///
/// Get collection name
///
public string Name => _collection;
///
/// Get collection auto id type
///
public BsonAutoId AutoId => _autoId;
///
/// Getting entity mapper from current collection. Returns null if collection are BsonDocument type
///
public EntityMapper EntityMapper => _entity;
internal LiteCollection(string name, BsonAutoId autoId, ILiteEngine engine, BsonMapper mapper)
{
_collection = name ?? mapper.ResolveCollectionName(typeof(T));
_engine = engine;
_mapper = mapper;
_includes = new List();
// if strong typed collection, get _id member mapped (if exists)
if (typeof(T) == typeof(BsonDocument))
{
_entity = null;
_id = null;
_autoId = autoId;
}
else
{
_entity = mapper.GetEntityMapper(typeof(T));
_entity.WaitForInitialization();
_id = _entity.Id;
if (_id != null && _id.AutoId)
{
_autoId =
_id.DataType == typeof(Int32) || _id.DataType == typeof(Int32?) ? BsonAutoId.Int32 :
_id.DataType == typeof(Int64) || _id.DataType == typeof(Int64?) ? BsonAutoId.Int64 :
_id.DataType == typeof(Guid) || _id.DataType == typeof(Guid?) ? BsonAutoId.Guid :
BsonAutoId.ObjectId;
}
else
{
_autoId = autoId;
}
}
}
}
}
================================================
FILE: LiteDB/Client/Database/LiteDatabase.cs
================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using LiteDB.Engine;
using static LiteDB.Constants;
namespace LiteDB
{
///
/// The LiteDB database. Used for create a LiteDB instance and use all storage resources. It's the database connection
///
public partial class LiteDatabase : ILiteDatabase
{
#region Properties
private readonly ILiteEngine _engine;
private readonly BsonMapper _mapper;
private readonly bool _disposeOnClose;
///
/// Get current instance of BsonMapper used in this database instance (can be BsonMapper.Global)
///
public BsonMapper Mapper => _mapper;
#endregion
#region Ctor
///
/// Starts LiteDB database using a connection string for file system database
///
public LiteDatabase(string connectionString, BsonMapper mapper = null)
: this(new ConnectionString(connectionString), mapper)
{
}
///
/// Starts LiteDB database using a connection string for file system database
///
public LiteDatabase(ConnectionString connectionString, BsonMapper mapper = null)
{
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
_engine = connectionString.CreateEngine();
_mapper = mapper ?? BsonMapper.Global;
_disposeOnClose = true;
}
///
/// Starts LiteDB database using a generic Stream implementation (mostly MemoryStream).
///
/// DataStream reference
/// BsonMapper mapper reference
/// LogStream reference
public LiteDatabase(Stream stream, BsonMapper mapper = null, Stream logStream = null)
{
var settings = new EngineSettings
{
DataStream = stream ?? throw new ArgumentNullException(nameof(stream)),
LogStream = logStream
};
_engine = new LiteEngine(settings);
_mapper = mapper ?? BsonMapper.Global;
_disposeOnClose = true;
}
///
/// Start LiteDB database using a pre-exiting engine. When LiteDatabase instance dispose engine instance will be disposed too
///
public LiteDatabase(ILiteEngine engine, BsonMapper mapper = null, bool disposeOnClose = true)
{
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
_mapper = mapper ?? BsonMapper.Global;
_disposeOnClose = disposeOnClose;
}
#endregion
#region Collections
///
/// Get a collection using an entity class as strong typed document. If collection does not exist, create a new one.
///
/// Collection name (case insensitive)
/// Define autoId data type (when object contains no id field)
public ILiteCollection GetCollection(string name, BsonAutoId autoId = BsonAutoId.ObjectId)
{
return new LiteCollection(name, autoId, _engine, _mapper);
}
///
/// Get a collection using a name based on typeof(T).Name (BsonMapper.ResolveCollectionName function)
///
public ILiteCollection GetCollection()
{
return this.GetCollection(null);
}
///
/// Get a collection using a name based on typeof(T).Name (BsonMapper.ResolveCollectionName function)
///
public ILiteCollection GetCollection(BsonAutoId autoId)
{
return this.GetCollection(null, autoId);
}
///
/// Get a collection using a generic BsonDocument. If collection does not exist, create a new one.
///
/// Collection name (case insensitive)
/// Define autoId data type (when document contains no _id field)
public ILiteCollection GetCollection(string name, BsonAutoId autoId = BsonAutoId.ObjectId)
{
if (name.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(name));
return new LiteCollection(name, autoId, _engine, _mapper);
}
#endregion
#region Transaction
///
/// Initialize a new transaction. Transaction are created "per-thread". There is only one single transaction per thread.
/// Return true if transaction was created or false if current thread already in a transaction.
///
public bool BeginTrans() => _engine.BeginTrans();
///
/// Commit current transaction
///
public bool Commit() => _engine.Commit();
///
/// Rollback current transaction
///
public bool Rollback() => _engine.Rollback();
#endregion
#region FileStorage
private ILiteStorage _fs = null;
///
/// Returns a special collection for storage files/stream inside datafile. Use _files and _chunks collection names. FileId is implemented as string. Use "GetStorage" for custom options
///
public ILiteStorage FileStorage
{
get { return _fs ?? (_fs = this.GetStorage()); }
}
///
/// Get new instance of Storage using custom FileId type, custom "_files" collection name and custom "_chunks" collection. LiteDB support multiples file storages (using different files/chunks collection names)
///
public ILiteStorage GetStorage(string filesCollection = "_files", string chunksCollection = "_chunks")
{
return new LiteStorage(this, filesCollection, chunksCollection);
}
#endregion
#region Shortcut
///
/// Get all collections name inside this database.
///
public IEnumerable GetCollectionNames()
{
// use $cols system collection with type = user only
var cols = this.GetCollection("$cols")
.Query()
.Where("type = 'user'")
.ToDocuments()
.Select(x => x["name"].AsString)
.ToArray();
return cols;
}
///
/// Checks if a collection exists on database. Collection name is case insensitive
///
public bool CollectionExists(string name)
{
if (name.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(name));
return this.GetCollectionNames().Contains(name, StringComparer.OrdinalIgnoreCase);
}
///
/// Drop a collection and all data + indexes
///
public bool DropCollection(string name)
{
if (name.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(name));
return _engine.DropCollection(name);
}
///
/// Rename a collection. Returns false if oldName does not exists or newName already exists
///
public bool RenameCollection(string oldName, string newName)
{
if (oldName.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(oldName));
if (newName.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(newName));
return _engine.RenameCollection(oldName, newName);
}
#endregion
#region Execute SQL
///
/// Execute SQL commands and return as data reader.
///
public IBsonDataReader Execute(TextReader commandReader, BsonDocument parameters = null)
{
if (commandReader == null) throw new ArgumentNullException(nameof(commandReader));
var tokenizer = new Tokenizer(commandReader);
var sql = new SqlParser(_engine, tokenizer, parameters);
var reader = sql.Execute();
return reader;
}
///
/// Execute SQL commands and return as data reader
///
public IBsonDataReader Execute(string command, BsonDocument parameters = null)
{
if (command == null) throw new ArgumentNullException(nameof(command));
var tokenizer = new Tokenizer(command);
var sql = new SqlParser(_engine, tokenizer, parameters);
var reader = sql.Execute();
return reader;
}
///
/// Execute SQL commands and return as data reader
///
public IBsonDataReader Execute(string command, params BsonValue[] args)
{
var p = new BsonDocument();
var index = 0;
foreach (var arg in args)
{
p[index.ToString()] = arg;
index++;
}
return this.Execute(command, p);
}
#endregion
#region Checkpoint/Rebuild
///
/// Do database checkpoint. Copy all commited transaction from log file into datafile.
///
public void Checkpoint()
{
_engine.Checkpoint();
}
///
/// Rebuild all database to remove unused pages - reduce data file
///
public long Rebuild(RebuildOptions options = null)
{
return _engine.Rebuild(options ?? new RebuildOptions());
}
#endregion
#region Pragmas
///
/// Get value from internal engine variables
///
public BsonValue Pragma(string name)
{
return _engine.Pragma(name);
}
///
/// Set new value to internal engine variables
///
public BsonValue Pragma(string name, BsonValue value)
{
return _engine.Pragma(name, value);
}
///
/// Get/Set database user version - use this version number to control database change model
///
public int UserVersion
{
get => _engine.Pragma(Pragmas.USER_VERSION);
set => _engine.Pragma(Pragmas.USER_VERSION, value);
}
///
/// Get/Set database timeout - this timeout is used to wait for unlock using transactions
///
public TimeSpan Timeout
{
get => TimeSpan.FromSeconds(_engine.Pragma(Pragmas.TIMEOUT).AsInt32);
set => _engine.Pragma(Pragmas.TIMEOUT, (int)value.TotalSeconds);
}
///
/// Get/Set if database will deserialize dates in UTC timezone or Local timezone (default: Local)
///
public bool UtcDate
{
get => _engine.Pragma(Pragmas.UTC_DATE);
set => _engine.Pragma(Pragmas.UTC_DATE, value);
}
///
/// Get/Set database limit size (in bytes). New value must be equals or larger than current database size
///
public long LimitSize
{
get => _engine.Pragma(Pragmas.LIMIT_SIZE);
set => _engine.Pragma(Pragmas.LIMIT_SIZE, value);
}
///
/// Get/Set in how many pages (8 Kb each page) log file will auto checkpoint (copy from log file to data file). Use 0 to manual-only checkpoint (and no checkpoint on dispose)
/// Default: 1000 pages
///
public int CheckpointSize
{
get => _engine.Pragma(Pragmas.CHECKPOINT);
set => _engine.Pragma(Pragmas.CHECKPOINT, value);
}
///
/// Get database collection (this options can be changed only in rebuild proces)
///
public Collation Collation
{
get => new Collation(_engine.Pragma(Pragmas.COLLATION).AsString);
}
#endregion
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
~LiteDatabase()
{
this.Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && _disposeOnClose)
{
_engine.Dispose();
}
}
}
}
================================================
FILE: LiteDB/Client/Database/LiteQueryable.cs
================================================
using LiteDB.Engine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using static LiteDB.Constants;
namespace LiteDB
{
///
/// An IQueryable-like class to write fluent query in documents in collection.
///
public class LiteQueryable : ILiteQueryable
{
protected readonly ILiteEngine _engine;
protected readonly BsonMapper _mapper;
protected readonly string _collection;
protected readonly Query _query;
// indicate that T type are simple and result are inside first document fields (query always return a BsonDocument)
private readonly bool _isSimpleType = Reflection.IsSimpleType(typeof(T));
internal LiteQueryable(ILiteEngine engine, BsonMapper mapper, string collection, Query query)
{
_engine = engine;
_mapper = mapper;
_collection = collection;
_query = query;
}
#region Includes
///
/// Load cross reference documents from path expression (DbRef reference)
///
public ILiteQueryable Include(Expression> path)
{
_query.Includes.Add(_mapper.GetExpression(path));
return this;
}
///
/// Load cross reference documents from path expression (DbRef reference)
///
public ILiteQueryable Include(BsonExpression path)
{
_query.Includes.Add(path);
return this;
}
///
/// Load cross reference documents from path expression (DbRef reference)
///
public ILiteQueryable Include(List paths)
{
_query.Includes.AddRange(paths);
return this;
}
#endregion
#region Where
///
/// Filters a sequence of documents based on a predicate expression
///
public ILiteQueryable Where(BsonExpression predicate)
{
_query.Where.Add(predicate);
return this;
}
///
/// Filters a sequence of documents based on a predicate expression
///
public ILiteQueryable Where(string predicate, BsonDocument parameters)
{
_query.Where.Add(BsonExpression.Create(predicate, parameters));
return this;
}
///
/// Filters a sequence of documents based on a predicate expression
///
public ILiteQueryable Where(string predicate, params BsonValue[] args)
{
_query.Where.Add(BsonExpression.Create(predicate, args));
return this;
}
///
/// Filters a sequence of documents based on a predicate expression
///
public ILiteQueryable Where(Expression> predicate)
{
return this.Where(_mapper.GetExpression(predicate));
}
#endregion
#region OrderBy
///
/// Sort the documents of resultset in ascending (or descending) order according to a key (support only one OrderBy)
///
public ILiteQueryable OrderBy(BsonExpression keySelector, int order = Query.Ascending)
{
if (_query.OrderBy != null) throw new ArgumentException("ORDER BY already defined in this query builder");
_query.OrderBy = keySelector;
_query.Order = order;
return this;
}
///
/// Sort the documents of resultset in ascending (or descending) order according to a key (support only one OrderBy)
///
public ILiteQueryable OrderBy(Expression> keySelector, int order = Query.Ascending)
{
return this.OrderBy(_mapper.GetExpression(keySelector), order);
}
///
/// Sort the documents of resultset in descending order according to a key (support only one OrderBy)
///
public ILiteQueryable OrderByDescending(BsonExpression keySelector) => this.OrderBy(keySelector, Query.Descending);
///
/// Sort the documents of resultset in descending order according to a key (support only one OrderBy)
///
public ILiteQueryable OrderByDescending(Expression> keySelector) => this.OrderBy(keySelector, Query.Descending);
#endregion
#region GroupBy
///
/// Groups the documents of resultset according to a specified key selector expression (support only one GroupBy)
///
public ILiteQueryable GroupBy(BsonExpression keySelector)
{
if (_query.GroupBy != null) throw new ArgumentException("GROUP BY already defined in this query");
_query.GroupBy = keySelector;
return this;
}
#endregion
#region Having
///
/// Filter documents after group by pipe according to predicate expression (requires GroupBy and support only one Having)
///
public ILiteQueryable Having(BsonExpression predicate)
{
if (_query.Having != null) throw new ArgumentException("HAVING already defined in this query");
_query.Having = predicate;
return this;
}
#endregion
#region Select
///
/// Transform input document into a new output document. Can be used with each document, group by or all source
///
public ILiteQueryableResult Select(BsonExpression selector)
{
_query.Select = selector;
return new LiteQueryable(_engine, _mapper, _collection, _query);
}
///
/// Project each document of resultset into a new document/value based on selector expression
///
public ILiteQueryableResult Select(Expression> selector)
{
if (_query.GroupBy != null) throw new ArgumentException("Use Select(BsonExpression selector) when using GroupBy query");
_query.Select = _mapper.GetExpression(selector);
return new LiteQueryable(_engine, _mapper, _collection, _query);
}
#endregion
#region Offset/Limit/ForUpdate
///
/// Execute query locking collection in write mode. This is avoid any other thread change results after read document and before transaction ends
///
public ILiteQueryableResult ForUpdate()
{
_query.ForUpdate = true;
return this;
}
///
/// Bypasses a specified number of documents in resultset and retun the remaining documents (same as Skip)
///
public ILiteQueryableResult Offset(int offset)
{
_query.Offset = offset;
return this;
}
///
/// Bypasses a specified number of documents in resultset and retun the remaining documents (same as Offset)
///
public ILiteQueryableResult Skip(int offset) => this.Offset(offset);
///
/// Return a specified number of contiguous documents from start of resultset
///
public ILiteQueryableResult Limit(int limit)
{
_query.Limit = limit;
return this;
}
#endregion
#region Execute Result
///
/// Execute query and returns resultset as generic BsonDataReader
///
public IBsonDataReader ExecuteReader()
{
_query.ExplainPlan = false;
return _engine.Query(_collection, _query);
}
///
/// Execute query and return resultset as IEnumerable of documents
///
public IEnumerable ToDocuments()
{
using (var reader = this.ExecuteReader())
{
while (reader.Read())
{
yield return reader.Current as BsonDocument;
}
}
}
///
/// Execute query and return resultset as IEnumerable of T. If T is a ValueType or String, return values only (not documents)
///
public IEnumerable ToEnumerable()
{
if (_isSimpleType)
{
return this.ToDocuments()
.Select(x => x[x.Keys.First()])
.Select(x => (T)_mapper.Deserialize(typeof(T), x));
}
else
{
return this.ToDocuments()
.Select(x => (T)_mapper.Deserialize(typeof(T), x));
}
}
///
/// Execute query and return results as a List
///
public List ToList()
{
return this.ToEnumerable().ToList();
}
///
/// Execute query and return results as an Array
///
public T[] ToArray()
{
return this.ToEnumerable().ToArray();
}
///
/// Get execution plan over current query definition to see how engine will execute query
///
public BsonDocument GetPlan()
{
_query.ExplainPlan = true;
var reader = _engine.Query(_collection, _query);
return reader.ToEnumerable().FirstOrDefault()?.AsDocument;
}
#endregion
#region Execute Single/First
///
/// Returns the only document of resultset, and throw an exception if there not exactly one document in the sequence
///
public T Single()
{
return this.ToEnumerable().Single();
}
///
/// Returns the only document of resultset, or null if resultset are empty; this method throw an exception if there not exactly one document in the sequence
///
public T SingleOrDefault()
{
return this.ToEnumerable().SingleOrDefault();
}
///
/// Returns first document of resultset
///
public T First()
{
return this.ToEnumerable().First();
}
///
/// Returns first document of resultset or null if resultset are empty
///
public T FirstOrDefault()
{
return this.ToEnumerable().FirstOrDefault();
}
#endregion
#region Execute Count
///
/// Execute Count methos in filter query
///
public int Count()
{
var oldSelect = _query.Select;
try
{
this.Select($"{{ count: COUNT(*._id) }}");
var ret = this.ToDocuments().Single()["count"].AsInt32;
return ret;
}
finally
{
_query.Select = oldSelect;
}
}
///
/// Execute Count methos in filter query
///
public long LongCount()
{
var oldSelect = _query.Select;
try
{
this.Select($"{{ count: COUNT(*._id) }}");
var ret = this.ToDocuments().Single()["count"].AsInt64;
return ret;
}
finally
{
_query.Select = oldSelect;
}
}
///
/// Returns true/false if query returns any result
///
public bool Exists()
{
var oldSelect = _query.Select;
try
{
this.Select($"{{ exists: ANY(*._id) }}");
var ret = this.ToDocuments().Single()["exists"].AsBoolean;
return ret;
}
finally
{
_query.Select = oldSelect;
}
}
#endregion
#region Execute Into
public int Into(string newCollection, BsonAutoId autoId = BsonAutoId.ObjectId)
{
_query.Into = newCollection;
_query.IntoAutoId = autoId;
using (var reader = this.ExecuteReader())
{
return reader.Current.AsInt32;
}
}
#endregion
}
}
================================================
FILE: LiteDB/Client/Database/LiteRepository.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using static LiteDB.Constants;
namespace LiteDB
{
///
/// The LiteDB repository pattern. A simple way to access your documents in a single class with fluent query api
///
public class LiteRepository : ILiteRepository
{
#region Properties
private readonly ILiteDatabase _db = null;
///
/// Get database instance
///
public ILiteDatabase Database => _db;
#endregion
#region Ctor
///
/// Starts LiteDB database an existing Database instance
///
public LiteRepository(ILiteDatabase database)
{
_db = database;
}
///
/// Starts LiteDB database using a connection string for file system database
///
public LiteRepository(string connectionString, BsonMapper mapper = null)
{
_db = new LiteDatabase(connectionString, mapper);
}
///
/// Starts LiteDB database using a connection string for file system database
///
public LiteRepository(ConnectionString connectionString, BsonMapper mapper = null)
{
_db = new LiteDatabase(connectionString, mapper);
}
///
/// Starts LiteDB database using a Stream disk
///
public LiteRepository(Stream stream, BsonMapper mapper = null, Stream logStream = null)
{
_db = new LiteDatabase(stream, mapper, logStream);
}
#endregion
#region Insert
///
/// Insert a new document into collection. Document Id must be a new value in collection - Returns document Id
///
public BsonValue Insert(T entity, string collectionName = null)
{
return _db.GetCollection(collectionName).Insert(entity);
}
///
/// Insert an array of new documents into collection. Document Id must be a new value in collection. Can be set buffer size to commit at each N documents
///
public int Insert(IEnumerable entities, string collectionName = null)
{
return _db.GetCollection(collectionName).Insert(entities);
}
#endregion
#region Update
///
/// Update a document into collection. Returns false if not found document in collection
///
public bool Update(T entity, string collectionName = null)
{
return _db.GetCollection(collectionName).Update(entity);
}
///
/// Update all documents
///
public int Update(IEnumerable entities, string collectionName = null)
{
return _db.GetCollection(collectionName).Update(entities);
}
#endregion
#region Upsert
///
/// Insert or Update a document based on _id key. Returns true if insert entity or false if update entity
///
public bool Upsert(T entity, string collectionName = null)
{
return _db.GetCollection(collectionName).Upsert(entity);
}
///
/// Insert or Update all documents based on _id key. Returns entity count that was inserted
///
public int Upsert(IEnumerable entities, string collectionName = null)
{
return _db.GetCollection(collectionName).Upsert(entities);
}
#endregion
#region Delete
///
/// Delete entity based on _id key
///
public bool Delete(BsonValue id, string collectionName = null)
{
return _db.GetCollection(collectionName).Delete(id);
}
///
/// Delete entity based on Query
///
public int DeleteMany(BsonExpression predicate, string collectionName = null)
{
return _db.GetCollection(collectionName).DeleteMany(predicate);
}
///
/// Delete entity based on predicate filter expression
///
public int DeleteMany(Expression> predicate, string collectionName = null)
{
return _db.GetCollection(collectionName).DeleteMany(predicate);
}
#endregion
#region Query
///
/// Returns new instance of LiteQueryable that provides all method to query any entity inside collection. Use fluent API to apply filter/includes an than run any execute command, like ToList() or First()
///
public ILiteQueryable Query(string collectionName = null)
{
return _db.GetCollection(collectionName).Query();
}
#endregion
#region EnsureIndex
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Index name - unique name for this collection
/// Create a custom expression function to be indexed
/// If is a unique index
/// Collection Name
public bool EnsureIndex(string name, BsonExpression expression, bool unique = false, string collectionName = null)
{
return _db.GetCollection(collectionName).EnsureIndex(name, expression, unique);
}
///
/// Create a new permanent index in all documents inside this collections if index not exists already. Returns true if index was created or false if already exits
///
/// Create a custom expression function to be indexed
/// If is a unique index
/// Collection Name
public bool EnsureIndex(BsonExpression expression, bool unique = false, string collectionName = null)
{
return _db.GetCollection(collectionName).EnsureIndex(expression, unique);
}
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
/// Collection Name
public bool EnsureIndex(Expression> keySelector, bool unique = false, string collectionName = null)
{
return _db.GetCollection(collectionName).EnsureIndex(keySelector, unique);
}
///
/// Create a new permanent index in all documents inside this collections if index not exists already.
///
/// Index name - unique name for this collection
/// LinqExpression to be converted into BsonExpression to be indexed
/// Create a unique keys index?
/// Collection Name
public bool EnsureIndex(string name, Expression