Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
3077 lines (2614 loc) · 106 KB
/
Copy pathexample_test.go
File metadata and controls
3077 lines (2614 loc) · 106 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
package sqlite
import (
"context"
"database/sql"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/1set/starlet"
"github.com/starpkg/base"
"go.starlark.net/starlark"
)
// Sections: script examples; row/file limits; UDF conversion and concurrency;
// host function policy and local/remote connection boundaries.
// funcNameCounter makes custom-function names unique within a process. The
// register_function registry is process-global, so reusing a name across runs
// (e.g. under -count>1) would fail with "already registered"; a per-call suffix
// keeps registration-based tests repeatable.
var funcNameCounter int64
func uniqueFuncName(prefix string) string {
return fmt.Sprintf("%s_%d", prefix, atomic.AddInt64(&funcNameCounter, 1))
}
// TestStarlarkScripts runs Starlark test scripts from the test directory.
// Scripts with "test-" prefix should succeed, "panic-" prefix should fail.
func TestStarlarkScripts(t *testing.T) {
scriptDir := filepath.Join("..", "test", ModuleName)
runDir := filepath.Join(t.TempDir(), ModuleName)
if err := os.MkdirAll(runDir, 0o755); err != nil {
t.Fatalf("failed to create Starlark test run directory: %v", err)
}
scripts, err := filepath.Glob(filepath.Join(scriptDir, "*.star"))
if err != nil {
t.Fatalf("failed to list Starlark tests: %v", err)
}
for _, scriptPath := range scripts {
content, err := os.ReadFile(scriptPath)
if err != nil {
t.Fatalf("failed to read %q: %v", scriptPath, err)
}
dst := filepath.Join(runDir, filepath.Base(scriptPath))
if err := os.WriteFile(dst, content, 0o644); err != nil {
t.Fatalf("failed to copy %q: %v", scriptPath, err)
}
}
// Create a module factory function that returns a fresh module loader for each test
moduleFactory := func() starlet.ModuleLoader {
return NewModule().LoadModule()
}
extraModules := []string{"go_idiomatic"}
// Use the helper function from the base package
base.RunStarlarkTests(t, ModuleName, moduleFactory, extraModules, runDir)
}
func testConfigOption[T any](name, description string, value T) *base.ConfigOption[T] {
return genConfigOption(name, description, value).WithValue(value)
}
func newTestModuleWithConfig(database string, maxRows int, restrictFileAccess bool) *Module {
m := newModuleWithOptions(
testConfigOption(configKeyDatabase, "Path to SQLite database (use :memory: for in-memory)", database),
testConfigOption(configKeyTimeout, "Connection timeout in seconds", defaultTimeout),
testConfigOption(configKeyBusyTimeout, "Busy timeout in seconds", defaultBusyTimeout),
testConfigOption(configKeyForeignKeys, "Enable foreign key constraints", defaultForeignKeys),
testConfigOption(configKeyJournalMode, "Journal mode (WAL, DELETE, TRUNCATE, PERSIST, MEMORY, OFF)", defaultJournalMode),
testConfigOption(configKeySynchronous, "Synchronous mode (FULL, NORMAL, OFF)", defaultSynchronous),
testConfigOption(configKeyCacheSize, "Cache size in number of pages", defaultCacheSize),
testConfigOption(configKeyMaxRows, "Maximum rows returned by query helpers (0 means unlimited)", maxRows),
)
m.restrictFileAccess = restrictFileAccess
return m
}
func runSQLiteScript(t *testing.T, script string, moduleFactory func() starlet.ModuleLoader) error {
t.Helper()
s := starlet.NewDefault()
s.AddLazyloadModules(map[string]starlet.ModuleLoader{
ModuleName: moduleFactory(),
})
_, err := s.RunScript([]byte(script), nil)
return err
}
func requireSQLiteScript(t *testing.T, script string, moduleFactory func() starlet.ModuleLoader) {
t.Helper()
if err := runSQLiteScript(t, script, moduleFactory); err != nil {
t.Fatalf("script failed: %v", err)
}
}
func requireSQLiteScriptErrorContains(t *testing.T, script string, moduleFactory func() starlet.ModuleLoader, want string) {
t.Helper()
err := runSQLiteScript(t, script, moduleFactory)
if err == nil {
t.Fatalf("expected script error containing %q", want)
}
if !strings.Contains(err.Error(), want) {
t.Fatalf("expected script error containing %q, got %v", want, err)
}
}
func quoteStarlarkString(s string) string {
return fmt.Sprintf("%q", s)
}
func TestMaxRows(t *testing.T) {
const unrestrictedScript = `
load("sqlite", "connect")
def main():
db = connect(":memory:")
db.execute("CREATE TABLE rows (id INTEGER PRIMARY KEY)")
for i in range(10):
db.execute("INSERT INTO rows (id) VALUES (?)", [i])
queried = db.query("SELECT id FROM rows ORDER BY id")
if len(queried) != 10:
fail("expected 10 queried rows, got {}".format(len(queried)))
selected = db.select("rows", ["id"], order_by="id")
if len(selected) != 10:
fail("expected 10 selected rows, got {}".format(len(selected)))
stmt = db.prepare_query("SELECT id FROM rows ORDER BY id")
prepared = stmt.query()
if len(prepared) != 10:
fail("expected 10 prepared rows, got {}".format(len(prepared)))
stmt.close()
tx = db.begin()
tx_result = tx.query("SELECT id FROM rows ORDER BY id")
if not tx_result.ok:
fail("transaction query failed: {}".format(tx_result.error))
if len(tx_result.value) != 10:
fail("expected 10 transaction rows, got {}".format(len(tx_result.value)))
tx.rollback()
db.close()
main()
`
requireSQLiteScript(t, unrestrictedScript, func() starlet.ModuleLoader {
return newTestModuleWithConfig(defaultDatabase, 0, false).LoadModule()
})
}
// TestMaxRowsAtLimit verifies a result set exactly at the limit is allowed.
func TestMaxRowsAtLimit(t *testing.T) {
const atLimitScript = `
load("sqlite", "connect")
def main():
db = connect(":memory:")
db.execute("CREATE TABLE rows (id INTEGER PRIMARY KEY)")
for i in range(3):
db.execute("INSERT INTO rows (id) VALUES (?)", [i])
if len(db.query("SELECT id FROM rows ORDER BY id")) != 3:
fail("db.query should allow rows at the limit")
if len(db.select("rows", ["id"], order_by="id")) != 3:
fail("db.select should allow rows at the limit")
stmt = db.prepare_query("SELECT id FROM rows ORDER BY id")
if len(stmt.query()) != 3:
fail("prepared query should allow rows at the limit")
stmt.close()
tx = db.begin()
tx_result = tx.query("SELECT id FROM rows ORDER BY id")
if not tx_result.ok:
fail("transaction query should allow rows at the limit: {}".format(tx_result.error))
if len(tx_result.value) != 3:
fail("transaction query should return rows at the limit")
tx.rollback()
db.close()
main()
`
requireSQLiteScript(t, atLimitScript, func() starlet.ModuleLoader {
return newTestModuleWithConfig(defaultDatabase, 3, false).LoadModule()
})
}
// TestMaxRowsDBQueryExceeds verifies db.query past the limit returns an error.
func TestMaxRowsDBQueryExceeds(t *testing.T) {
const exceedsQueryScript = `
load("sqlite", "connect")
def main():
db = connect(":memory:")
db.execute("CREATE TABLE rows (id INTEGER PRIMARY KEY)")
for i in range(3):
db.execute("INSERT INTO rows (id) VALUES (?)", [i])
db.query("SELECT id FROM rows ORDER BY id")
main()
`
requireSQLiteScriptErrorContains(t, exceedsQueryScript, func() starlet.ModuleLoader {
return newTestModuleWithConfig(defaultDatabase, 2, false).LoadModule()
}, "query result exceeds max_rows limit (2)")
}
// TestMaxRowsTransactionExceeds verifies a tx query past the limit surfaces an error result.
func TestMaxRowsTransactionExceeds(t *testing.T) {
const exceedsTransactionScript = `
load("sqlite", "connect")
def main():
db = connect(":memory:")
db.execute("CREATE TABLE rows (id INTEGER PRIMARY KEY)")
for i in range(3):
db.execute("INSERT INTO rows (id) VALUES (?)", [i])
tx = db.begin()
tx_result = tx.query("SELECT id FROM rows ORDER BY id")
if tx_result.ok:
fail("transaction query should have failed")
if "query result exceeds max_rows limit (2)" not in tx_result.error:
fail("unexpected transaction query error: {}".format(tx_result.error))
tx.rollback()
db.close()
main()
`
requireSQLiteScript(t, exceedsTransactionScript, func() starlet.ModuleLoader {
return newTestModuleWithConfig(defaultDatabase, 2, false).LoadModule()
})
}
func TestFileAccessRestriction(t *testing.T) {
restrictedErr := "file database access is restricted by the host; only in-memory or the host-configured database is allowed"
t.Run("default allows file database", func(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "default.db")
script := fmt.Sprintf(`
load("sqlite", "connect")
def main():
db = connect(database=%s)
db.execute("CREATE TABLE t (id INTEGER)")
db.close()
main()
`, quoteStarlarkString(dbPath))
requireSQLiteScript(t, script, func() starlet.ModuleLoader {
return NewModule().LoadModule()
})
})
t.Run("restricted rejects file database", func(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "restricted.db")
script := fmt.Sprintf(`
load("sqlite", "connect")
def main():
connect(database=%s)
main()
`, quoteStarlarkString(dbPath))
requireSQLiteScriptErrorContains(t, script, func() starlet.ModuleLoader {
return NewModuleWithFileAccess(false).LoadModule()
}, restrictedErr)
})
t.Run("restricted allows memory database", func(t *testing.T) {
const script = `
load("sqlite", "connect")
def main():
db = connect(":memory:")
db.execute("CREATE TABLE t (id INTEGER)")
db.close()
main()
`
requireSQLiteScript(t, script, func() starlet.ModuleLoader {
return NewModuleWithFileAccess(false).LoadModule()
})
})
t.Run("restricted allows host configured database", func(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "host.db")
t.Setenv("SQLITE_DATABASE", dbPath)
const script = `
load("sqlite", "connect")
def main():
db = connect()
db.execute("CREATE TABLE t (id INTEGER)")
db.close()
main()
`
requireSQLiteScript(t, script, func() starlet.ModuleLoader {
return NewModuleWithFileAccess(false).LoadModule()
})
})
t.Run("restricted rejects file attach", func(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "attached.db")
script := fmt.Sprintf(`
load("sqlite", "connect")
def main():
db = connect(":memory:")
db.attach(%s, "attached")
main()
`, quoteStarlarkString(dbPath))
requireSQLiteScriptErrorContains(t, script, func() starlet.ModuleLoader {
return NewModuleWithFileAccess(false).LoadModule()
}, "file database attach is restricted by the host; only in-memory databases are allowed")
})
}
func TestPanickingRegisteredFunctionReturnsError(t *testing.T) {
regFunc := ®isteredFunction{
name: "TEST_PANIC",
starlarkFunc: starlark.NewBuiltin("TEST_PANIC", func(_ *starlark.Thread, _ *starlark.Builtin, _ starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
panic("boom")
}),
}
wrapper := createGoFunctionWrapper(regFunc)
_, err := wrapper(nil, nil)
if err == nil {
t.Fatal("expected panic to be returned as an error")
}
if !strings.Contains(err.Error(), `custom function "TEST_PANIC" panicked: boom`) {
t.Fatalf("unexpected panic error: %v", err)
}
}
func TestExamples(t *testing.T) {
tests := []struct {
name string
script string
}{
{"BasicExample", `
# Load the sqlite module
load("sqlite", "connect")
def main():
# Connect to an in-memory database with timeout configuration
db = connect(":memory:", timeout=30.0, busy_timeout=5.0)
# Create a users table
db.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
age INTEGER
)
""")
# Insert some data
db.execute("INSERT INTO users (name, email, age) VALUES (?, ?, ?)", ["Alice", "alice@example.com", 30])
db.execute("INSERT INTO users (name, email, age) VALUES (?, ?, ?)", ["Bob", "bob@example.com", 25])
# Query data
rows = db.query("SELECT * FROM users ORDER BY age DESC")
for row in rows:
print("Name: {}, Age: {}".format(row["name"], row["age"]))
# Prepared statement
stmt = db.prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)")
stmt.execute(["Charlie", "charlie@example.com", 35])
stmt.close()
# Transaction
tx = db.begin()
update_result = tx.execute("UPDATE users SET age = age + 1 WHERE name = ?", ["Alice"])
if update_result.ok:
commit_result = tx.commit()
if not commit_result.ok:
fail("Failed to commit transaction: {}".format(commit_result.error))
else:
fail("Failed to update user age: {}".format(update_result.error))
# Query with parameters
user = db.query_one("SELECT * FROM users WHERE name = ?", ["Alice"])
if user:
print("Alice's new age: {}".format(user["age"]))
# Verify age was incremented properly
if user["age"] != 31:
fail("Expected Alice's age to be 31, but got {}".format(user["age"]))
else:
fail("Failed to find Alice in database")
# High-level table operations
db.create_table("products", {
"id": "INTEGER PRIMARY KEY",
"name": "TEXT NOT NULL",
"price": "REAL DEFAULT 0.0"
})
# Insert records
product_id = db.insert("products", {"name": "Laptop", "price": 999.99})
print("Inserted product with ID: {}".format(product_id))
# Query the table
rows = db.query("SELECT * FROM products")
for row in rows:
print("Product: {}, Price: {}".format(row["name"], row["price"]))
# Verify product was inserted correctly
if row["name"] != "Laptop" or row["price"] != 999.99:
fail("Product values don't match: expected Laptop/999.99, got {}/{}".format(
row["name"], row["price"]))
# Verify the row count
count = db.count("products")
if count != 1:
fail("Expected 1 product, found {}".format(count))
# Close the connection
db.close()
print("✓ All verifications passed")
main()
`},
{"TransactionErrorHandling", `
load("sqlite", "connect")
def main():
"""Test the new OperationResult-based transaction error handling."""
print("Testing OperationResult-based transaction error handling...")
# Connect to an in-memory database
db = connect(":memory:")
# Create test table
db.execute("""
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
balance REAL NOT NULL DEFAULT 0.0
)
""")
# Insert test data
db.execute("INSERT INTO accounts (id, name, balance) VALUES (1, 'Alice', 1000.0)")
db.execute("INSERT INTO accounts (id, name, balance) VALUES (2, 'Bob', 500.0)")
# Test 1: Successful transaction operations
print("Test 1: Successful operations")
tx = db.begin()
# Test successful execute
debit_result = tx.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", [100.0, 1])
if not debit_result.ok:
fail("Execute should succeed: {}".format(debit_result.error))
if debit_result.value != 1: # 1 row affected
fail("Expected 1 row affected, got {}".format(debit_result.value))
print("✓ Execute result: ok={}, value={}".format(debit_result.ok, debit_result.value))
# Test successful query
balance_result = tx.query("SELECT * FROM accounts WHERE id = 1")
if not balance_result.ok:
fail("Query should succeed: {}".format(balance_result.error))
if len(balance_result.value) != 1:
fail("Expected 1 result row")
print("✓ Query result: ok={}, rows={}".format(balance_result.ok, len(balance_result.value)))
# Test successful query_one
one_result = tx.query_one("SELECT balance FROM accounts WHERE id = 1")
if not one_result.ok:
fail("Query_one should succeed: {}".format(one_result.error))
if one_result.value["balance"] != 900.0:
fail("Expected balance to be 900.0, got {}".format(one_result.value["balance"]))
print("✓ Query_one result: ok={}, balance={}".format(one_result.ok, one_result.value["balance"]))
# Test successful commit
commit_result = tx.commit()
if not commit_result.ok:
fail("Commit should succeed: {}".format(commit_result.error))
print("✓ Commit result: ok={}".format(commit_result.ok))
# Test 2: Error handling - SQL error
print("Test 2: SQL error handling")
tx2 = db.begin()
# Try to execute invalid SQL
bad_result = tx2.execute("INVALID SQL STATEMENT")
if bad_result.ok:
fail("Invalid SQL should fail")
if bad_result.error == "":
fail("Error message should not be empty")
print("✓ SQL error caught: {}".format(bad_result.error))
# Transaction should still be usable after error
good_result = tx2.execute("SELECT COUNT(*) as count FROM accounts")
if not good_result.ok:
fail("Transaction should still be usable after SQL error")
tx2.rollback() # Clean up
# Test 3: Error handling - constraint violation
print("Test 3: Constraint violation")
tx3 = db.begin()
# Try to insert duplicate unique key
dup_result = tx3.execute("INSERT INTO accounts (id, name, balance) VALUES (3, 'Alice', 100.0)")
if dup_result.ok:
fail("Duplicate name should violate unique constraint")
if "UNIQUE constraint failed" not in dup_result.error:
fail("Expected UNIQUE constraint error, got: {}".format(dup_result.error))
print("✓ Constraint error caught: {}".format(dup_result.error))
tx3.rollback()
# Test 4: No rows found (not an error)
print("Test 4: No rows scenarios")
tx4 = db.begin()
# Query with no results
empty_query = tx4.query("SELECT * FROM accounts WHERE id = 999")
if not empty_query.ok:
fail("Query with no results should succeed with empty list")
if len(empty_query.value) != 0:
fail("Expected empty result list")
print("✓ Empty query result: ok={}, rows={}".format(empty_query.ok, len(empty_query.value)))
# Query_one with no results
empty_one = tx4.query_one("SELECT * FROM accounts WHERE id = 999")
if not empty_one.ok:
fail("Query_one with no results should succeed with None")
if empty_one.value != None:
fail("Expected None result")
print("✓ Empty query_one result: ok={}, value={}".format(empty_one.ok, empty_one.value))
tx4.commit()
# Test 5: Rollback still fails on error (as designed)
print("Test 5: Rollback behavior")
tx5 = db.begin()
tx5.execute("INSERT INTO accounts (id, name, balance) VALUES (3, 'Charlie', 200.0)")
# Normal rollback should work
tx5.rollback()
print("✓ Normal rollback works")
# Verify data was rolled back
charlie = db.query_one("SELECT * FROM accounts WHERE name = 'Charlie'")
if charlie != None:
fail("Charlie should not exist after rollback")
db.close()
print("✓ All OperationResult tests passed")
main()
`},
{"Transactions", `
load("sqlite", "connect")
def main():
# Connect to an in-memory database
db = connect(":memory:")
# Set up test data
db.execute("""
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
balance REAL NOT NULL DEFAULT 0.0
)
""")
# Insert initial accounts
db.insert("accounts", {"id": 1, "name": "Alice", "balance": 1000.0})
db.insert("accounts", {"id": 2, "name": "Bob", "balance": 500.0})
# Verify initial balances
alice_initial = db.query_one("SELECT balance FROM accounts WHERE id = 1")
bob_initial = db.query_one("SELECT balance FROM accounts WHERE id = 2")
if alice_initial["balance"] != 1000.0:
fail("Initial Alice balance incorrect: {}".format(alice_initial["balance"]))
if bob_initial["balance"] != 500.0:
fail("Initial Bob balance incorrect: {}".format(bob_initial["balance"]))
# Function that transfers money using a transaction
def transfer_money(from_id, to_id, amount):
tx = db.begin()
# Check if from_account has sufficient funds
from_account_result = tx.query_one("SELECT * FROM accounts WHERE id = ?", [from_id])
if not from_account_result.ok:
print("Failed to check account: {}".format(from_account_result.error))
tx.rollback()
return False
from_account = from_account_result.value
if not from_account or from_account["balance"] < amount:
print("Insufficient funds, rolling back")
tx.rollback()
return False
# Update balances
debit_result = tx.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", [amount, from_id])
if not debit_result.ok:
print("Failed to debit account: {}".format(debit_result.error))
tx.rollback()
return False
credit_result = tx.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", [amount, to_id])
if not credit_result.ok:
print("Failed to credit account: {}".format(credit_result.error))
tx.rollback()
return False
# Commit the transaction
commit_result = tx.commit()
if not commit_result.ok:
print("Failed to commit transaction: {}".format(commit_result.error))
return False
print("Transfer successful")
return True
# Successful transfer
transfer_result = transfer_money(1, 2, 200.0)
if not transfer_result:
fail("Expected successful transfer")
# Verify balances after successful transfer
alice = db.query_one("SELECT * FROM accounts WHERE id = 1")
bob = db.query_one("SELECT * FROM accounts WHERE id = 2")
print("Alice balance: {}, Bob balance: {}".format(alice["balance"], bob["balance"]))
# Verify exact amounts
if alice["balance"] != 800.0:
fail("Expected Alice balance to be 800.0, got {}".format(alice["balance"]))
if bob["balance"] != 700.0:
fail("Expected Bob balance to be 700.0, got {}".format(bob["balance"]))
# Failed transfer (insufficient funds)
failed_result = transfer_money(2, 1, 1000.0)
if failed_result:
fail("Transfer should have failed due to insufficient funds")
# Verify balances unchanged after failed transfer
alice_after_fail = db.query_one("SELECT balance FROM accounts WHERE id = 1")
bob_after_fail = db.query_one("SELECT balance FROM accounts WHERE id = 2")
if alice_after_fail["balance"] != 800.0:
fail("Alice balance should be unchanged at 800.0")
if bob_after_fail["balance"] != 700.0:
fail("Bob balance should be unchanged at 700.0")
# Close the connection
db.close()
print("✓ All transaction tests passed")
main()
`},
{"PreparedStatements", `
load("sqlite", "connect")
def main():
# Connect to an in-memory database
db = connect(":memory:")
# Create a test table
db.execute("""
CREATE TABLE measurements (
id INTEGER PRIMARY KEY,
sensor_id INTEGER NOT NULL,
temperature REAL NOT NULL,
humidity REAL,
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
# Create a prepared statement for inserting data
insert_stmt = db.prepare("INSERT INTO measurements (sensor_id, temperature, humidity) VALUES (?, ?, ?)")
# Insert multiple records efficiently using the prepared statement
sensor_data = [
[1, 22.5, 45.2],
[1, 22.8, 45.5],
[2, 18.2, 50.0],
[2, 18.5, 49.8],
[3, 25.1, 30.5]
]
for data in sensor_data:
insert_stmt.execute(data)
# Close the statement when done
insert_stmt.close()
# Verify the correct number of records were inserted
count = db.count("measurements", "")
if count != 5:
fail("Expected 5 measurements, found {}".format(count))
# Verify records by sensor
sensor1_count = db.count("measurements", "sensor_id = 1")
sensor2_count = db.count("measurements", "sensor_id = 2")
sensor3_count = db.count("measurements", "sensor_id = 3")
if sensor1_count != 2:
fail("Expected 2 records for sensor 1, found {}".format(sensor1_count))
if sensor2_count != 2:
fail("Expected 2 records for sensor 2, found {}".format(sensor2_count))
if sensor3_count != 1:
fail("Expected 1 record for sensor 3, found {}".format(sensor3_count))
# Create a prepared query statement
query_stmt = db.prepare_query("SELECT * FROM measurements WHERE sensor_id = ? ORDER BY temperature DESC")
# Use the prepared query multiple times with different parameters
print("Sensor 1 measurements:")
sensor1_rows = query_stmt.query([1])
row_count = 0
prev_temp = 999.9 # Ensure descending order
for row in sensor1_rows:
row_count += 1
print(" Temperature: {}, Humidity: {}".format(row["temperature"], row["humidity"]))
# Verify order and values
if row["temperature"] > prev_temp:
fail("Results not in descending temperature order")
prev_temp = row["temperature"]
if row_count != 2:
fail("Expected 2 rows for sensor 1, got {}".format(row_count))
# Similar check for sensor 2
print("Sensor 2 measurements:")
sensor2_rows = query_stmt.query([2])
if len(sensor2_rows) != 2:
fail("Expected 2 rows for sensor 2")
# Close the prepared query
query_stmt.close()
# Test a different kind of prepared query
max_temp_stmt = db.prepare_query("SELECT MAX(temperature) as max_temp FROM measurements WHERE sensor_id = ?")
max_result = max_temp_stmt.query_one([1])
if max_result["max_temp"] != 22.8:
fail("Expected max temperature for sensor 1 to be 22.8, got {}".format(max_result["max_temp"]))
max_temp_stmt.close()
# Close the database connection
db.close()
print("✓ All prepared statement tests passed")
main()
`},
{"HighLevelOperations", `
load("sqlite", "connect")
def main():
# Connect to an in-memory database
db = connect(":memory:")
# Create a table using high-level API
db.create_table("employees", {
"id": "INTEGER PRIMARY KEY",
"name": "TEXT NOT NULL",
"department": "TEXT NOT NULL",
"salary": "REAL DEFAULT 0.0",
"hire_date": "TEXT DEFAULT CURRENT_DATE"
})
# Verify table was created
if not db.table_exists("employees"):
fail("employees table should exist")
# Insert records using the high-level API
id1 = db.insert("employees", {"name": "John Doe", "department": "Engineering", "salary": 85000})
id2 = db.insert("employees", {"name": "Jane Smith", "department": "Marketing", "salary": 75000})
# Verify IDs are as expected (SQLite should auto-assign 1, 2)
if id1 != 1:
fail("Expected first insert ID to be 1, got {}".format(id1))
if id2 != 2:
fail("Expected second insert ID to be 2, got {}".format(id2))
# Bulk insert multiple records
db.insert_many("employees", [
{"name": "Bob Johnson", "department": "Engineering", "salary": 90000},
{"name": "Alice Williams", "department": "HR", "salary": 65000},
{"name": "Charlie Brown", "department": "Engineering", "salary": 80000}
])
# Verify total record count
total_count = db.count("employees", "")
if total_count != 5:
fail("Expected 5 total employees, found {}".format(total_count))
# Count employees by department
eng_count = db.count("employees", ["department = ?", "Engineering"])
print("Engineering employees: {}".format(eng_count))
if eng_count != 3:
fail("Expected 3 Engineering employees, found {}".format(eng_count))
# Select all employees from a specific department
engineers = db.select("employees", ["name", "salary"], ["department = ?", "Engineering"], order_by="salary DESC")
print("Engineering team:")
# Verify engineers are returned in correct order (by descending salary)
if len(engineers) != 3:
fail("Expected 3 engineers, got {}".format(len(engineers)))
expected_names = ["Bob Johnson", "John Doe", "Charlie Brown"]
expected_salaries = [90000, 85000, 80000]
for i, eng in enumerate(engineers):
print(" {} - ${}".format(eng["name"], eng["salary"]))
if eng["name"] != expected_names[i] or eng["salary"] != expected_salaries[i]:
fail("Expected engineer {} to be {}, got {}".format(i, expected_names[i], eng["name"]))
# Update records
updated_rows = db.update("employees", {"salary": 95000}, ["name = ?", "Bob Johnson"])
if updated_rows != 1:
fail("Expected to update 1 row, updated {}".format(updated_rows))
# Verify the update
bob = db.query_one("SELECT * FROM employees WHERE name = ?", ["Bob Johnson"])
if bob["salary"] != 95000:
fail("Expected Bob's salary to be 95000, got {}".format(bob["salary"]))
# Upsert (update or insert)
db.upsert("employees", {"id": 1, "name": "John Doe", "department": "Engineering", "salary": 88000}, ["id"])
# Verify the update
john = db.query_one("SELECT * FROM employees WHERE name = ?", ["John Doe"])
print("John's updated salary: ${}".format(john["salary"]))
if john["salary"] != 88000:
fail("Expected John's salary to be 88000, got {}".format(john["salary"]))
# Check if a table exists
if db.table_exists("employees"):
print("Employees table exists")
# Get table information
columns = db.table_info("employees")
expected_columns = ["id", "name", "department", "salary", "hire_date"]
column_names = [col["name"] for col in columns]
for col_name in expected_columns:
if col_name not in column_names:
fail("Expected column {} not found in table schema".format(col_name))
print("Table columns:")
for col in columns:
print(" {} ({})".format(col["name"], col["type"]))
# Delete a record
deleted_rows = db.delete("employees", ["name = ?", "Alice Williams"])
if deleted_rows != 1:
fail("Expected to delete 1 row, deleted {}".format(deleted_rows))
# Verify record was deleted
alice = db.query_one("SELECT * FROM employees WHERE name = ?", ["Alice Williams"])
if alice:
fail("Alice should have been deleted but was found")
# Verify count after deletion
after_delete_count = db.count("employees", "")
if after_delete_count != 4:
fail("Expected 4 employees after deletion, found {}".format(after_delete_count))
# List all tables
tables = db.tables()
print("Database tables: {}".format(tables))
if "employees" not in tables:
fail("employees should be in the list of tables")
if len(tables) != 1:
fail("Expected 1 table, found {}".format(len(tables)))
# Close the connection
db.close()
print("✓ All high-level operation tests passed")
main()
`},
{"BatchOperations", `
load("sqlite", "connect")
def main():
# Connect to an in-memory database
db = connect(":memory:")
# Create tables using batch operations
setup_results = db.batch([
"""CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
balance REAL NOT NULL DEFAULT 0.0
)""",
"""CREATE TABLE transactions (
id INTEGER PRIMARY KEY,
from_account INTEGER,
to_account INTEGER,
amount REAL NOT NULL,
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
)""",
"CREATE INDEX idx_accounts_name ON accounts(name)"
])
if len(setup_results) != 3:
fail("Expected 3 setup results, got {}".format(len(setup_results)))
print("Setup completed. Results:", setup_results)
# Insert initial data using batch with parameters
initial_data = db.batch([
["INSERT INTO accounts (name, balance) VALUES (?, ?)", ["Alice", 1000.0]],
["INSERT INTO accounts (name, balance) VALUES (?, ?)", ["Bob", 500.0]],
["INSERT INTO accounts (name, balance) VALUES (?, ?)", ["Charlie", 750.0]]
])
if len(initial_data) != 3:
fail("Expected 3 initial data results, got {}".format(len(initial_data)))
print("Initial data inserted. Results:", initial_data)
# Verify initial data
accounts = db.query("SELECT * FROM accounts ORDER BY name")
if len(accounts) != 3:
fail("Expected 3 accounts, got {}".format(len(accounts)))
# Perform a money transfer using batch operations
transfer_amount = 200.0
transfer_results = db.batch([
["UPDATE accounts SET balance = balance - ? WHERE name = ?", [transfer_amount, "Alice"]],
["UPDATE accounts SET balance = balance + ? WHERE name = ?", [transfer_amount, "Bob"]],
["INSERT INTO transactions (from_account, to_account, amount) VALUES (?, ?, ?)", [1, 2, transfer_amount]]
])
if len(transfer_results) != 3:
fail("Expected 3 transfer results, got {}".format(len(transfer_results)))
print("Transfer completed. Results:", transfer_results)
# Test mixed batch (some with params, some without)
mixed_results = db.batch([
"UPDATE accounts SET balance = 1000.0 WHERE id = 3",
["INSERT INTO accounts (name, balance) VALUES (?, ?)", ["David", 300.0]],
"DELETE FROM transactions WHERE amount < 50.0"
])
if len(mixed_results) != 3:
fail("Expected 3 mixed results, got {}".format(len(mixed_results)))
# Verify the results
final_accounts = db.query("SELECT * FROM accounts ORDER BY name")
expected_names = ["Alice", "Bob", "Charlie", "David"]
if len(final_accounts) != 4:
fail("Expected 4 accounts after all operations, got {}".format(len(final_accounts)))
for i, account in enumerate(final_accounts):
if account["name"] != expected_names[i]:
fail("Account {} name mismatch: expected {}, got {}".format(i, expected_names[i], account["name"]))
# Verify specific balances
alice_balance = final_accounts[0]["balance"] # Alice
bob_balance = final_accounts[1]["balance"] # Bob
if alice_balance != 800.0: # 1000 - 200
fail("Alice balance should be 800.0, got {}".format(alice_balance))
if bob_balance != 700.0: # 500 + 200
fail("Bob balance should be 700.0, got {}".format(bob_balance))
# Check transaction history
transactions = db.query("SELECT * FROM transactions")
if len(transactions) != 1:
fail("Expected 1 transaction, got {}".format(len(transactions)))