Skip to content

Latest commit

 

History

History

_DOCS

README.md

PSLocalBase Documentation & Reference Guide

Welcome to the comprehensive PSLocalBase documentation guide! This document provides everything you need to know about embedded NoSQL document persistence in PowerShell, from a 2-minute quick start to advanced multi-collection sharding, relational joins, and multi-client SMB architecture.


Table of Contents


Quick Start in 2 Minutes

Get up and running with embedded NoSQL persistence in PowerShell in under two minutes:

# Install from PowerShell Gallery (Recommended):
Install-Module -Name PSLocalBase -Scope CurrentUser
Import-Module PSLocalBase

# Option B: Run from Source Code (Local Repository Clone):
# git clone https://github.com/cmartineztech/PSLocalBase.git; cd PSLocalBase
# Import-Module .\PSLocalBase.psd1 -Force

# 1. Initialize embedded database (creates file & parent folder if not present)
$db = [PSLocalBase]::new(".\mydata.db", @{
    cacheSizeMB = 16      # Warm memory cache (default: 16 MB)
    wal         = $true   # High-concurrency WAL mode (default: true)
    depth       = 20      # Max JSON serialization depth (default: 20)
})

# 2. Insert documents (point set with custom key or auto-generated GUID)
$db.collection("users").doc("usr-100").set(@{
    name       = "Carlos Martinez"
    role       = "Admin"
    department = "Engineering"
    active     = $true
    skills     = @("PowerShell", "SQLite", "Cloud")
})

# 3. Read back single document as native [PSCustomObject]
$user = $db.collection("users").doc("usr-100").get()

Write-Host "User: $($user.name) | Role: $($user.role) | Active: $($user.active)"

# 4. Query collection with filtering, ordering, and pipeline formatting
$admins = $db.collection("users").where("role", "=", "Admin").orderBy("name", "asc").get()
$admins | Format-Table name, department, role, active

# 5. Clean close to release file handles
$db.close()

Visual Explorer: Interactive GUI Playground

Prefer a visual tool to explore documents, test queries, and generate PowerShell code with one click? Launch the built-in WPF Playground:

PSLocalBase Playground

pwsh -ExecutionPolicy Bypass -File .\Playground\Playground.ps1
# or
powershell.exe -ExecutionPolicy Bypass -File .\Playground\Playground.ps1
  • Interactive Query Builder: Build and execute .where(), .orderBy(), .limit(), and .count() with immediate feedback.
  • Live PowerShell Code Snippets: Copy generated PowerShell syntax directly to your clipboard.
  • Seed Demo Data: 1-click loading of realistic users, products, and orders datasets.
  • Theme Switching: Sleek dark and light themes with automatic Windows OS theme detection.

1. Installation & Import

PSLocalBase requires zero external dependencies, no NuGet packages, and no binary downloads. It uses Windows' native, pre-installed SQLite engine (winsqlite3.dll).

# Install from PowerShell Gallery (Recommended):
Install-Module -Name PSLocalBase -Scope CurrentUser
Import-Module PSLocalBase

# Option B: Run from Source Code (Local Repository Clone):
# git clone https://github.com/cmartineztech/PSLocalBase.git; cd PSLocalBase
# Import-Module .\PSLocalBase.psd1 -Force

System Requirements & Compatibility

Platform Support Matrix

Tier Operating System / Environment Testing & Support Status
Verified in CI & Local Suites Windows 10 / 11 (x64 & ARM64) Tested on GitHub Actions in parallel on windows-latest (x64) and windows-11-arm (native ARM64) across PowerShell 7.x (Core) and Windows PowerShell 5.1 (Desktop).
Supported by Design Windows Server 2019, 2022, 2025 (x64); WinPE x64 Supported by design via native System32 winsqlite3.dll and .NET Framework 4.5+ / .NET Core runtime.
Architectural Bounds UNC / SMB shares, Non-Windows OS Remote network shares (\\server\share) are explicitly blocked by design for WAL database persistence. Linux and macOS are unsupported.
  • Windows only: "PowerShell 7+" means PowerShell 7 on Windows; importing on Linux or macOS throws PlatformNotSupportedException.
  • CI Test Suite: Continuous integration validates the manifest, runs PSScriptAnalyzer, and executes the 22-suite test runner (_TESTS/run-tests.ps1) and the Playground verification on both PowerShell 7 and Windows PowerShell 5.1 on every push and pull request.
  • Engine Dependency: Relies strictly on Microsoft's native C:\Windows\System32\winsqlite3.dll, pre-installed on modern Windows installations.

