Skip to content

Commit 41cd258

Browse files
committed
Add db/empty command for asserting that a table is empty
Quite often test cases need to assert that a table has been cleaned up. To avoid the unnecessary empty table file, add a command for asserting this. Signed-off-by: Jussi Maki <[email protected]>
1 parent a5e93e3 commit 41cd258

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

any_table.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ type AnyTable struct {
1515
Meta TableMeta
1616
}
1717

18+
func (t AnyTable) NumObjects(txn ReadTxn) int {
19+
indexTxn := txn.getTxn().mustIndexReadTxn(t.Meta, PrimaryIndexPos)
20+
return indexTxn.Len()
21+
}
22+
1823
func (t AnyTable) All(txn ReadTxn) iter.Seq2[any, Revision] {
1924
all, _ := t.AllWatch(txn)
2025
return all

script.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func ScriptCommands(db *DB) hive.ScriptCmdsOut {
2828
"db": DBCmd(db),
2929
"db/show": ShowCmd(db),
3030
"db/cmp": CompareCmd(db),
31+
"db/empty": EmptyCmd(db),
3132
"db/insert": InsertCmd(db),
3233
"db/delete": DeleteCmd(db),
3334
"db/get": GetCmd(db),
@@ -168,8 +169,6 @@ func ShowCmd(db *DB) script.Cmd {
168169
fs.StringP("format", "f", "table", "Format to write in (table, yaml or json)")
169170
},
170171
Detail: []string{
171-
"Show the contents of a table.",
172-
"",
173172
"The contents are written to stdout, but can be written to",
174173
"a file instead with the -o flag.",
175174
"",
@@ -354,6 +353,28 @@ func CompareCmd(db *DB) script.Cmd {
354353
})
355354
}
356355

356+
func EmptyCmd(db *DB) script.Cmd {
357+
return script.Command(
358+
script.CmdUsage{
359+
Summary: "Assert that given table(s) are empty",
360+
Args: "table",
361+
},
362+
func(s *script.State, args ...string) (script.WaitFunc, error) {
363+
txn := db.ReadTxn()
364+
for _, tableName := range args {
365+
meta := db.GetTable(txn, tableName)
366+
if meta == nil {
367+
return nil, fmt.Errorf("table %q not found", tableName)
368+
}
369+
tbl := AnyTable{Meta: meta}
370+
if n := tbl.NumObjects(txn); n != 0 {
371+
return nil, fmt.Errorf("table %q not empty, found %d obects", tableName, n)
372+
}
373+
}
374+
return nil, nil
375+
})
376+
}
377+
357378
func InsertCmd(db *DB) script.Cmd {
358379
return script.Command(
359380
script.CmdUsage{

testdata/db.txtar

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,17 @@ db/initialized test1 test2
1717
db/show test1
1818
db/show test2
1919

20+
# Assert empty
21+
db/empty test1 test2
22+
2023
# Insert
2124
db/insert test1 obj1.yaml
2225
db/insert test1 obj2.yaml
2326
db/insert test2 obj2.yaml
2427

28+
# Assert not empty
29+
! db/empty test1 test2
30+
2531
# Show (non-empty)
2632
db/show test1
2733
stdout ^ID.*Tags

0 commit comments

Comments
 (0)