Utilizing LiteDB in PowerShell 7

Utilizing LiteDB in PowerShell 7


Powershell logo

LiteDB is a .NET native NoSQL embedded database. Constructed-in .NET, LiteDB is well accessible to PowerShell and works splendidly as an area and versatile database. Constructed-in encryption, SQL-like instructions, and ACID-compliant with full transaction assist LiteDB is straightforward and simple to make use of. On this article, we’ll discuss you should use LiteDB inside PowerShell and potential use cases!

Putting in LiteDB in PowerShell

Out there as a NuGet package deal, LiteDB is well installable as a package deal utilizing the Set up-Package deal cmdlet. The latest version, on the time of publication, is model 5.0.9, which we’re concentrating on because the minimal model. Moreover, to keep away from the necessity for administrative rights, we’re putting in this underneath the CurrentUser scope.

Set up-Package deal -Title 'LiteDB' -MinimumVersion '5.0.9' -Supply 'nuget.org' -Scope 'CurrentUser'

Subsequent, we’re going to import the library to be used. You possibly can merely use Add-Sort and level to the trail of the meeting, however we are able to automate that.

# Check if we've already loaded the meeting by in search of the PSType of LiteDB.LiteDatabase
If ( -Not ([System.Management.Automation.PSTypeName]'LiteDB.LiteDatabase').Sort ) {
	# 1) Get the trail of the LiteDB package deal utilizing the Supply 
  # 2) This returns the *.nupkg file, so we use Cut up-Path to solely return the package deal root path
  # 3) A number of DLL's will exist, often for .NET 4.5, .NET Normal 1.3, and .NET Normal 2.0. Find solely the .NET Normal and the most recent model, on this case 2.0.
  # The trail will look one thing like: C:UsersusernameAppDataLocalPackageManagementNuGetPackagesLiteDB.5.0.9libnetstandard2.0LiteDB.dll
  $standardAssemblyFullPath = (Get-ChildItem -Filter '*.dll' -Recurse (Cut up-Path (Get-Package deal -Title 'LiteDB').Supply)).FullName | The place-Object {$_ -Like "*customary*"} | Choose-Object -Final 1
  
  Add-Sort -Path $standardAssemblyFullPath -ErrorAction 'SilentlyContinue'
}

Now that we’ve loaded the module to be used, learn on to create a brand new LiteDB database within the subsequent part!

Making a New LiteDB Database

There are a selection of instructions out there for LiteDB, which you’ll be able to learn about here, however we first have to create a model new database. We might want to outline the trail the place to create the database file. Since LiteDB creates single file databases, the database might be situated wherever. On this case, we’ll find the DB in our present path and use the identify of Check.db.

# Create the Check.db database within the present listing
$Database = [LiteDB.LiteDatabase]::New((Be part of-Path -Path "." -ChildPath "Check.db"))

Remember the fact that till you name $Database.Dispose() on the database file, the Check.db file will stay locked.

Within the subsequent part we’ll create a desk, add an index, and create a brand new document in our database.

Making a Desk and Including a Report into LiteDB

Much like tables in SQL, LiteDB makes use of Collections, much like MongoDB. For this text, we’ll create a brand new assortment named TestCollection, and by utilizing GetCollection() the gathering shall be created if it doesn’t exist already.

# Retrieve the gathering (i.e. desk) to retailer our information in.
$Assortment = $Database.GetCollection('TestCollection')

# Ensure that an index exists on the Title discipline in order that queries work simpler and faster.
# To permit for named queries, reminiscent of utilizing the Title discipline, we guarantee an index is created.
# The result's despatched to Out-Null to keep away from the True console output on creation.
$Assortment.EnsureIndex('Title') | Out-Null

Indexes are worthwhile as they enhance efficiency and permit for simply named queries when trying to find a document. Applied utilizing skip-lists, indexes keep away from a full-scan and deserialization of the database each time a search is completed.

Including a Report Right into a LiteDB Assortment

First, we have to arrange the LiteDB.BSONMapper. That is LiteDB’s implementation of paperwork, which shops key-value pairs. We first create a mapper that we are able to parse a PowerShell object right into a doc that may then be added to our assortment utilizing the Insert() methodology.

$BSONMapper = [LiteDB.BSONMapper]::New()

$Object = @{
  "Title"  = 'TestName'
  "Worth" = 'TestValue'
}

Strive {
  # Try and insert the thing as a brand new assortment entry.
  $Assortment.Insert($BSONMapper.ToDocument($Object))
} Catch {
  Throw "Unable to insert merchandise."
}

Querying Information in LiteDB

To question an object in LiteDB, we are able to use a number of totally different strategies reminiscent of:

  • FindAll() – Return all paperwork in a group.
  • FindOne() – Returns FirstOrDefault of a Discover() question.
  • FindById() – Returns SingleOrDefault results of Discover() by utilizing the first key of _id index.
  • Discover() – Return all paperwork utilizing the outlined expression.

On this instance, let’s question all of the paperwork after which simply the one which we’re in search of. We are able to additionally check if the doc exists, utilizing the Exists() methodology. To exhibit this, we’ll first confirm that the doc exists, then find the primary doc with the identify TestName and eventually find all paperwork. To exhibit the final methodology, we’ve added an extra doc of the identical identify however a special worth.

# Check if the `TestName` doc exists
$Assortment.Exists("`$.Title="TestName"")
# Return the primary `TestName` doc discovered
$Assortment.FindOne("`$.Title="TestName"")
# Show all paperwork in a group
$Assortment.FindAll()

Confirm that the doc exists, situated the precise doc, after which all paperwork.

Updating and Eradicating a Doc

Now that we’ve created a doc, let’s replace the worth. That is executed utilizing the aptly named Replace() methodology.

$Merchandise = $Assortment.FindOne("`$.Title="TestName"")

$Merchandise['Value'] = 'UpdatedValue'

Strive {
  # Try and replace the prevailing doc with the up to date worth
  $Assortment.Replace($Merchandise)
} Catch {
  Throw "Unable to replace merchandise."
}

After all, we might not need to maintain this doc. Subsequently, we are able to take away the doc utilizing the Take away() methodology. This requires us to know the ID of the doc. Since we have already got the knowledge within the $Merchandise variable, we are able to leverage the _id property to take away the doc.

Strive {
	# Take away the entry utilizing the _id attribute, inside to the LiteDB database
	$Assortment.Delete($Merchandise['_id'].RawValue)
} Catch {
	Throw "Unable to delete merchandise."
}

Cleansing up the Database and Subsequent Steps

For the reason that database is locked when in use, we have to name the Dispose() methodology to take away the lock. This is a vital step, in any other case, we might find yourself with corruption.

$Database.Dispose()

With that, we’ve demonstrated end-to-end examples of making a database, creating and updating paperwork, and eradicating these paperwork. There are lots of doable makes use of for LiteDB, reminiscent of a brief information assortment database on a server, to a quick and moveable doc storage system that may be simply backed up. Discover LiteDB and see what you are able to do with it right now!



Source link

Uncategorized