2. Database Initialization

Standard File-Based Persistence

Creates or opens a SQLite database file on disk. Parent directories are created automatically if they do not exist.

# Method A: Using the standard class constructor
$db = [PSLocalBase]::new(".\app_data.db")

# Method B: With performance & serialization tuning options
$db = [PSLocalBase]::new(".\app_data.db", @{
    cacheSizeMB = 32      # 32 MB warm page cache (default: 16)
    wal         = $true   # Write-Ahead Logging (default: true)
    depth       = 20      # JSON serialization depth limit (default: 20)
    busyTimeout = 5000    # Retry timeout on locks in ms (default: 5000)
})

In-Memory Ephemeral Database

Lives exclusively in RAM with zero disk footprints. Ideal for testing, temporary caching, and CI/CD pipelines.

$db = [PSLocalBase]::new(":memory:")

Helper Cmdlet: New-LocalBase

You can also initialize instances using standard PowerShell cmdlet syntax:

# In-memory
$db = New-LocalBase

# File-based
$db = New-LocalBase -Path "C:\Data\app.db"

# File-based with options (same keys as the constructor hashtable)
$db = New-LocalBase -Path "C:\Data\app.db" -Options @{ busyTimeout = 10000; synchronous = "FULL" }

Supported options: wal (default $true), synchronous (EXTRA, FULL, NORMAL, OFF; default NORMAL with WAL), busyTimeout (ms, default 5000), cacheSizeMB (default 16), depth (1-100, default 20), maxDocumentBytes (default 16MB), maxReadDepth (default 100) and debug (default $false). Boolean options accept $true/$false or true/false/1/0/yes/no; anything else throws. A closed instance cannot be reopened.


3. Collections & Document Lifecycle

Collections map to isolated SQLite tables. Collection navigation is lazy: referencing a collection ($db.collection("name")) or querying it does not create ghost/empty tables until documents are written.

Collection Navigation (collection)

$col = $db.collection("orders")

Listing Collections (getCollections, listCollections)

Returns an array of all collection names present in the active database:

$names = $db.getCollections()
# Returns: @("users", "products", "orders")

Collection Existence Check (collectionExists)

if (-not $db.collectionExists("audit_logs")) {
    $db.createCollection("audit_logs")
}

Explicit Collection Creation (create, createCollection)

Pre-provisions the collection table in SQLite immediately without requiring initial documents:

# Fluent chaining:
$db.collection("audit_logs").create()

# Direct method:
$db.createCollection("audit_logs")

Targeting Documents (doc)

Targets a document either by its unique string key or by an object/hashtable that names it with key, id or _key. Targeting creates no table; the first write does:

# By string key:
$db.collection("users").doc("usr-100")

# By criteria hashtable:
$db.collection("users").doc(@{ id = "usr-100" })

Writing through a reference leaves it unchanged, so it can be reused:

$user = $db.collection("users").doc("usr-100")
$user.set(@{ name = "Carlos" })
$user.update(@{ role = "Admin" })
$user.get()   # still usr-100

Insert with Custom Key (set)

$db.collection("users").doc("usr-100").set(@{
    name       = "Carlos Martinez"
    role       = "Lead Architect"
    active     = $true
    department = "Engineering"
    skills     = @("PowerShell", "SQLite", "Security")
})

Insert with Auto-Generated GUID (add)

Generates a unique 32-character GUID key and returns it:

$logId = $db.collection("audit_logs").add(@{
    action    = "UserLogin"
    userId    = "usr-100"
    timestamp = (Get-Date).ToString("o")
})
Write-Host "Created audit record with ID: $logId"

Atomic Upsert (upsert)

Inserts the document if it does not exist, or updates it atomically if the key already exists (INSERT ... ON CONFLICT(key) DO UPDATE):

# Upsert with explicit custom key:
$db.collection("devices").upsert(@{ serial = "SN-100"; status = "online" }, "dev-1")

# Upsert with criteria object:
$db.collection("devices").upsert(@{ id = "dev-1"; serial = "SN-100"; status = "online" })

# Or using fluent .doc() chaining:
$db.collection("devices").doc("dev-1").upsert(@{ serial = "SN-100"; status = "standby" })

