-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSQLSimplePS.psm1
1021 lines (829 loc) · 32.8 KB
/
SQLSimplePS.psm1
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SQL Simple for PowerShell (SQLSimplePS)
# Version 1.7.2
# https://github.com/texhex/SQLSimplePS
#
# Copyright (c) 2018 Michael 'Tex' Hex
# Licensed under the Apache License, Version 2.0.
#
# To use this classes, add this line as the very first line in your script:
# using module .\SQLSimplePS.psm1
#
#
# ## NOTICE ##
# SQLSimple uses Snapshot Isolation as default isolation level (as it prevents a lot of problems that other isolation levels have).
# Execute this SQL command in the target database to allow this isolation level:
#
# ALTER DATABASE CURRENT SET ALLOW_SNAPSHOT_ISOLATION ON
# GO
#
# ## EXAMPLES ##
#
# The following table is used for all examples:
<#
CREATE TABLE [dbo].[TestTable](
[ID] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, [IntValue] [int] NOT NULL, [NumericValue] [decimal](5, 2) NOT NULL,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
( [ID] ASC )
WITH (IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)
ON [PRIMARY]
GO
#>
# This is the connection string used by all examples
<#
$connectionString="Server=.\SQLEXPRESS; Database=TestDB; Connect Timeout=15; Integrated Security=True; Application Name=SQLSimpleTest;"
#>
#
#
# ### ONE LINERS ###
<#
#Only returns an array of single values
[SQLSimple]::Execute("INSERT INTO dbo.TestTable(Name, IntValue, NumericValue) OUTPUT Inserted.ID VALUES('Second Test', 9, 45.66)", $connectionString)
#Specify transaction isolation level
[SQLSimple]::Query("SELECT * FROM dbo.TestTable", $connectionString, [System.Data.IsolationLevel]::Serializable)
#Returns a hash table
[SQLSimple]::Query("SELECT * FROM dbo.TestTable", $connectionString)
#Specify transaction isolation level
[SQLSimple]::Query("SELECT * FROM dbo.TestTable", $connectionString, [System.Data.IsolationLevel]::Serializable))
#>
#
# ### INSERT DATA WITH DELETE FIRST ####
<#
$sqls = [SQLSimple]::new($connectionString)
$sqls.AddCommand("DELETE FROM dbo.TestTable")
$sqls.AddCommand("INSERT INTO dbo.TestTable(Name, IntValue, NumericValue) OUTPUT Inserted.ID VALUES('Chain Test 1', 11, 11.11);")
$sqls.Execute()
#>
#
# ### INSERT DATA WITH DELETE FIRST AND USING SQLCommandTemplates ####
<#
$sqls = [SQLSimple]::new($connectionString)
$sqls.Objectname="dbo.TestTable"
$deleteCommand = $sqls.AddCommandEx("DELETE FROM @@OBJECT_NAME@@ WHERE IntValue = @IntValue")
$deleteCommand.AddMappingWithData("IntValue", 2, [Data.SqlDbType]::Int)
$insertCommand = $sqls.AddCommandEx("INSERT INTO @@OBJECT_NAME@@(Name, IntValue, NumericValue) OUTPUT Inserted.ID VALUES(@Name, @IntValue, @NumericValue);")
$insertCommand.AddMappingWithData("Name", "Chain Test 2", [Data.SqlDbType]::NVarChar)
$insertCommand.AddMappingWithData("IntValue", 2, [Data.SqlDbType]::Int)
$insertCommand.AddMappingWithData("NumericValue", 22.22, [Data.SqlDbType]::Decimal)
$sqls.Execute()
#>
#
# ### INSERT SEVERAL ROWS USING DATA PROPERTY ####
<#
$sqls = [SQLSimple]::new("[dbo].[TestTable]", $connectionString)
$insertCommand = $sqls.AddCommandEx("INSERT INTO dbo.TestTable(Name, IntValue, NumericValue) OUTPUT Inserted.ID VALUES(@Name, @IntValue, @NumericValue);")
#Add the mapping
$insertCommand.AddMapping("Name", "NameProp", [Data.SqlDbType]::NVarChar)
$insertCommand.AddMapping("IntValue", "MyCount", [Data.SqlDbType]::int)
$insertCommand.AddMapping("NumericValue", "NumericVal", [Data.SqlDbType]::Decimal)
#Add the data #1
$myData1 = @{ NameProp = "Chain Test 4"; MyCount = 4; NumericVal = 44.44; }
$insertCommand.AddData($myData1)
#Add the data #2
$myData2 = @{ NameProp = "Chain Test 5"; MyCount = 5; NumericVal = 55.55; }
$insertCommand.AddData($myData2)
$sqls.Execute()
#>
#
# ### QUERY (SELECT) EXAMPLE ###
<#
$sqlSelect = [SQLSimple]::new("[dbo].[TestTable]", $connectionString)
$result=$sqlSelect.Query("SELECT * FROM @@OBJECT_NAME@@;")
#>
#
# ## SELECT EXAMPLE WITH PARAMETERS ###
<#
$sqls = [SQLSimple]::new($connectionString)
$selectCommand = $sqls.AddCommandEx("SELECT * from dbo.TestTable WHERE IntValue < @IntValue;")
$selectCommand.AddMappingWithData("IntValue", 12, [Data.SqlDbType]::Int)
$sqls.Query()
#>
#
#
#This script requires PowerShell 5 because we are using classes
#requires -version 5
#Guard against common code errors
Set-StrictMode -version 2.0
#Terminate script on errors
$ErrorActionPreference = 'Stop'
Import-Module "$PSScriptRoot\MPSXM.psm1"
#Base class that holds the object name, the connection string and the commands
class SQLSimple
{
#PowerShell really needs to support constructor chaining...
#https://github.com/PowerShell/PowerShell/issues/3820#issuecomment-302750422
SQLSimple()
{
$this.Init()
}
SQLSimple([string] $ConnectionString)
{
$this.Init()
$this.InitConnectionString($ConnectionString)
}
SQLSimple([string] $Objectname, [string] $ConnectionString)
{
$this.Init()
$this.InitConnectionString($ConnectionString)
$this.ObjectName = $Objectname
}
SQLSimple([string] $ConnectionString, [System.Data.IsolationLevel] $IsolationLevel)
{
$this.Init()
$this.InitConnectionString($ConnectionString)
$this.TransactionIsolationLevel = $IsolationLevel
}
SQLSimple([string] $Objectname, [string] $ConnectionString, [System.Data.IsolationLevel] $IsolationLevel)
{
$this.Init()
$this.InitConnectionString($ConnectionString)
$this.ObjectName = $Objectname
$this.TransactionIsolationLevel = $IsolationLevel
}
hidden [void] Init()
{
$this.ObjectName = ""
$this.ConnectionString = ""
$this.Commands = New-Object System.Collections.ArrayList
$this.TransactionIsolationLevel = [System.Data.IsolationLevel]::Snapshot
}
hidden [void] InitConnectionString([string] $ConnectionString)
{
if ( $ConnectionString.Length -le 0)
{
throw "SQLSimple: ConnectionString can not be empty"
}
$this.ConnectionString = $ConnectionString
}
#These functiuons are not hidden as there might be cases where we need the content
static [string] ReadConnectionStringFile()
{
return ReadConnectionStringFile("")
}
static [string] ReadConnectionStringFile([string] $Filename)
{
if ( $Filename.Length -le 0)
{
$Filename = "$PSScriptRoot\ConnectionString.conf"
}
$conString = Get-Content $FileName -ErrorAction Stop -Raw # -Encoding UTF8
if ( $conString.Length -le 0)
{
throw "SQLSimple: Trying to read the connection string from file [$FileName] failed as the file is emtpy"
}
#Clean up
$conString = Get-TrimmedString -RemoveDuplicates $conString
return $conString
}
static [SQLSimple] CreateFromConnectionStringFile()
{
return [SQLSimple]::CreateFromConnectionStringFile("")
}
static [SQLSimple] CreateFromConnectionStringFile([string] $Filename)
{
$conString = [SQLSimple]::ReadConnectionStringFile($Filename)
$sqls = [SQLSimple]::new($conString)
return $sqls
}
#I think, given the name of the function, the only supported parameter should be #$Filename.
#But I leave these others in place if I ever change my mind.
<#
static [SQLSimple] CreateFromConnectionStringFile([string] $Objectname)
{
return [SQLSimple]::CreateFromConnectionStringFile("", $Objectname)
}
static [SQLSimple] CreateFromConnectionStringFile([string] $Filename, [string] $Objectname)
{
return [SQLSimple]::CreateFromConnectionStringFile($Filename, $ObjectName, [System.Data.IsolationLevel]::Snapshot)
}
static [SQLSimple] CreateFromConnectionStringFile([string] $Filename, [string] $Objectname, [System.Data.IsolationLevel] $IsolationLevel)
{
$sqls = [SQLSimple]::CreateFromConnectionStringFile($FileName)
$sqls.Objectname=$Objectname
$sqls.TransactionIsolationLevel=$IsolationLevel
return $sqls
}
#>
#Replacement tokens
hidden static [string] $ObjectNameToken = "@@OBJECT_NAME@@"
hidden static [string] $ColumnToken = "@@COLUMN@@"
hidden static [string] $ParameterToken = "@@PARAMETER@@"
hidden static [string] $ColumnEqualsParameterToken = "@@COLUMN_EQUALS_PARAMETER@@"
#The SQL object this map applies to - in most cases, this will be a table: "[dbo].[MyTable]"
[string] $Objectname
#The connection string used to connect to the database
[string] $ConnectionString
#The transaction isolation level we want to use
#For details, please see this excellent post by Sergey Barskiy: http://www.dotnetspeak.com/data/transaction-isolation-levels-explained-in-details/
[System.Data.IsolationLevel] $TransactionIsolationLevel
#An array list of SQLSimpleCommand
[System.Collections.ArrayList] $Commands
#Add a SQLCommand
[void] AddCommand([SQLSimpleCommand] $Command)
{
[void] $this.Commands.Add($Command)
}
#Add a SQLSimpleCommand by using a string
[void] AddCommand([string] $SQLTemplate)
{
[void] $this.Commands.Add([SQLSimpleCommand]::new($SQLTemplate))
}
#Add a SQLSimpleCommand by using a SQLCommandTemplate
[void] AddCommand([SQLCommandTemplate] $Template)
{
[void] $this.Commands.Add([SQLSimpleCommand]::new($Template))
}
#Creates a command, adds it to the list and returns it
#I have no idea what the best naming for this function would be:
#? [SQLSimpleCommand] AddCommandEx([string] $SQLTemplate)
#? [SQLSimpleCommand] AddCommand2([string] $SQLTemplate)
#? [SQLSimpleCommand] AppendCommand([string] $SQLTemplate)
#? [SQLSimpleCommand] CreateCommand([string] $SQLTemplate)
#? [SQLSimpleCommand] AttachCommand([string] $SQLTemplate)
#? [SQLSimpleCommand] AddCommandAndReturn([string] $SQLTemplate)
[SQLSimpleCommand] AddCommandEx([string] $SQLTemplate)
{
$command = [SQLSimpleCommand]::new($SQLTemplate)
[void] $this.Commands.Add($command)
return $command
}
[SQLSimpleCommand] AddCommandEx([SQLCommandTemplate] $Template)
{
$command = [SQLSimpleCommand]::new($Template)
[void] $this.Commands.Add($command)
return $command
}
#Validates this SQLSimple is everything is set as planned
[void] Validate()
{
#Objectname can be empty, but not null
if ( $this.Objectname -eq $null)
{
throw "SQLSimple: Objectname is null"
}
if ( Test-String -IsNullOrWhiteSpace $this.ConnectionString )
{
throw "SQLSimple: ConnectionString is not set"
}
if ( $this.Commands -eq $null )
{
throw "SQLSimple: Commands is null"
}
else
{
if ( $this.Commands.Count -lt 1 )
{
throw "SQLSimple: No commands defined"
}
foreach ($command in $this.Commands)
{
$command.Validate()
}
}
}
static [array] Execute([string] $SQLQuery, [string] $ConnectionString)
{
return [SQLSimple]::Execute($SQLQuery, $ConnectionString, [System.Data.IsolationLevel]::Snapshot)
}
static [array] Execute([string] $SQLQuery, [string] $ConnectionString, [System.Data.IsolationLevel] $IsolationLevel)
{
$sql = [SQLSimple]::new($ConnectionString, $IsolationLevel)
$sql.AddCommand($SQLQuery)
return $sql.Execute()
}
static [object] ExecuteScalar([string] $SQLQuery, [string] $ConnectionString)
{
return [SQLSimple]::ExecuteScalar($SQLQuery, $ConnectionString, [System.Data.IsolationLevel]::Snapshot)
}
static [object] ExecuteScalar([string] $SQLQuery, [string] $ConnectionString, [System.Data.IsolationLevel] $IsolationLevel)
{
$sql = [SQLSimple]::new($ConnectionString, $IsolationLevel)
$sql.AddCommand($SQLQuery)
return $sql.ExecuteScalar()
}
static [array] Query([string] $SQLQuery, [string] $ConnectionString)
{
return [SQLSimple]::Query($SQLQuery, $ConnectionString, [System.Data.IsolationLevel]::Snapshot)
}
static [array] Query([string] $SQLQuery, [string] $ConnectionString, [System.Data.IsolationLevel] $IsolationLevel)
{
$sql = [SQLSimple]::new($ConnectionString, $IsolationLevel)
$sql.AddCommand($SQLQuery)
return $sql.Query()
}
[array] Query()
{
#Make sure everything is ready
$this.Validate()
#A query only allows a single command and a single data object
if ( $this.Commands.Count -gt 1 )
{
throw "SQLSimple: When using Query() only a single command is allowed"
}
return $this.ExecuteSQLInternally($true)
}
[array] Execute()
{
#Make sure everything is ready
$this.Validate()
return $this.ExecuteSQLInternally($false)
}
[object] ExecuteScalar()
{
$return = $this.Execute()
if ( $return.Count -gt 0 )
{
return $return[0]
}
else
{
#No return values, return $null
return $null
}
}
hidden [array] ExecuteSQLInternally([bool] $ReturnFullResult)
{
$transaction = $null
$connection = $null
$sqlCommand = $null
$reader = $null
$returnList = new-object System.Collections.ArrayList
try
{
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = Get-TrimmedString -RemoveDuplicates $this.ConnectionString
$connection.Open()
if ($connection.State -ne [Data.ConnectionState]::Open)
{
throw "Unable to open connection to database!"
}
#We do not care how many rows a command has affected
$sqlCommand = $connection.CreateCommand()
$sqlCommand.CommandText = "SET NOCOUNT ON;"
[void]$sqlCommand.ExecuteNonQuery()
$sqlCommand.Dispose()
#Ignore transactions if the level is Unspecified
if ( $this.TransactionIsolationLevel -ne [System.Data.IsolationLevel]::Unspecified )
{
#Start the transaction - yes, even for SELECTs
#"An application can perform actions such as acquiring locks to protect the transaction isolation level of SELECT statements [..]"
#https://docs.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql
$transaction = $connection.BeginTransaction( $this.TransactionIsolationLevel )
}
foreach ($simpleCommand in $this.Commands)
{
$sqlCommand = $simpleCommand.Build($this.Objectname)
$sqlCommand.Connection = $connection
$sqlCommand.Transaction = $transaction
#Change the sourceData to an array so foreach() and .Count works always
$sourceData = @()
$sourceData = ConvertTo-Array $simpleCommand.Data
if ( $sourceData.Count -lt 1 )
{
#No data available, we just execute the command and be done with it
$this.ExecuteCommandAndProcessResults($sqlCommand, $ReturnFullResult, $returnList)
}
else
{
#Go through each entry in data
foreach ($sourceDataEntry in $sourceData)
{
#Map the SQL parameters to the source objects
foreach ($simpleColumn in $simpleCommand.ColumnMap)
{
$value = $null
if ( Test-IsHashtable $sourceDataEntry)
{
#Hash table is simple
if ( $sourceDataEntry.Contains($simpleColumn.Source) )
{
$value = $sourceDataEntry[$simpleColumn.Source]
}
else
{
throw "Source property [$($simpleColumn.Source)] not found as key in hash table for column [$($simpleColumn.Column)]"
}
}
else
{
#Access NoteProperty
try
{
$value = Select-Object -InputObject $sourceDataEntry -ExpandProperty $simpleColumn.Source
}
catch [System.ArgumentException]
{
throw "Source property [$($simpleColumn.Source)] not found in data for column [$($simpleColumn.Column)]"
}
}
#Changwe $null to DBNull if needed
if ( $value -eq $null )
{
$sqlCommand.Parameters["@$($simpleColumn.Column)"].Value = [System.DBNull]::Value
}
else
{
$sqlCommand.Parameters["@$($simpleColumn.Column)"].Value = $value
}
}
#Everything is ready, go for it
$this.ExecuteCommandAndProcessResults($sqlCommand, $ReturnFullResult, $returnList)
}
}
$sqlCommand.Dispose()
$sqlCommand = $null
#All data in this SQLSimpleCommand done, next one please
}
#All commands done, check if there is a transaction we need to commit
if ( $transaction -ne $null )
{
try
{
$transaction.Commit()
$transaction = $null
}
catch
{
#Our commit has failed. This can happen for many reasons, but one of them is that we have requested
#snapshot isolation and the database does not support it. I have no idea how we could detect this case.
$transaction.Dispose()
$transaction = $null
if ( $this.TransactionIsolationLevel -eq [System.Data.IsolationLevel]::Snapshot )
{
throw "Commit failed (please make sure the database supports snapshot isolation): $($_.Exception.Message)"
}
else
{
throw "Commit failed: $($_.Exception.Message)"
}
}
}
#Done
}
finally
{
#We do not check if reader is null because this triggers the reader
try
{
if ( -not $reader.IsClosed ) { $reader.Close() }
}
catch {}
if ( $sqlCommand -ne $null )
{
try { $sqlCommand.Dispose() } catch {}
}
if ( $transaction -ne $null)
{
if ( $transaction.Connection -ne $null )
{
try { $transaction.Rollback() } catch {}
}
try { $transaction.Dispose() } catch {}
}
if ( $connection -ne $null )
{
if ( $connection.State -eq [Data.ConnectionState]::Open )
{
try { $connection.Close() } catch {}
}
}
}
return $returnList.ToArray()
}
hidden [void] ExecuteCommandAndProcessResults([System.Data.SqlClient.SqlCommand] $Command, [bool] $FullResults, [System.Collections.ArrayList] $ReturnList)
{
if ( $FullResults )
{
try
{
$reader = $Command.ExecuteReader()
}
catch
{
throw "Query failed: $($_.Exception.Message) (SQL: $($Command.CommandText))"
}
try
{
if ($reader.HasRows)
{
while ( $reader.Read() )
{
#Ordered dictionary will do
$row = [Ordered]@{}
For ($curField = 0; $curField -lt $reader.FieldCount; $curField++)
{
if ( -not $reader.IsDBNull($curField) )
{
$row.Add( $reader.GetName($curField), $reader.GetValue($curField) )
}
else
{
#Field is DBNull. Use $NULL in this case (else it would be [System.DBNull]::Value )
$row.Add( $reader.GetName($curField), $null )
}
}
[void]$ReturnList.Add($row)
}
}
}
finally
{
#Always close the reader
$reader.Close()
}
}
else
{
#No Full results, use ExecuteScalar()
try
{
$val = $Command.ExecuteScalar()
#Check if the value is a DBNull
#If ExecuteScalar returns nothing (DELETE FROM TABLE;), the value is already $NULL
#If ExecuteScalar is used to return a single value from a table that is NULL, the value will be DBNull
if ( $val -eq [System.DBNull]::Value )
{
$val = $null
}
#Only add a value to the array if the value is not $null
if ( $val -ne $null)
{
$returnList.Add($val)
}
}
catch
{
throw "Execute failed: $($_.Exception.Message) (SQL: $($Command.CommandText))"
}
}
}
}
enum SQLCommandTemplate
{
Delete = 1
DeleteReturnID = 2
DeleteAll = 3
DeleteAllReturnID = 4
Insert = 31
InsertReturnID = 32
#I think we better leave them out
#Update = 61
#UpdateReturnID = 62
}
#A single SQL command
class SQLSimpleCommand
{
SQLSimpleCommand()
{
$this.ColumnMap = New-Object System.Collections.ArrayList
$this.Data = New-Object System.Collections.ArrayList
}
SQLSimpleCommand([string] $SQLTemplate)
{
$this.ColumnMap = New-Object System.Collections.ArrayList
$this.Data = New-Object System.Collections.ArrayList
$this.SQLTemplate = $SQLTemplate
}
SQLSimpleCommand([SQLCommandTemplate] $Template)
{
$this.ColumnMap = New-Object System.Collections.ArrayList
$this.Data = New-Object System.Collections.ArrayList
switch ($Template)
{
Delete
{
$this.SQLTemplate = "DELETE FROM @@OBJECT_NAME@@ WHERE @@COLUMN_EQUALS_PARAMETER@@;"
}
DeleteReturnID
{
$this.SQLTemplate = "DELETE FROM @@OBJECT_NAME@@ OUTPUT Deleted.ID WHERE @@COLUMN_EQUALS_PARAMETER@@;"
}
DeleteAll
{
$this.SQLTemplate = "DELETE FROM @@OBJECT_NAME@@;"
}
DeleteAllReturnID
{
$this.SQLTemplate = "DELETE FROM @@OBJECT_NAME@@ OUTPUT Deleted.ID;"
}
Insert
{
$this.SQLTemplate = "INSERT INTO @@OBJECT_NAME@@(@@COLUMN@@) VALUES(@@PARAMETER@@);"
}
InsertReturnID
{
$this.SQLTemplate = "INSERT INTO @@OBJECT_NAME@@(@@COLUMN@@) OUTPUT Inserted.ID VALUES(@@PARAMETER@@);"
}
<#
Update
{
$this.SQLTemplate = "UPDATE @@OBJECT_NAME@@ SET @@COLUMN@@=@@PARAMETER@@;"
}
UpdateReturnID
{
$this.SQLTemplate = "UPDATE @@OBJECT_NAME@@ SET @@COLUMN@@=@@PARAMETER@@ OUTPUT Inserted.ID;"
}
#>
}
}
#The SQL text to be executed. Can contain replacement tokens @@OBJECT_NAME@@, @@COLUMN@@ or @@PARAMETER@@
[string] $SQLTemplate
#An array list of SQLSimpleColumn that map the data at runtime to the matching SQL column
[System.Collections.ArrayList] $ColumnMap
#It's also possible to directly use $command.ColumnMap.Add($sqlping)
[void] AddMapping([SQLSimpleColumn] $Column)
{
[void] $this.ColumnMap.Add($Column)
}
#This helper function will make the source code a little bit easier to read
[void] AddMapping([string] $Columnname, [string] $Source, [Data.SqlDbType] $Type)
{
$this.AddMapping( [SQLSimpleColumn]::new($Columnname, $Source, $Type) )
}
#Quick access function that adds a column mapping and the value for it directly
#This will only apply to the first entry of Data and will NOT work if the object in Data[0] already exists and is not a hash table
[void] AddMappingWithData([string] $Columnname, $Data, [Data.SqlDbType] $Type)
{
#First add the mapping
$column = [SQLSimpleColumn]::new($Columnname, $Columnname, $Type)
$this.AddMapping($column)
#Then the data
if ( $this.Data.Count -eq 0 )
{
$temp = @{}
$this.AddData($temp)
}
$this.Data[0].Add($Columnname, $Data)
}
#An array list of the data that should be used when executing this command.
#Each entry must contain an object that holds the data. For example, if you want to insert a row with "NAME" and "AGE", do not add
#those two properties directly to this array list, instead create a hash table, add those properties to that hash table and then add
#the hash table to this array list so $Data.Count will be 1
[System.Collections.ArrayList] $Data
#It's also possible to directly use $command.Data.Add($myData)
[void] AddData($Data)
{
[void] $this.Data.Add($Data)
}
[void] Validate()
{
#if ( [string]::IsNullOrWhiteSpace($this.SQLTemplate) )
if ( Test-String -IsNullOrWhiteSpace $this.SQLTemplate )
{
throw "SQLSimpleCommand: SQLTemplate is not set"
}
if ( $this.ColumnMap -eq $null )
{
#ColumnMap can be empty, but not $null
throw "SQLSimpleCommand: ColumMap is null"
}
if ( $this.ColumnMap.Count -gt 0 )
{
foreach ( $sqlCol in $this.ColumnMap )
{
$sqlCol.Validate()
}
}
if ( $this.Data -eq $null )
{
#Data can be empty, but not $null
throw "SQLSimpleCommand: Data is null"
}
#Check if the SQLTemplate contains @@COLUMN or @@PARAMETER replacement values but ColumnMap and/or Data is empty
if ($this.SQLTemplate.Contains([SQLSimple]::ColumnToken) -or
$this.SQLTemplate.Contains([SQLSimple]::ParameterToken))
{
#Replacement values found. Check if BOTH ColumnMap and Data is set
if (($this.ColumnMap.Count -eq 0) -or
($this.Data.Count -eq 0))
{
throw "SQLSimpleCommand: SQLTemplate contains replacement values, but either ColumnMap and/or Data is empty"
}
}
}
hidden [System.Data.SqlClient.SqlCommand] Build([string] $Objectname)
{
$command = new-object System.Data.SqlClient.SqlCommand
$command.CommandText = $this.GenerateSQLText($Objectname)
#Build SQL Parameters and name them @Column
foreach ($sqlColumn in $this.ColumnMap)
{
$param = New-Object Data.SqlClient.SqlParameter("@$($sqlColumn.Column)", $sqlColumn.Type)
$command.Parameters.Add($param)
}
return $command
}
hidden [string] GenerateSQLText([string] $Objectname)
{
$sqlPart = new-object System.Text.StringBuilder
$sb = new-object System.Text.StringBuilder
$sb.Append($this.SQLTemplate)
if ($this.SQLTemplate.Contains([SQLSimple]::ObjectNameToken))
{
#Check if the objectname is set
if ( $objectName.Length -gt 0 )
{
$sb.Replace([SQLSimple]::ObjectNameToken, $objectName)
}
else
{
throw "Found replacement token $([SQLSimple]::ObjectNameToken) but Objectname is empty"
}
}
#Check if the SQLTemplate contains @@COLUMN@@ and start the replacement if this is the case
if ($this.SQLTemplate.Contains([SQLSimple]::ColumnToken))
{
$sqlPart.Clear();
foreach ($sqlColumn in $this.ColumnMap)
{
$sqlPart.Append($sqlColumn.Column)
$sqlPart.Append(",")
}
$sb.Replace([SQLSimple]::ColumnToken, $sqlPart.ToString().TrimEnd(","))
}
#Check if the SQLTemplate contains @@PARAMETER@@ and start the replacement if this is the case
if ($this.SQLTemplate.Contains([SQLSimple]::ParameterToken))
{
$sqlPart.Clear();
foreach ($sqlColumn in $this.ColumnMap)
{
$sqlPart.Append("@")
$sqlPart.Append($sqlColumn.Column)
$sqlPart.Append(",")
}
$sb.Replace([SQLSimple]::ParameterToken, $sqlPart.ToString().TrimEnd(","));
}
#Check if the SQLTemplate contains @@COLUMN_EQUALS_PARAMETER@@ and start the replacement if this is the case
if ($this.SQLTemplate.Contains([SQLSimple]::ColumnEqualsParameterToken))
{
$sqlPart.Clear();
$sqlAND=" AND "
foreach ($sqlColumn in $this.ColumnMap)
{
$sqlPart.Append($sqlColumn.Column)
$sqlPart.Append(" = @")
$sqlPart.Append($sqlColumn.Column)
$sqlPart.Append($sqlAND)
}
#We can not use the following command as TrimEnd() might remove additonal characters, see https://github.com/texhex/SQLSimplePS/issues/3
#$sb.Replace([SQLSimple]::ColumnEqualsParameterToken, $sqlPart.ToString().TrimEnd(" AND "))
$sqlPartString=$sqlPart.ToString()
#Ensure it ends with " AND "
if ( $sqlPartString.EndsWith($sqlAND) )
{
$sqlPartString = $sqlPartString.Remove($sqlPartString.Length - $sqlAND.Length)
}
$sb.Replace([SQLSimple]::ColumnEqualsParameterToken, $sqlPartString)
}
#Ensure the command ends with a ;
$finalSQL = $sb.ToString()
if ( -not ($finalSQL.EndsWith(";")) )
{
$finalSQL += ";"
}
return $finalSQL;
}
}
#A single mapping between a SQL server column and the name of the property on the data object
class SQLSimpleColumn
{
SQLSimpleColumn()
{
$this.Column = $null
$this.Source = $null
$this.Type = [Data.SQLDBType]::NVarChar
}
SQLSimpleColumn([string] $Column, [string] $Source)
{
$this.Column = $Column
$this.Source = $Source
$this.Type = [Data.SQLDBType]::NVarChar
}
SQLSimpleColumn([string] $Column, [string] $Source, [Data.SqlDbType] $Type)
{
$this.Column = $Column
$this.Source = $Source
$this.Type = $Type
}
#The SQL object column name. It will also be used as parameter name.
[string] $Column
#The source property of the data object that maps to this column during runtime
[string] $Source
#The SQL Server data type of this column
[Data.SQLDBType] $Type
[void] Validate()