Repository navigation
Expand file tree
/
Copy pathPSLocalBase.Cmdlets.ps1
More file actions
950 lines (815 loc) · 32 KB
/
Copy pathPSLocalBase.Cmdlets.ps1
File metadata and controls
950 lines (815 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
<#
.SYNOPSIS
PSLocalBase.Cmdlets.ps1 - Native PowerShell Cmdlet & Pipeline Adapter for PSLocalBase.
.DESCRIPTION
Provides an idiomatic PowerShell cmdlet interface (Verb-Noun, pipeline integration,
-WhatIf, -Confirm, tab completion) built as a PowerShell adapter on top
of the PSLocalBase fluent engine.
Preserves 100% interoperability with the primary fluent API ($db.collection().get()).
#>
# ---------------------------------------------------------------------------
# Module Execution Context & Session Management
# ---------------------------------------------------------------------------
$script:CurrentLocalBaseConnection = $null
# Identity is separate from payload properties, including colliding metadata names.
$script:LocalBaseIdentity = [System.Runtime.CompilerServices.ConditionalWeakTable[object, object]]::new()
function Register-LocalBaseDocumentIdentity {
param($Document, [string]$Collection, [string]$Id, [bool]$Wrapped = $false)
$original = @{}
foreach ($name in @('_localbase_collection', '_localbase_key')) {
if ($Document.PSObject.Properties[$name]) { $original[$name] = $Document.$name }
}
$syntheticId = -not $Document.PSObject.Properties['id']
$script:LocalBaseIdentity.Add($Document, @{ Collection = $Collection; Id = $Id; Original = $original; SyntheticId = $syntheticId; Wrapped = $Wrapped })
Add-Member -InputObject $Document -NotePropertyName '_localbase_collection' -NotePropertyValue $Collection -Force
Add-Member -InputObject $Document -NotePropertyName '_localbase_key' -NotePropertyValue $Id -Force
if ($syntheticId) { Add-Member -InputObject $Document -NotePropertyName 'id' -NotePropertyValue $Id }
}
function Resolve-LocalBaseDocumentIdentity {
param($Document, [string]$Collection, [string]$Id)
$identity = $null
if ($null -ne $Document) { $null = $script:LocalBaseIdentity.TryGetValue($Document, [ref]$identity) }
if (-not $Collection) {
if ($identity) { $Collection = $identity.Collection }
elseif ($Document.Collection) { $Collection = $Document.Collection }
elseif ($Document._localbase_collection) { $Collection = $Document._localbase_collection }
}
if (-not $Id) {
if ($identity) { $Id = $identity.Id }
else {
foreach ($name in @('id', '_key', 'key', '_localbase_key')) {
if ($Document.$name) { $Id = $Document.$name; break }
}
}
}
return @{ Collection = $Collection; Id = $Id }
}
function ConvertTo-LocalBasePayload {
param($Document)
$identity = $null
if ($null -ne $Document -and $script:LocalBaseIdentity.TryGetValue($Document, [ref]$identity)) {
if ($identity.Wrapped) { return ,$Document.Value }
$clean = $Document.PSObject.Copy()
foreach ($name in @('_localbase_collection', '_localbase_key')) {
$clean.PSObject.Properties.Remove($name)
if ($identity.Original.ContainsKey($name)) {
Add-Member -InputObject $clean -NotePropertyName $name -NotePropertyValue $identity.Original[$name]
}
}
if ($identity.SyntheticId) { $clean.PSObject.Properties.Remove('id') }
return ,$clean
}
return ,$Document
}
function Get-LocalBaseExecutionContext {
[CmdletBinding()]
param(
[Parameter()]
$Database
)
if ($Database) {
return $Database
}
if ($script:CurrentLocalBaseConnection -and $script:CurrentLocalBaseConnection.DbHandle -ne [System.IntPtr]::Zero) {
return $script:CurrentLocalBaseConnection
}
throw [System.InvalidOperationException]::new(
"No active PSLocalBase database connection found. Use 'Connect-LocalBase -Path <path>' to connect, or pass -Database explicitly."
)
}
# ---------------------------------------------------------------------------
# 1. Connection & Database Management Cmdlets
# ---------------------------------------------------------------------------
function Connect-LocalBase {
<#
.SYNOPSIS
Connects to a PSLocalBase SQLite database and sets it as the active session connection.
.DESCRIPTION
Opens an existing SQLite database file or automatically creates and provisions
a new database file on demand if it does not yet exist. Sets the connection
as the ambient session default for all downstream pipeline cmdlets.
Successful replacement closes the previous ambient connection and rolls back
its uncommitted work. Failed opening leaves the previous connection intact.
Defaults: BusyTimeoutMs 5000, JournalMode WAL, Synchronous NORMAL.
Emits no object unless -PassThru is specified. Use New-LocalBase to create
independent connections without replacing the ambient connection.
.EXAMPLE
Connect-LocalBase -Path "./data.db"
.EXAMPLE
Connect-LocalBase -Path ":memory:"
#>
[CmdletBinding()]
[Alias('Open-LocalBase')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Path,
[Parameter()]
[ValidateRange(0, 2147483647)]
[int]$BusyTimeoutMs = 5000,
[Parameter()]
[ValidateSet('WAL', 'DELETE')]
[string]$JournalMode = 'WAL',
[Parameter()]
[ValidateSet('NORMAL', 'FULL', 'OFF', 'EXTRA')]
[string]$Synchronous = 'NORMAL',
[Parameter()]
[switch]$PassThru
)
$opts = @{
busyTimeout = $BusyTimeoutMs
wal = ($JournalMode -eq 'WAL')
synchronous = $Synchronous
}
# Opening/validating may throw. Keep the original ambient connection and transaction intact.
$db = New-LocalBase -Path $Path -Options $opts
try {
if ($script:CurrentLocalBaseConnection) { $script:CurrentLocalBaseConnection.close() }
} catch {
$db.close()
throw
}
$script:CurrentLocalBaseConnection = $db
if ($PassThru) {
return $db
}
}
function Disconnect-LocalBase {
<#
.SYNOPSIS
Closes the active PSLocalBase connection and releases all file locks.
.EXAMPLE
Disconnect-LocalBase
#>
[CmdletBinding()]
[Alias('Close-LocalBase')]
param(
[Parameter()]
$Database
)
$targetDb = if ($Database) { $Database } else { $script:CurrentLocalBaseConnection }
if ($targetDb) {
$targetDb.close()
if ($targetDb -eq $script:CurrentLocalBaseConnection) {
$script:CurrentLocalBaseConnection = $null
}
}
}
function Get-LocalBaseConnection {
<#
.SYNOPSIS
Gets the active PSLocalBase connection for the current session.
.DESCRIPTION
Returns the ambient object, or nothing if none is set. Closing it directly
with .close() does not clear this reference; Disconnect-LocalBase does.
#>
[CmdletBinding()]
param()
return $script:CurrentLocalBaseConnection
}
function Backup-LocalBaseDatabase {
<#
.SYNOPSIS
Performs a live, consistent online backup using SQLite VACUUM INTO.
.DESCRIPTION
Resolves relative destinations from the current PowerShell location.
Requires an existing parent directory and an absent or empty destination.
Cannot run inside an active transaction. Returns no object.
.EXAMPLE
Backup-LocalBaseDatabase -DestinationPath "./backup.db"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$DestinationPath,
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
$resolvedPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DestinationPath)
$cleanPath = $resolvedPath -replace "'", "''"
$null = $ctx.query("VACUUM INTO '$cleanPath';")
}
function Remove-LocalBaseDatabase {
<#
.SYNOPSIS
Deletes a database file and its -wal, -shm, and -journal sidecars.
.DESCRIPTION
Close all connections first. Active or inaccessible files cause an error;
this command does not close connections. Force permits read-only removal,
but does not bypass active-file checks, WhatIf, or confirmation. Missing
files are ignored; directories are rejected. Multi-file removal is not atomic.
.EXAMPLE
Remove-LocalBaseDatabase -Path "./old.db" -Confirm:$false
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Path,
[Parameter()]
[switch]$Force
)
$resolved = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
if ($PSCmdlet.ShouldProcess($resolved, "Delete database file and SQLite journals")) {
$targets = @($resolved, "$resolved-wal", "$resolved-shm", "$resolved-journal")
$locks = [System.Collections.Generic.List[System.IDisposable]]::new()
try {
# Check every file before removing any. Active SQLite handles prevent
# exclusive access, including connections outside the ambient context.
foreach ($target in $targets) {
if (Test-Path -LiteralPath $target -ErrorAction Stop) {
$item = Get-Item -LiteralPath $target -Force -ErrorAction Stop
if ($item.PSIsContainer) { throw "Database path is a directory: '$target'." }
if ($item.IsReadOnly -and -not $Force) { throw "Database file '$target' is read-only. Use -Force to remove it." }
$locks.Add([System.IO.File]::Open($target, 'Open', 'Read', 'None'))
}
}
} catch {
throw [System.IO.IOException]::new("Cannot remove database '$resolved'. Close all connections and check file permissions. $($_.Exception.Message)", $_.Exception)
} finally {
foreach ($fileLock in $locks) { $fileLock.Dispose() }
}
foreach ($target in $targets) {
if (Test-Path -LiteralPath $target -ErrorAction Stop) {
Remove-Item -LiteralPath $target -Force:$Force -ErrorAction Stop
}
}
}
}
# ---------------------------------------------------------------------------
# 2. Collection & Index Lifecycle Cmdlets
# ---------------------------------------------------------------------------
function Get-LocalBaseCollection {
<#
.SYNOPSIS
Lists all collections present in the active database.
#>
[CmdletBinding()]
param(
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
return $ctx.getCollections()
}
function New-LocalBaseCollection {
<#
.SYNOPSIS
Explicitly provisions a collection table in the database schema.
.EXAMPLE
New-LocalBaseCollection -Name "customers"
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Name,
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
if ($PSCmdlet.ShouldProcess($Name, "Create collection")) { $null = $ctx.createCollection($Name) }
}
function Remove-LocalBaseCollection {
<#
.SYNOPSIS
Drops a collection table and all associated indexes from the database.
.EXAMPLE
Remove-LocalBaseCollection -Collection "temp_data" -Confirm:$false
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Collection,
[Parameter()]
$Database
)
if ($PSCmdlet.ShouldProcess($Collection, "Drop collection table and associated index metadata")) {
$ctx = Get-LocalBaseExecutionContext -Database $Database
$null = $ctx.collection($Collection).drop()
}
}
function Clear-LocalBaseCollection {
<#
.SYNOPSIS
Truncates/empties all documents in a collection while preserving its schema table and indexes.
.EXAMPLE
Clear-LocalBaseCollection -Collection "logs" -Confirm:$false
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Collection,
[Parameter()]
$Database
)
if ($PSCmdlet.ShouldProcess($Collection, "Delete all documents in collection")) {
$ctx = Get-LocalBaseExecutionContext -Database $Database
$null = $ctx.collection($Collection).delete()
}
}
function New-LocalBaseIndex {
<#
.SYNOPSIS
Creates a secondary or unique expression index on a document field.
.EXAMPLE
New-LocalBaseIndex -Collection "users" -Field "email" -Unique
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Collection,
[Parameter(Mandatory = $true, Position = 1)]
[string]$Field,
[Parameter()]
[switch]$Unique,
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
if ($PSCmdlet.ShouldProcess("$Collection/$Field", "Create index")) { $null = $ctx.collection($Collection).createIndex($Field, [bool]$Unique) }
}
function Remove-LocalBaseIndex {
<#
.SYNOPSIS
Drops a secondary index on a collection field.
.EXAMPLE
Remove-LocalBaseIndex -Collection "users" -Field "email"
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Collection,
[Parameter(Mandatory = $true, Position = 1)]
[string]$Field,
[Parameter()]
$Database
)
if ($PSCmdlet.ShouldProcess("$Collection/$Field", "Drop secondary index")) {
$ctx = Get-LocalBaseExecutionContext -Database $Database
$null = $ctx.collection($Collection).dropIndex($Field)
}
}
# ---------------------------------------------------------------------------
# 3. Document CRUD & Pipeline Cmdlets
# ---------------------------------------------------------------------------
function Get-LocalBaseDocument {
<#
.SYNOPSIS
Materializes selected documents, then emits each document to the pipeline.
Use -First/-Skip to bound reads; downstream Select-Object -First does not reduce database reading.
.DESCRIPTION
JSON objects expose their payload properties. Top-level arrays, scalars and null
expose the payload in Value. Set/Add unwrap these trusted envelopes; Remove uses
their private identity. Missing point reads emit no item. Distinct rejects paging
and ordering modifiers. Unsupported numeric comparisons throw instead of rounding.
Filter entries use equality and combine with Field, Exists and Missing using AND.
Operator defaults to ==. Count counts after First/Skip, takes precedence over
Distinct, and ignores Select. Distinct ignores Select. A projected document
piped to Set replaces the entire stored payload with that projection.
.EXAMPLE
Get-LocalBaseDocument -Collection "users" -Id "usr_100"
.EXAMPLE
Get-LocalBaseDocument -Collection "users" -Filter @{ role = 'Admin' } -OrderBy 'age' -Descending -First 10
.EXAMPLE
Get-LocalBaseDocument -Collection "items" -Field "price" -Operator ">=" -Value 50
#>
[CmdletBinding(DefaultParameterSetName = 'Query')]
[Alias('gld')]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Collection,
[Parameter(Mandatory = $true, ParameterSetName = 'ById', Position = 1)]
[string]$Id,
[Parameter(ParameterSetName = 'Query')]
[hashtable]$Filter,
[Parameter(ParameterSetName = 'Query')]
[string]$Field,
[Parameter(ParameterSetName = 'Query')]
[string]$Operator = '==',
[Parameter(ParameterSetName = 'Query')]
[object]$Value,
[Parameter(ParameterSetName = 'Query')]
[string]$Exists,
[Parameter(ParameterSetName = 'Query')]
[string]$Missing,
[Parameter(ParameterSetName = 'Query')]
[string]$OrderBy,
[Parameter(ParameterSetName = 'Query')]
[switch]$Descending,
[Parameter(ParameterSetName = 'Query')]
[int]$First,
[Parameter(ParameterSetName = 'Query')]
[int]$Skip,
[Parameter()]
[string[]]$Select,
[Parameter(ParameterSetName = 'Query')]
[string]$Distinct,
[Parameter(ParameterSetName = 'Query')]
[switch]$Count,
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
$col = $ctx.collection($Collection)
# Point Lookup by Id
if ($PSCmdlet.ParameterSetName -eq 'ById') {
$q = $col.doc($Id)
if ($Select) {
$q = $q.select($Select)
}
$entry = $q.get(@{ keys = $true })
if ($null -ne $entry) {
$doc = $entry.data
$wrapped = $null -eq $doc -or $doc -isnot [System.Management.Automation.PSCustomObject]
if ($wrapped) { $doc = [pscustomobject]@{ Value = $doc } }
Register-LocalBaseDocumentIdentity -Document $doc -Collection $Collection -Id $Id -Wrapped $wrapped
$PSCmdlet.WriteObject($doc, $false)
}
return
}
$q = $col
# Apply Filter hashtable
if ($Filter) {
foreach ($k in $Filter.Keys) {
$q = $q.where($k, '==', $Filter[$k])
}
}
# Apply explicit field filter
if ($Field) {
$q = $q.where($Field, $Operator, $Value)
}
# Apply Exists / Missing
if ($Exists) {
$q = $q.whereExists($Exists)
}
if ($Missing) {
$q = $q.whereMissing($Missing)
}
# Apply OrderBy
if ($OrderBy) {
$dir = if ($Descending) { 'desc' } else { 'asc' }
$q = $q.orderBy($OrderBy, $dir)
}
# Apply Skip & First
if ($PSBoundParameters.ContainsKey('Skip')) {
$q = $q.skip($Skip)
}
if ($PSBoundParameters.ContainsKey('First')) {
$q = $q.limit($First)
}
# Return Count directly if requested
if ($Count) {
return $q.count()
}
# Return Distinct values if requested
if ($Distinct) {
return $q.distinct($Distinct)
}
# Apply Select projection
if ($Select) {
$q = $q.select($Select)
}
$results = $q.get(@{ keys = $true })
if ($null -eq $results) { return }
# Emit the already materialized results through the pipeline
foreach ($entry in $results) {
if ($null -ne $entry) {
$item = $entry.data
$wrapped = $null -eq $item -or $item -isnot [System.Management.Automation.PSCustomObject]
if ($wrapped) { $item = [pscustomobject]@{ Value = $item } }
Register-LocalBaseDocumentIdentity -Document $item -Collection $Collection -Id $entry.key -Wrapped $wrapped
$PSCmdlet.WriteObject($item, $false)
}
}
}
function Add-LocalBaseDocument {
<#
.SYNOPSIS
Inserts one or more documents into a collection. Supports pipeline streaming.
.DESCRIPTION
Returns one storage key for each insert. Id must be new; duplicates throw.
Without Id a GUID is generated. Accepts JSON null and empty arrays. Each
input is written independently; use Invoke-LocalBaseTransaction for a batch.
.EXAMPLE
Add-LocalBaseDocument -Collection "users" -Data @{ name = 'Carlos'; role = 'Admin' }
.EXAMPLE
Get-Process | Add-LocalBaseDocument -Collection "processes"
#>
[CmdletBinding()]
[Alias('ald')]
param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipelineByPropertyName = $true)]
[string]$Collection,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)]
[AllowNull()]
[AllowEmptyCollection()]
[object]$Data,
[Parameter(Position = 2)]
[string]$Id,
[Parameter()]
$Database
)
process {
$cleanData = ConvertTo-LocalBasePayload $Data
$ctx = Get-LocalBaseExecutionContext -Database $Database
$col = $ctx.collection($Collection)
if ($Id) {
return $col.add($cleanData, $Id)
} else {
return $col.add($cleanData)
}
}
}
function Set-LocalBaseDocument {
<#
.SYNOPSIS
Sets/replaces a document with a specific key, or upserts if it does not exist.
.DESCRIPTION
Collection and Id may be explicit or resolved from each input object's
identity. Data binds from the pipeline and replaces the entire payload.
Accepts JSON null and empty arrays. Emits no result object.
.EXAMPLE
Set-LocalBaseDocument -Collection "users" -Id "usr_1" -Data @{ name = 'Carlos'; active = $true }
.EXAMPLE
$user.status = 'Inactive'
$user | Set-LocalBaseDocument
#>
[CmdletBinding(SupportsShouldProcess = $true)]
[Alias('sld')]
param(
[Parameter(Position = 0)]
[string]$Collection,
[Parameter(Position = 1)]
[string]$Id,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 2)]
[AllowNull()]
[AllowEmptyCollection()]
[object]$Data,
[Parameter()]
$Database
)
process {
$identity = Resolve-LocalBaseDocumentIdentity -Document $Data -Collection $Collection -Id $Id
$targetCollection = $identity.Collection
$targetId = $identity.Id
if (-not $targetCollection) {
throw [System.ArgumentException]::new("Collection name must be specified via -Collection or pipeline object.")
}
if (-not $targetId) {
throw [System.ArgumentException]::new("Document Id must be specified via -Id or pipeline object.")
}
# Strip internal decoration metadata if piped from Get-LocalBaseDocument
$cleanData = ConvertTo-LocalBasePayload $Data
$ctx = Get-LocalBaseExecutionContext -Database $Database
$col = $ctx.collection($targetCollection)
if ($PSCmdlet.ShouldProcess("$targetCollection/$targetId", "Set document")) { $null = $col.doc($targetId).set($cleanData) }
}
}
function Update-LocalBaseDocument {
<#
.SYNOPSIS
Updates documents with partial recursive JSON merge. Supports pipeline forwarding.
.DESCRIPTION
Data is the patch; pipeline input binds to InputObject to identify the target.
Creates a document if the key is absent. Emits no result object.
.EXAMPLE
Update-LocalBaseDocument -Collection "users" -Id "usr_1" -Data @{ active = $true }
.EXAMPLE
Get-LocalBaseDocument -Collection "users" -Filter @{ role = 'Guest' } |
Update-LocalBaseDocument -Data @{ expired = $true }
#>
[CmdletBinding(SupportsShouldProcess = $true)]
[Alias('uld')]
param(
[Parameter(Position = 0)]
[string]$Collection,
[Parameter(Position = 1)]
[string]$Id,
[Parameter(Mandatory = $true, Position = 2)]
[object]$Data,
[Parameter(ValueFromPipeline = $true)]
[object]$InputObject,
[Parameter()]
$Database
)
process {
$identity = Resolve-LocalBaseDocumentIdentity -Document $InputObject -Collection $Collection -Id $Id
$targetCollection = $identity.Collection
$targetId = $identity.Id
if (-not $targetCollection) {
throw [System.ArgumentException]::new("Collection name must be specified via -Collection or pipeline object.")
}
if (-not $targetId) {
throw [System.ArgumentException]::new("Document Id must be specified via -Id or pipeline object.")
}
if ($PSCmdlet.ShouldProcess("$targetCollection/$targetId", "Update document fields")) {
$ctx = Get-LocalBaseExecutionContext -Database $Database
$null = $ctx.collection($targetCollection).doc($targetId).update((ConvertTo-LocalBasePayload $Data))
}
}
}
function Remove-LocalBaseDocument {
<#
.SYNOPSIS
Deletes documents by ID, pipeline, or filter with -WhatIf and -Confirm safety.
.DESCRIPTION
Id and Filter combine using AND. An empty Filter without a resolved Id is
rejected; use Clear-LocalBaseCollection to remove all documents. Emits no count.
.EXAMPLE
Remove-LocalBaseDocument -Collection "users" -Id "usr_1" -Confirm:$false
.EXAMPLE
Get-LocalBaseDocument -Collection "logs" -Filter @{ level = 'Debug' } |
Remove-LocalBaseDocument -WhatIf
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
[Alias('rld')]
param(
[Parameter(Position = 0)]
[string]$Collection,
[Parameter(Position = 1)]
[string]$Id,
[Parameter(ValueFromPipeline = $true)]
[object]$InputObject,
[Parameter()]
[hashtable]$Filter,
[Parameter()]
$Database
)
process {
$identity = Resolve-LocalBaseDocumentIdentity -Document $InputObject -Collection $Collection -Id $Id
$targetCollection = $identity.Collection
$targetId = $identity.Id
$ctx = Get-LocalBaseExecutionContext -Database $Database
if ($targetId) {
if (-not $targetCollection) {
throw [System.ArgumentException]::new("Collection name must be specified via -Collection or pipeline object.")
}
$target = $ctx.collection($targetCollection).doc($targetId)
if ($Filter) {
foreach ($k in $Filter.Keys) {
$target = $target.where($k, '==', $Filter[$k])
}
}
$desc = if ($Filter) { "$targetCollection/$targetId (filtered by $(($Filter.Keys -join ', ')))" } else { "$targetCollection/$targetId" }
if ($PSCmdlet.ShouldProcess($desc, "Delete document")) {
$null = $target.delete()
}
}
elseif ($Filter -and $targetCollection) {
if ($Filter.Count -eq 0) {
throw [System.ArgumentException]::new("Empty -Filter is not allowed when deleting without -Id. To delete all documents in a collection, use Clear-LocalBaseCollection.")
}
$col = $ctx.collection($targetCollection)
$q = $col
foreach ($k in $Filter.Keys) {
$q = $q.where($k, '==', $Filter[$k])
}
if ($PSCmdlet.ShouldProcess("$targetCollection (filtered by $(($Filter.Keys -join ', ')))", "Delete matching documents")) {
$null = $q.delete()
}
}
else {
throw [System.ArgumentException]::new("Specify either -Id (or pipeline object) or -Filter to delete documents.")
}
}
}
function Measure-LocalBaseDocument {
<#
.SYNOPSIS
Returns document count and requested Sum, Average, Minimum and Maximum field aggregates.
.DESCRIPTION
Always returns Collection, Field and Count; requested switches add aggregate
properties. Count includes every matching document. Sum/Average use JSON
numbers only and return zero with no numbers. Minimum/Maximum prefer numbers,
fall back to text, then null. Queries execute separately; use a transaction
for a consistent view across concurrent writes.
.EXAMPLE
Measure-LocalBaseDocument -Collection "sales" -Field "amount" -Sum -Average
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Collection,
[Parameter(Mandatory = $true, Position = 1)]
[string]$Field,
[Parameter()]
[hashtable]$Filter,
[Parameter()]
[switch]$Sum,
[Parameter()]
[switch]$Average,
[Parameter()]
[switch]$Minimum,
[Parameter()]
[switch]$Maximum,
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
$q = $ctx.collection($Collection)
if ($Filter) {
foreach ($k in $Filter.Keys) {
$q = $q.where($k, '==', $Filter[$k])
}
}
$out = [ordered]@{
Collection = $Collection
Field = $Field
Count = $q.count()
}
if ($Sum) { $out['Sum'] = $q.sum($Field) }
if ($Average) { $out['Average'] = $q.avg($Field) }
if ($Minimum) { $out['Minimum'] = $q.min($Field) }
if ($Maximum) { $out['Maximum'] = $q.max($Field) }
return [PSCustomObject]$out
}
# ---------------------------------------------------------------------------
# 4. Transaction Cmdlets
# ---------------------------------------------------------------------------
function Invoke-LocalBaseTransaction {
<#
.SYNOPSIS
Executes a scriptblock inside an atomic SQLite transaction (BEGIN IMMEDIATE / COMMIT / ROLLBACK).
.DESCRIPTION
Uses the selected database as the ambient connection for the block, restores
the previous connection afterward, and returns output only after commit.
Invokes the block with ErrorActionPreference Stop; unhandled errors roll back.
Same-connection nesting is rejected. Different databases use independent
transactions and do not form a distributed atomic commit.
.EXAMPLE
Invoke-LocalBaseTransaction {
Add-LocalBaseDocument -Collection "accounts" -Data @{ id = 1; balance = 90 }
Add-LocalBaseDocument -Collection "accounts" -Data @{ id = 2; balance = 110 }
}
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[scriptblock]$ScriptBlock,
[Parameter()]
$Database
)
$ctx = Get-LocalBaseExecutionContext -Database $Database
# Reject same-connection nesting before changing ambient state.
$null = $ctx.beginTransaction()
$previousConnection = $script:CurrentLocalBaseConnection
$previousPreference = $ErrorActionPreference
try {
$script:CurrentLocalBaseConnection = $ctx
$ErrorActionPreference = 'Stop'
# Caller-created scriptblocks retain their session state. Inject the
# preference into the invocation scope instead of only this module scope.
$variables = [System.Collections.Generic.List[System.Management.Automation.PSVariable]]::new()
$variables.Add([System.Management.Automation.PSVariable]::new('ErrorActionPreference', 'Stop'))
$result = $ScriptBlock.InvokeWithContext($null, $variables, @())
$null = $ctx.commit()
return $result
}
catch {
try { $null = $ctx.rollback() } catch { Write-Verbose "Rollback failed: $($_.Exception.Message)" }
throw
}
finally {
$script:CurrentLocalBaseConnection = $previousConnection
$ErrorActionPreference = $previousPreference
}
}
function Start-LocalBaseTransaction {
<#
.SYNOPSIS
Manually starts an atomic transaction on the database.
.DESCRIPTION
Begins IMMEDIATE on the explicit or ambient connection without replacing
the ambient context. Nested transactions on the same connection throw.
Supports WhatIf and Confirm. Emits no object.
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param([Parameter()]$Database)
$ctx = Get-LocalBaseExecutionContext -Database $Database
if ($PSCmdlet.ShouldProcess("Database", "Begin transaction")) { $null = $ctx.beginTransaction() }
}
function Complete-LocalBaseTransaction {
<#
.SYNOPSIS
Commits all pending changes in the current transaction.
.DESCRIPTION
Uses the explicit or ambient connection. Throws if there is no active
transaction. Emits no object; does not support WhatIf or Confirm.
#>
[CmdletBinding()]
param([Parameter()]$Database)
$ctx = Get-LocalBaseExecutionContext -Database $Database
$null = $ctx.commit()
}
function Undo-LocalBaseTransaction {
<#
.SYNOPSIS
Rolls back all pending changes in the current transaction.
.DESCRIPTION
Uses the explicit or ambient connection. Throws if there is no active
transaction. Emits no object; does not support WhatIf or Confirm.
#>
[CmdletBinding()]
param([Parameter()]$Database)
$ctx = Get-LocalBaseExecutionContext -Database $Database
$null = $ctx.rollback()
}