Replace an Entire Collection (replaceAll)

Atomically replaces every document in the collection with an array of objects. set(@(...)) is an alias:

$products = @(
    @{ id = "prod-1"; name = "Mechanical Keyboard"; price = 120.00; stock = 45 },
    @{ id = "prod-2"; name = "Wireless Mouse";     price = 45.50;  stock = 120 },
    @{ id = "prod-3"; name = "USB-C Hub";           price = 35.00;  stock = 80 }
)
$db.collection("products").replaceAll($products)

Warning

Replacing deletes every existing document, so it is rejected with InvalidOperationException on a query that has where(), orderBy(), limit() or skip(). To change a subset, use where(...).delete() followed by add()/set().

Dates

DateTime and DateTimeOffset values are stored as ISO-8601 UTC strings (2026-01-02T03:04:05.0000000Z) in both PowerShell editions, and the same conversion is applied to where() values, IN lists and query() parameters, so date comparisons are lexical and correct. Reads return the stored text unchanged.

Partial Update / Deep Merge (update)

Performs a deep recursive merge into the targeted document inside a single BEGIN IMMEDIATE transaction (read, merge, write). Existing properties remain untouched, and a missing document is created from the partial data:

$db.collection("users").doc("usr-100").update(@{
    role    = "Principal Architect"
    profile = @{
        title = "Staff Fellow"
    }
})

Atomic Array Mutations (ArrayUnion, ArrayRemove)

Apply array mutations as part of update()'s transactional read, deep merge and whole-document write:

# Add tags without duplicates
$db.collection("users").doc("usr-100").update(@{
    skills = [PSLocalBase]::ArrayUnion("C#", "Security")
})

# Remove elements from array
$db.collection("users").doc("usr-100").update(@{
    skills = [PSLocalBase]::ArrayRemove("Security")
})

# Descriptor syntax also supported
$db.collection("users").doc("usr-100").update(@{
    skills = @{ '$arrayUnion' = @("CloudArchitecture") }
})

Tip

Numeric Precision & Subnormals: ArrayUnion and ArrayRemove perform exact 64-bit integer comparisons and preserve floating-point values below Decimal resolution (|Double| < 1e-28), preventing quantization loss and collisions between Double and Decimal types.

Secondary Expression Indexes (createIndex, dropIndex)

Create native B-Tree expression indexes on document JSON fields. Query speed depends on the plan and dataset; guarded fluent extraction may not use these indexes (see the numeric comparison domain):

# Standard secondary expression index on a JSON field
$db.collection("users").createIndex("role")

# Unique constraint index (throws on duplicate values); $true is shorthand for @{ unique = $true }
$db.collection("users").createIndex("email", @{ unique = $true })

# Descending index
$db.collection("orders").createIndex("createdAt", @{ order = "desc" })

# Drop the index for a field (the argument is the field, not an index name)
$db.collection("users").dropIndex("role")

Index names are generated internally from the collection and field (idx_<collection>__<field>_<hash>).

Storage Integrity & Validation (validate)

Every collection table is created with a strict table-level constraint:

doc TEXT NOT NULL CHECK (json_valid(doc))

To scan a collection's JSON validity, call validate(). It returns a [bool]: $true when no document is NULL or invalid JSON (and for a collection that does not exist yet), $false otherwise. It does not validate the entire SQLite file or enforce an application schema:

if (-not $db.collection("users").validate()) {
    $bad = $db.query("SELECT key FROM users WHERE doc IS NULL OR json_valid(doc) = 0;")
    Write-Warning "Invalid documents: $($bad.key -join ', ')"
}

Deleting Documents & Dropping Collections (delete, drop)

# Delete single targeted document
$db.collection("users").doc("usr-100").delete()

# Delete matching filtered documents
$db.collection("audit_logs").where("timestamp", "<", (Get-Date).AddDays(-30)).delete()

# Truncate all records from collection (preserves table schema and indexes)
$db.collection("temporary_data").delete()

# Drop entire collection table
$db.collection("temporary_data").drop()

drop() always removes the entire selected table, even if a key, filter, ordering or pagination is present. It is rejected on union and collection-group queries. delete() rejects ordering/pagination and composite queries; a key and filters are combined with AND. Filtered point set(), update() and upsert() are rejected rather than ignoring filters.


