-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-test-db.ps1
More file actions
8834 lines (8755 loc) · 78.7 KB
/
create-test-db.ps1
File metadata and controls
8834 lines (8755 loc) · 78.7 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
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
param(
[string]$ContainerName = "sql-test",
[string]$SqlVersion = "2022",
[string]$SaPassword = "Pa55word",
[string]$DbName = "TestLab",
[int]$Users = 1000000,
[int]$Products = 5000,
[int]$Orders = 2000000,
[switch]$RecreateDb # drops and recreates the DB
)
# Build correct docker image name dynamically
$imageName = "mcr.microsoft.com/mssql/server:$SqlVersion-latest"
function Invoke-OrThrow {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Cmd,
[string]$Err = "Command failed",
[string]$Activity = "Running command",
[int]$ProgressDelayMs = 200
)
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$spinner = @('|','/','-','\')
$i = 0
$job = Start-Job -ScriptBlock {
param($Cmd)
$output = Invoke-Expression $Cmd 2>&1
[pscustomobject]@{
Output = $output
ExitCode = $LASTEXITCODE
}
} -ArgumentList $Cmd
while ($job.State -eq 'Running') {
$i = ($i + 1) % $spinner.Length
Write-Progress -Activity $Activity -Status ("{0} elapsed {1:c}" -f $spinner[$i], $sw.Elapsed) -PercentComplete 50
Start-Sleep -Milliseconds $ProgressDelayMs
}
Write-Progress -Activity $Activity -Completed
$sw.Stop()
$result = Receive-Job $job -Keep
Remove-Job $job | Out-Null
if ($null -eq $result) {
throw ("{0}`nNo output. Final job state: {1}. Duration: {2:c}" -f $Err, $job.State, $sw.Elapsed)
}
if ($result.ExitCode -ne 0) {
$text = ($result.Output -join [Environment]::NewLine)
throw ("{0}`n{1}`nExitCode: {2}. Duration: {3:c}" -f $Err, $text, $jobResult.ExitCode, $sw.Elapsed)
}
Write-Host ("{0} completed in {1:c}" -f $Activity, $sw.Elapsed)
return $result.Output
}
$existing = (docker ps -a --format "{{.Names}}" | Where-Object { $_ -eq $ContainerName })
if (-not $existing) {
Write-Host "Starting new SQL Server container '$ContainerName'..."
Invoke-OrThrow "docker run -d --name $ContainerName -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=$SaPassword' -p 1433:1433 $imageName" "Failed to start container"
} elseif (-not (docker ps --format "{{.Names}}" | Where-Object { $_ -eq $ContainerName })) {
Write-Host "Starting existing container '$ContainerName'..."
Invoke-OrThrow "docker start $ContainerName" "Failed to start existing container"
}
Write-Host "Waiting for SQL Server to become ready..."
$tries = 60
for ($i=1; $i -le $tries; $i++) {
$ok = docker exec $ContainerName /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P $SaPassword -C -Q "SELECT 1" 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "SQL is ready."
# Give SQL a bit more time to finish starting other databases
Start-Sleep -Seconds 10
break
}
Start-Sleep -Seconds 2
if ($i -eq $tries) {
throw "SQL Server did not become ready in time."
}
}
$tmp = New-TemporaryFile
@'
SET NOCOUNT ON;
-- ============================================================
-- TestLab: lightweight test DB for T-SQL exercises
-- ============================================================
IF '$(RECREATE)' = '1'
BEGIN
IF DB_ID('$(DBNAME)') IS NOT NULL
BEGIN
ALTER DATABASE [$(DBNAME)] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [$(DBNAME)];
END
END
IF DB_ID('$(DBNAME)') IS NULL
BEGIN
PRINT 'Creating database $(DBNAME)...';
CREATE DATABASE [$(DBNAME)];
END
GO
USE [$(DBNAME)];
GO
-- TABLES
IF OBJECT_ID('dbo.Users') IS NULL
CREATE TABLE dbo.Users
(
UserID INT IDENTITY(1,1) PRIMARY KEY,
Username NVARCHAR(50) NOT NULL,
FirstName NVARCHAR(200) NOT NULL,
Surname NVARCHAR(200) NOT NULL,
Email NVARCHAR(255) NOT NULL UNIQUE,
CreatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),
IsActive BIT NOT NULL DEFAULT 1
);
IF OBJECT_ID('dbo.Products') IS NULL
CREATE TABLE dbo.Products
(
ProductID INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Category NVARCHAR(50) NOT NULL,
Price DECIMAL(10,2) NOT NULL,
CreatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
);
IF OBJECT_ID('dbo.Orders') IS NULL
CREATE TABLE dbo.Orders
(
OrderID BIGINT IDENTITY(1,1) PRIMARY KEY,
UserID INT NOT NULL REFERENCES dbo.Users(UserID),
OrderDate DATETIME2 NOT NULL,
Status NVARCHAR(20) NOT NULL
);
IF OBJECT_ID('dbo.OrderItems') IS NULL
CREATE TABLE dbo.OrderItems
(
OrderItemID BIGINT IDENTITY(1,1) PRIMARY KEY,
OrderID BIGINT NOT NULL REFERENCES dbo.Orders(OrderID),
ProductID INT NOT NULL REFERENCES dbo.Products(ProductID),
Quantity INT NOT NULL CHECK (Quantity>=1),
UnitPrice DECIMAL(10,2) NOT NULL
);
IF OBJECT_ID('dbo.Posts') IS NULL
CREATE TABLE dbo.Posts
(
PostID BIGINT IDENTITY(1,1) PRIMARY KEY,
UserID INT NOT NULL REFERENCES dbo.Users(UserID),
Title NVARCHAR(200) NOT NULL,
Body NVARCHAR(MAX) NOT NULL,
CreatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
);
IF OBJECT_ID('dbo.Events') IS NULL
CREATE TABLE dbo.Events
(
EventID BIGINT IDENTITY(1,1) PRIMARY KEY,
OccurredAt DATETIME2 NOT NULL,
EventType NVARCHAR(50) NOT NULL,
Payload NVARCHAR(4000) NULL
);
-- INDEXES
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name='IX_Users_CreatedAt' AND object_id=OBJECT_ID('dbo.Users'))
CREATE INDEX IX_Users_CreatedAt ON dbo.Users(CreatedAt);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name='IX_Products_Category' AND object_id=OBJECT_ID('dbo.Products'))
CREATE INDEX IX_Products_Category ON dbo.Products(Category);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name='IX_Orders_OrderDate' AND object_id=OBJECT_ID('dbo.Orders'))
CREATE INDEX IX_Orders_OrderDate ON dbo.Orders(OrderDate);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name='IX_OrderItems_OrderID' AND object_id=OBJECT_ID('dbo.OrderItems'))
CREATE INDEX IX_OrderItems_OrderID ON dbo.OrderItems(OrderID);
-- VIEWS
IF OBJECT_ID('dbo.v_OrderSummary') IS NULL
EXEC('CREATE VIEW dbo.v_OrderSummary AS
SELECT o.OrderID,o.UserID,o.OrderDate,
COUNT(oi.OrderItemID) AS ItemCount,
SUM(oi.Quantity*oi.UnitPrice) AS OrderTotal
FROM dbo.Orders o
JOIN dbo.OrderItems oi ON oi.OrderID=o.OrderID
GROUP BY o.OrderID,o.UserID,o.OrderDate;');
-- FUNCTIONS
IF OBJECT_ID('dbo.udf_SalesTax') IS NULL
EXEC('CREATE FUNCTION dbo.udf_SalesTax(@amount DECIMAL(10,2),@rate DECIMAL(5,2))
RETURNS DECIMAL(12,2)
AS BEGIN RETURN ROUND(@amount*(@rate/100.0),2); END');
IF OBJECT_ID('dbo.itvf_OrdersByUser') IS NULL
EXEC('CREATE FUNCTION dbo.itvf_OrdersByUser(@UserID INT)
RETURNS TABLE AS RETURN
SELECT o.OrderID,o.UserID,o.OrderDate,SUM(oi.Quantity*oi.UnitPrice) AS OrderTotal
FROM dbo.Orders o JOIN dbo.OrderItems oi ON oi.OrderID=o.OrderID
WHERE o.UserID=@UserID GROUP BY o.OrderID,o.UserID,o.OrderDate;');
-- STORED PROCEDURES
IF OBJECT_ID('dbo.usp_GetTopCustomers') IS NULL
EXEC('CREATE PROCEDURE dbo.usp_GetTopCustomers
@From DATETIME2,@To DATETIME2,@TopN INT=10
AS BEGIN
SET NOCOUNT ON;
SELECT TOP(@TopN) u.UserID,u.Username,SUM(oi.Quantity*oi.UnitPrice) AS Spend
FROM dbo.Users u
JOIN dbo.Orders o ON o.UserID=u.UserID AND o.OrderDate>=@From AND o.OrderDate<@To
JOIN dbo.OrderItems oi ON oi.OrderID=o.OrderID
GROUP BY u.UserID,u.Username
ORDER BY Spend DESC;
END');
-- NUMBERS TABLE
IF OBJECT_ID('dbo.Numbers') IS NOT NULL
DROP TABLE dbo.Numbers
PRINT 'Populating numbers table';
SELECT TOP 10000000
IDENTITY(INT,1,1) AS N
INTO dbo.Numbers
FROM master.dbo.syscolumns sc1
CROSS JOIN master.dbo.syscolumns sc2
CROSS JOIN master.dbo.syscolumns sc3
CROSS JOIN master.dbo.syscolumns sc4
CROSS JOIN master.dbo.syscolumns sc5;
PRINT 'Numbers table populated, add primary key';
ALTER TABLE dbo.Numbers ADD CONSTRAINT PK_Numbers_N PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100;
PRINT 'Grant permissions';
GRANT SELECT, REFERENCES ON dbo.Numbers TO PUBLIC;
-- POPULATE TABLES
IF OBJECT_ID('tempdb..#first_name') IS NOT NULL
DROP TABLE #first_name;
CREATE TABLE #first_name (
first_name NVARCHAR(200) NOT NULL
);
DECLARE @raw NVARCHAR(MAX) = N'
aaron
abas
abbie
abby
abdul
abel
abelardo
abelrai
abigail
abisara
abogada
abogados
abraham
abrey
abril
achille
adam
adamn
adams
adan
adar
adel
adele
aden
adi
adimarys
adolfo
adria
adrian
adriana
adriane
adriann
adrianni
adriano
adrianus
adrien
adrienne
afrim
agathe
aggie
agnes
agnieszka
agostina
aguilar
agustin
ahlam
ahmay
ahmed
aida
aide
aiden
aileen
ailyn
aime
aimee
airnbn
aisha
akhil
aki
akiko
alaeddin
alain
alan
alana
alanna
alannah
alayne
alba
albañil
albert
alberto
albina
aldo
aldryn
ale
alec
aleena
alegario
alejandra
alejandro
aleksandra
aleman
alena
aleshia
alessandra
alessandro
aleta
alethia
aletia
alex
alexa
alexander
alexandra
alexandre
alexandrea
alexi
alexia
alexis
aleyda
alfonso
alfonzo
alfred
alfredo
alia
alice
alicen
alicia
alida
alie
alina
aline
alisa
alison
alissa
alix
alixandra
aliya
aliyah
aliz
aliza
all
allan
allen
allesandro
allesdandro
allie
allina
allison
ally
allyn
allyson
alma
almadelia
alna
alon
alona
alondra
alonso
alosnos
altilano
aluaro
alvaro
alya
alyse
alyson
alyssa
alyx
ama
aman
amanda
amandine
amando
amansala
amar
amarilis
amber
amdia
ame
amee
amelia
amelie
amerson
ami
amie
amigo
amigos
amir
amisha
amit
amith
amity
amma
ammar
amor
amy
amyjo
ana
anabel
anais
analia
analida
analise
anamaria
anamary
ananda
ananya
anastasia
anayeli
anca
ancelmo
anda
andersson
andra
andre
andrea
andreas
andreja
andres
andrew
andrews
andrey
anduena
andy
andye
ane
anel
anella
angel
angela
angele
angeles
angelica
angelina
angeline
angelo
angelynn
angie
angy
anh
ani
anibal
anica
anie
anika
anim
anina
anique
anirudh
anis
anissa
anita
anjali
anjie
ann
anna
annabela
annabelle
annalee
annalisa
anne
anneliese
annelise
annemaria
annemarie
annette
annie
annigna
another
anouk
anthea
anthony
antje
antoine
anton
antonio
antony
anu
anupama
anurag
anya
anzhelika
aparna
april
apryl
aquilino
aquilio
aracely
arash
arava
araya
arden
area
areli
arely
argelia
ariana
ariane
arianna
ariel
arielle
arizona
arlene
arleta
arlyne
arman
armando
armonia
arnaud
arnold
arthur
arthurs
artur
arturo
aruni
arvand
ash
asha
ashlee
ashleigh
ashley
ashlyn
aspe
assadour
asusena
athena
ati
atkins
atsuko
attree
aubree
auction
audra
audrey
audria
aundrea
aura
aurelia
aurelie
aurellie
aureo
aurora
aurore
austin
auten
ava
avelardo
avendano
avery
aviel
avila
aviva
awa
axel
aydee
ayesha
aygline
aylee
ayme
aymeric
ayse
azalea
babak
babi
bahareh
bahi
bahman
bailey
baili
baillargeault
balaouris
band
banelly
banks
barb
barbara
barbro
bardia
barnshaw
barreau
barrett
barrow
barry
bart
baruch
bas
bashi
basia
baudel
bea
beach
beata
beate
beatrice
beatriz
becca
becci
bech
bechmann
becki
becky
beldon
belen
belgica
belinda
bell
bella
bellin
belson
ben
benay
benedetta
benedicte
benedikt
bener
benigno
benito
benjamin
benn
bennet
benoit
bercy
berenice
berit
berkowitz
berliat
bernadette
bernard
bernardino
bernardo
bernd
bernice
berry
bessette
beth
bethany
betsy
bette
betti
bettina
betts
betty
betzy
bevan
beverly
bevin
bhargavi
biana
bianca
bici
bieta
bigler
bijan
bike
biken
bikes
bill
billie
billy
binfoh
binh
birgir
birgitta
bittia
bizanti
bjorn
blackman
blain
blaine
blaise
blake
blanca
blass
blathnaid
bleachclub
block
blockeado
blocked
blocking
bloq
bloquada
bloque
bloqueada
bloqueado
bloquedado
bloquedo
bloqueo
blythe
bob
bobbie
bobby
bodega
body
bonita
bonnal
bonnie
bony
booking
boqueano
boris
borka
bouchier
boutique
bowen
bracelet
brad
bradbury
braden
bradley
bradshaw
braedi
braga
branden
brandi
brandom
brandon
brandy
braysher
bre
breann
breanna
breen
breezy
brehan
brenda
brendan
brenna
brent
bret
breton
brett
bria
brian
briana
brianna
brianne
bridget
bridgette
brie
briese
brigette
brigid
brigitte
brion
britany
britney
britny
britt
britta
brittany
brittnay
britty
broadman
brockie
brook
brooke
brookelyn
bruce
bruna
bruno
brusovanik
bryan
brynn
brynne
buchan
burgess
burley
butler
cafetería
cahuich
caitla
caitlan
caitlin
caitlyn
caity
caleb
calin
callaghan
callista
cally
calum
calvin
cam
cambria
cameron
camila
camilla
camille
camilo
campbell
camper
campos
can
cancelled
candace
candelaria
candiano
candice
candie
candince
candyce
canosa
cantu
cappy
cara
caren
carey
carin
carina
carine
cark
carl
carla
carley
carlie
carling
carlitos
carlo
carlos
carlotta
carlson
carly
carmen
carmina
caro
carol
carol
carola
carole
caroliine
carolina
caroline
carolyn
carolynn
caron
caroti
carrie
carter
carwen
caryn
casa
casandra
casey
cash
casilda
casper
cassandra
cassidy
cassie
cassy
cat
catalan
catalina
catarina
catherine
cathi
cathleen
cathryn
cathy
caviccinow
cayetana
cecilia
cecilie
cecily
cedric
cee
celeste
celia
celian
celine
cemile
cerbone
ceres
cesar
cezar
ch5
chaaban
chad
chadwick
chalars
chanda
chandra
chanler
chano
chantal
chantale
chantelle
chapman
char
charee
charlene
charles
charlie
charlot
charlotte
chas
chasity
chasty
chatty
chavez
chef
chelsea
chelsey
chelsy
chema
cheng
chenin
cheree
cheria
cherie
cheryl
cheslea
chesney
cheyenne
chiara
chica
chiho
chilina
chin
chinitas
chinwe
chloe
chocki
chong
chou
chris
chrissy
christa
christaine
christelle
christi
christian
christiane
christiansen
christie
christina
christine
christinne
christoph
christophe
christopher
christy
chrysti
chuck
chuckl
chyna
chynna
ciara
cid
cinthhia
cinthia
cinthya
cintia
cintya
citlalli
cittone
claid
clair
claire
clara
clare
clase
clases
class
classe
classes
claude
claudia
claudio
clauvin
clay
clayton