MCPcopy
hub / github.com/ent/ent / Example_recursiveTraversal

Function Example_recursiveTraversal

examples/fs/example_test.go:19–97  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

17)
18
19func Example_recursiveTraversal() {
20 client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
21 if err != nil {
22 log.Fatalf("failed opening connection to sqlite: %v", err)
23 }
24 defer client.Close()
25 ctx := context.Background()
26 // Run the auto migration tool.
27 if err := client.Schema.Create(ctx); err != nil {
28 log.Fatalf("failed creating schema resources: %v", err)
29 }
30
31 // Add multiple files in the following tree structure:
32 //
33 // a/
34 // ├─ b/
35 // │ ├─ ba
36 // │ ├─ bb
37 // │ └─ bc (deleted)
38 // ├─ c/ (deleted)
39 // │ ├─ ca
40 // │ └─ cb
41 // └─ d (deleted)
42 //
43 a := client.File.Create().SetName("a").SaveX(ctx)
44 b := client.File.Create().SetName("b").SetParent(a).SaveX(ctx)
45 client.File.Create().SetName("ba").SetParent(b).SaveX(ctx)
46 client.File.Create().SetName("bb").SetParent(b).SaveX(ctx)
47 client.File.Create().SetName("bc").SetParent(b).SetDeleted(true).SaveX(ctx)
48 c := client.File.Create().SetName("c").SetParent(a).SetDeleted(true).SaveX(ctx)
49 client.File.Create().SetName("ca").SetParent(c).SaveX(ctx)
50 client.File.Create().SetName("cb").SetParent(c).SaveX(ctx)
51 client.File.Create().SetName("d").SetParent(a).SetDeleted(true).SaveX(ctx)
52
53 // Query undeleted files:
54 //
55 // a/
56 // └─ b/
57 // ├─ ba
58 // └─ bb
59 //
60 names := client.File.Query().
61 Where(func(s *sql.Selector) {
62 t1, t2 := sql.Table(file.Table), sql.Table(file.Table)
63 with := sql.WithRecursive("undeleted", file.FieldID, file.FieldParentID)
64 with.As(
65 // The initial `SELECT` statement executed once at the start,
66 // and produces the initial row or rows for the recursion.
67 sql.Select(t1.Columns(file.FieldID, file.FieldParentID)...).
68 From(t1).
69 Where(
70 sql.And(
71 sql.IsNull(t1.C(file.FieldParentID)),
72 sql.EQ(t1.C(file.FieldDeleted), false),
73 ),
74 ).
75 // Merge the `SELECT` statement above with the following:
76 UnionAll(

Callers

nothing calls this directly

Calls 15

OpenFunction · 0.92
TableFunction · 0.92
WithRecursiveFunction · 0.92
SelectFunction · 0.92
AndFunction · 0.92
IsNullFunction · 0.92
EQFunction · 0.92
UnionAllMethod · 0.80
OnMethod · 0.80
CloseMethod · 0.65
CreateMethod · 0.65
WhereMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…