4. Querying & Filtering

Point Lookups

Retrieves the stored JSON value by key: object documents become [PSCustomObject], while arrays, scalars and null retain their value shape. A missing document also returns $null; use get(@{ keys = $true }) or exists() to distinguish stored null from absence. Point lookups honor limit() and skip() clauses (for example, .limit(0) or .skip(1) returns $null).

$user = $db.collection("users").doc("usr-100").get()

Collection-Wide Retrieval

$allUsers = $db.collection("users").get()

First Matching Record (first)

Applies limit(1) to a cloned query and returns the first result or $null. For an array-valued point document, first() returns the array's first element; use point get() or first(@{ keys = $true }) to preserve the whole document. The selected result is still materialized:

$admin = $db.collection("users").where("role", "==", "Admin").first()

Existence Verification (exists)

Checks whether a matching record exists. Ordinary unpaged collection queries use SELECT 1 ... LIMIT 1; point and paged queries use a count, while unions can retrieve and deserialize a result. Key lookups use the primary-key index; an unindexed filter can scan records:

# Point lookup existence
if ($db.collection("users").doc("usr-100").exists()) {
    Write-Host "User exists!"
}

# Query existence
if ($db.collection("products").where("stock", "<=", 0).exists()) {
    Write-Host "Warning: Out-of-stock items detected."
}

Selective Field Projection (select)

Extracts and builds smaller JSON objects directly inside SQLite's C engine, reducing memory overhead:

$users = $db.collection("users").select("name", "department").get()

Repeated select() calls accumulate fields. A dotted path such as profile.city becomes a literal output property named profile.city (access it as $user.'profile.city'), rather than rebuilding a nested object.

Distinct Values (distinct)

distinct() rejects limit, skip and orderBy modifiers rather than ignoring them; point keys and filters are respected. See the numeric comparison domain for precision limits. It excludes null/missing values, sorts ascending using SQLite ordering, and rejects union and collection-group queries. Retrieves deduplicated typed values using SQLite DISTINCT; an index scan is not guaranteed:

$roles = $db.collection("users").distinct("role")
# Returns: @("Admin", "Developer", "Manager")

Filtering with where()

Supports chained filtering pushed down directly to SQLite's json_extract():

# Numeric comparisons
$db.collection("products").where("price", "<=", 50.00).get()

# Equality
$db.collection("users").where("active", "==", $true).get()

# String wildcards (LIKE)
$db.collection("users").where("name", "LIKE", "%Martinez%").get()

# Set inclusion (IN)
$db.collection("users").where("role", "IN", @("Admin", "Lead Architect")).get()

# Set exclusion (not-in)
$db.collection("users").where("role", "not-in", @("Guest", "Disabled")).get()

# Dates are compared as ISO-8601 UTC text; pass [datetime] values directly
$db.collection("audit_logs").where("timestamp", ">=", (Get-Date).AddDays(-7)).get()

# Nested dot paths
$db.collection("orders").where("shipping.address.city", "==", "Seattle").get()

IN with a $null member also matches documents where the field is null or missing. not-in only matches documents where the field is present and not null (an empty list therefore returns every document with a present, non-null field); $null members are ignored.

Numeric parameters and stored values used by guarded JSON extraction must satisfy the numeric comparison domain. Unsupported values raise errors instead of silently rounding; this can also affect sorting, projection, membership, aggregates and index creation.

Scalar null comparisons follow SQLite JSON semantics: .where("field", "=", $null) matches both explicit JSON nulls and missing fields; .where("field", "!=", $null) matches only present, non-null values. .whereType("field", "null") matches explicit JSON nulls only. These rules also apply to deep dot paths.

Array Membership & Intersection (array-contains, array-contains-any)

# Check if array contains a specific item
$devs = $db.collection("users").where("skills", "array-contains", "PowerShell").get()

# Check if array intersects with a set of items
$specialists = $db.collection("users").where("skills", "array-contains-any", @("Security", "Cloud")).get()

Array Length Filtering (whereLength, length)

Evaluates array size directly in C using SQLite's json_array_length():

# Dedicated fluent method: whereLength(field, operator, count); operators =, !=, >, >=, <, <=
$db.collection("orders").whereLength("items", ">", 3).get()
$db.collection("users").whereLength("skills", 5).get()   # exactly 5

# Operator syntax inside .where(): length, length>, length>=, length<, length<=, length!=
$db.collection("users").where("skills", "length", 5).get()
$db.collection("orders").where("items", "length>", 3).get()

Missing fields, JSON null and non-array values are treated as length zero. Unknown whereLength() operators throw ArgumentException.

Data Type Filtering (whereType, type)

Inspects dynamic document schemas using SQLite's json_type() (null, integer, real, text, array, object, true, false), plus the groups number (integer or real) and boolean (true or false):

# Dedicated fluent method: whereType(field, type)
$db.collection("events").whereType("metadata", "object").get()
$db.collection("flags").whereType("enabled", "boolean").get()

# Operator syntax inside .where()
$db.collection("metrics").where("value", "type", "integer").get()

Field Existence Filtering (whereExists, whereMissing, exists)

Query whether a document possesses or omits a field regardless of its value:

# Shorthand helper methods:
$missingEmail = $db.collection("users").whereMissing("email").get()
$hasPhone = $db.collection("users").whereExists("contact.phone").get()

# Operator syntax inside where():
$activeConfig = $db.collection("configs").where("featureFlags.beta", "exists", $true).get()
$unmigrated = $db.collection("records").where("schemaVersion", "missing", $true).get()

Array Index Filtering

Target specific array offsets using standard JSONPath indexing:

$db.collection("orders").where("items[0].sku", "==", "KB-100").get()

Counting Records (count)

# Total collection count
$totalUsers = $db.collection("users").count()

# Filtered count
$adminCount = $db.collection("users").where("role", "==", "Admin").count()

Mathematical Aggregations (sum, avg, min, max)

Performs calculations directly inside the native SQLite engine without bringing documents into PowerShell:

$totalSales = $db.collection("orders").sum("totalAmount")
$averageAge = $db.collection("users").avg("age")
$cheapest   = $db.collection("products").min("price")
$latestDate = $db.collection("audit_logs").max("timestamp")

sum() and avg() only use JSON numbers; text, booleans and nulls are ignored rather than counted as 0. min() and max() compare JSON numbers numerically and return them as [long] or [double]; when a field holds no numbers they compare text and return a string (which is how ISO-8601 dates work).

Empty numeric input returns 0.0 for sum()/avg(); no numeric or text input returns $null for min()/max(). These four methods reject pagination, union and collection-group queries, and honor point keys and filters. count() separately supports pagination and composite queries.

Sorting & Pagination (orderBy, skip, limit)

$pagedUsers = $db.collection("users").`
    where("active", "==", $true).`
    orderBy("name", "asc").`
    skip(20).`
    limit(10).`
    get()

Exposing Primary Keys (keys = $true)

$records = $db.collection("users").get(@{ keys = $true })
foreach ($r in $records) {
    Write-Host "Key: $($r.key) | Data: $($r.data.name)"
}

Query Immutability, Reusability & Branch Forking (clone, fork)

Query modifiers (where(), whereLength(), whereType(), whereExists(), whereMissing(), orderBy(), limit(), skip(), select(), populate()) are strictly immutable: each call returns a new isolated child query instance without modifying the parent.

Furthermore, terminal methods (get(), count(), exists(), distinct(), sum(), avg(), min(), max()) are non-destructive and do not wipe filters:

# Define base query
$activeUsers = $db.collection("users").where("active", "==", $true)

# Reuse the query definition multiple times
$totalActive = $activeUsers.count()
$firstActive = $activeUsers.first()

# Safely branch / fork without mutating $activeUsers
$adminUsers = $activeUsers.where("role", "==", "Admin").get()
$guestUsers = $activeUsers.where("role", "==", "Guest").get()

# Explicit clone / fork
$customBranch = $activeUsers.clone().orderBy("name", "asc")

5. Relational Lookups with .populate()

Resolve foreign keys and joins across collections in a single native SQLite query, completely eliminating N+1 loop queries:

The foreign field stores the other document's storage key. A missing match produces a null populated property. populate() is rejected on union() and collectionGroup() queries.

# Embed customer user document into the order object
$ordersWithCustomers = $db.collection("orders").`
    populate("customerId", "users", "customer").`
    get()

foreach ($order in $ordersWithCustomers) {
    Write-Host "Order: $($order.orderId) | Placed By: $($order.customer.name)"
}

6. Compound Queries & Sharding (union, unionAll, collectionGroup)

Compound Queries (union, unionAll)

Merge results across multiple distinct collections into a unified query:

$activeQuery = $db.collection("active_orders").where("total", ">", 100)
$archiveQuery = $db.collection("archived_orders").where("total", ">", 100)

# Deduplicated UNION
$allBigOrders = $activeQuery.union($archiveQuery).orderBy("total", "desc").get()

# High-speed UNION ALL (without deduplication)
$allOrders = $activeQuery.unionAll($archiveQuery).get()

Sharded Querying (collectionGroup)

Query across multiple collections matching a wildcard pattern (e.g. date-sharded logs or region tables). Matching tables are resolved each time the query runs, so collections created or dropped later are reflected. The returned view adds ._collection with the origin table, replacing any stored property of that name; projections can omit it. It can also be filtered with where("_collection", "=", "logs_2026_01"). A collection group cannot be combined with union()/unionAll():

$criticalErrors = $db.collectionGroup("logs_2026_*").`
    where("level", "==", "CRITICAL").`
    orderBy("timestamp", "desc").`
    limit(50).`
    get()

foreach ($err in $criticalErrors) {
    Write-Host "[$($err._collection)] $($err.timestamp): $($err.message)"
}

Note

Snapshot Isolation: Calling .union() or .unionAll() creates an immutable snapshot of both query branches via .clone(). Modifying source branches afterwards does not alter the composite query. Nested unions are prohibited.

Branch modifiers applied before composition remain local to that branch. Filters, ordering, projection and pagination applied after composition operate on the combined result once. -like/-notlike use the host PowerShell wildcard matcher through a SQLite scalar function with complete UTF-16 values, including NUL; SQL LIKE remains SQLite-native. Bracket classes remain unsupported and SQL NULL predicate behavior is preserved. Start a new PowerShell session after upgrading the native bridge.

Sharded Drop Protection: Calling .drop() on collectionGroup() is strictly prohibited and throws [System.InvalidOperationException] to prevent accidental mass deletion across wildcard-matched tables.


7. Raw Cross-Collection Queries (query)

Execute arbitrary SQL statements across collections when complex joins, CTEs, or custom SQLite JSON expressions are required:

$sql = @"
SELECT 
    json_extract(o.doc, '$.orderId') AS orderId,
    json_extract(u.doc, '$.name') AS customerName,
    json_extract(o.doc, '$.total') AS total
FROM orders o
JOIN users u ON json_extract(o.doc, '$.customerId') = u.key
WHERE CAST(json_extract(o.doc, '$.total') AS REAL) > 100.0
ORDER BY total DESC;
"@

$results = $db.query($sql)
$results | Format-Table orderId, customerName, total

query() runs exactly one statement and rejects any further statement after the first ;. Treat it as trusted code: build the SQL yourself and pass every external value through the parameter array ($db.query("... WHERE key = ?", @($key))). Error messages include the SQL text only when debug is enabled.


8. Atomic ACID Transactions

Wrap multi-document operations in high-performance atomic transactions:

$db.beginTransaction()
try {
    $db.collection("accounts").doc("acc-1").update(@{ balance = 400 })
    $db.collection("accounts").doc("acc-2").update(@{ balance = 600 })
    $db.commit()
    Write-Host "Funds transferred successfully."
} catch {
    $db.rollback()
    Write-Warning "Transfer failed, rolling back changes: $_"
}

beginTransaction() issues BEGIN IMMEDIATE: the write lock is taken at the start, so another process writing to the same file makes it wait up to busyTimeout instead of failing with database is locked when the transaction first writes. beginTransaction('deferred') and beginTransaction('exclusive') select the other SQLite modes.


9. Production Best Practice: try / finally

Always encapsulate database operations in a try / finally block to guarantee immediate connection closure and file handle release:

$db = [PSLocalBase]::new(".\production.db")
try {
    $db.collection("metrics").add(@{
        cpu  = (Get-CimInstance Win32_Processor).LoadPercentage
        date = (Get-Date).ToString("o")
    })
} finally {
    # Guaranteed cleanup: ensures file lock release even on unhandled exceptions
    $db.close()
}

Deleting a Database Completely (deleteDatabase)

To delete the active SQLite database file and its associated journal files (-wal, -shm, -journal), invoke .deleteDatabase() directly from the root database instance. The path comes from SQLite itself:

$db = [PSLocalBase]::new(".\temporary.db")
$db.collection("cache").add(@{ token = "xyz" })
# Closes handle and deletes .\temporary.db and its -wal, -shm and -journal files
$db.deleteDatabase()

An instance that is never closed is released by the garbage collector through a SafeHandle finalizer, but only close()/Dispose() release the file lock at a predictable moment.


10. PowerShell Pipeline Integration & Object Standard

Query builders (select(), populate(), collectionGroup(), union()) return PSLocalBase query instances; call get() or first() to materialize results. Object-shaped JSON documents become native [PSCustomObject] values, while arrays, scalars and null retain their JSON shape. Aggregates and exists() return their own scalar types.

get() materializes its selected result set before passing values down a PowerShell pipeline. Use bounded paging for large collections:

# 1. Filter and export directly to CSV
$db.collection("products").where("stock", ">", 0).get() |
    Select-Object id, name, price, stock |
    Export-Csv -Path ".\inventory.csv" -NoTypeInformation

# 2. Interactive Windows GridView
$db.collection("users").get() | Out-GridView -Title "Active Users Directory"

# 3. Pipeline grouping & sorting
$db.collectionGroup("logs_2026_*").get() |
    Group-Object _collection |
    Select-Object Name, Count

🛠️ Native PowerShell Cmdlets (PSLocalBase.Cmdlets.ps1)

The adapter is included in release 2.1.0 on main and in the PowerShell Gallery package; no dev checkout is required.

In addition to the Fluent API, PSLocalBase includes a 100% native PowerShell Cmdlet adapter with pipeline integration (Add-LocalBaseDocument, Get-LocalBaseDocument, Update-LocalBaseDocument, Remove-LocalBaseDocument), -WhatIf safety, and short interactive aliases (gld, ald, uld, rld).

👉 Complete Cmdlet Documentation: For the full reference, parameter matrices, and automation scripts, see CMDLETS.md.


11. Reading Over SMB / Network Shares

PSLocalBase enforces local drive access and strictly rejects UNC (\\server\share) and mapped network paths because SQLite's default Write-Ahead Logging (WAL) mode relies on shared memory (.db-shm) and OS-level locking primitives that network shares cannot safely coordinate.

Why Direct SMB Access is Blocked

Opening a live SQLite database directly over SMB invites locking deadlocks and silent database corruption. Furthermore, simply copying a live .db file while a writer has active WAL transactions leaves committed changes in .db-wal, producing an incomplete or stale copy.

Writer Pattern: Publishing Consistent Snapshots via VACUUM INTO

To safely distribute databases across network shares, the writer process exports a clean, completed snapshot directly using SQLite's native VACUUM INTO, then publishes the finished snapshot file to the share:

# 1. On the writer server: export consistent snapshot from live WAL DB
$snapshot = 'C:\Staging\catalog_snapshot.db' # Parent must exist; destination must not already exist
$db.query('VACUUM INTO ?;', @($snapshot)) # Run outside an active transaction

# 2. Publish under a unique name; clients consume only after this copy completes
$published = "\\server\share\catalog_$([guid]::NewGuid().ToString('N')).db"
Copy-Item -LiteralPath $snapshot -Destination $published -ErrorAction Stop
# Make $published available to clients only after Copy-Item succeeds.

Client Pattern: Safe Local Temp Consumption

Clients copy a completed, immutable published snapshot to a unique local temporary file, query the local copy, and clean up in finally. A cross-volume Move-Item or overwrite of a shared filename does not guarantee atomic publication. Coordinate distribution of the completed snapshot path with clients:

$smbSnapshot = $published # Completed immutable path supplied by the publisher
$tempPath    = Join-Path ([System.IO.Path]::GetTempPath()) ("pslocalbase_" + [System.Guid]::NewGuid().ToString("N") + ".db")

try {
    # 1. Copy snapshot to unique local temporary storage
    Copy-Item -LiteralPath $smbSnapshot -Destination $tempPath -Force

    # 2. Query at full local speed with zero network contention
    $db = [PSLocalBase]::new($tempPath)
    try {
        $products = $db.collection("hardware").where("inStock", "==", $true).get()
        $products | Format-Table id, name, price
    } finally {
        $db.close()
    }
} finally {
    if (Test-Path $tempPath) {
        Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
    }
}

Related Documentation