123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311 |
- package main
- import (
- "context"
- "fmt"
- "log"
- "os"
- "strings"
- "time"
- "code.osinet.fr/fgm/entdemo/ent"
- "code.osinet.fr/fgm/entdemo/ent/car"
- "code.osinet.fr/fgm/entdemo/ent/group"
- "code.osinet.fr/fgm/entdemo/ent/user"
- _ "github.com/mattn/go-sqlite3"
- )
- func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
- u, err := client.User.
- Create().
- SetAge(30).
- SetName("a8m").
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed creating user: %w", err)
- }
- log.Println("user was created: ", u)
- return u, nil
- }
- func QueryUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
- const name = "a8m"
- u, err := client.User.
- Query().
- Where(user.NameEQ(name)).
- // "Only" fails if no user found or more than 1 user returned.
- Only(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed querying user %s: %w", name, err)
- }
- log.Println("user returned: ", u)
- return u, nil
- }
- func CreateCars(ctx context.Context, client *ent.Client) (*ent.User, error) {
- var err error
- name := "tesla"
- tesla, err := client.Car.
- Create().
- SetModel(name).
- SetRegisteredAt(time.Now()).
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed creating %s car: %v", name, err)
- }
- log.Println("car was created: ", tesla)
- name = "ford"
- ford, err := client.Car.
- Create().
- SetModel(name).
- SetRegisteredAt(time.Now()).
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed creating %s car: %v", name, err)
- }
- log.Println("car was created: ", ford)
- u, err := QueryUser(ctx, client)
- if err != nil {
- return nil, fmt.Errorf("failed looking for user: %w", err)
- }
- u.Update().
- AddCars(tesla, ford).
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed adding cards to user: %w", err)
- }
- return u, nil
- }
- func QueryCars(ctx context.Context, user *ent.User) error {
- cars, err := user.QueryCars().
- All(ctx)
- if err != nil {
- return fmt.Errorf("failed querying user %s cars: %w", user.Name, err)
- }
- log.Println("returned all cars: ", cars)
- ford, err := user.QueryCars().
- Where(car.ModelEQ("ford")).
- Only(ctx)
- if err != nil {
- return fmt.Errorf("failed searching for ford cars: %w", err)
- }
- log.Println("filtered cars: ", ford)
- return nil
- }
- func QueryCarUsers(ctx context.Context, u *ent.User) error {
- cars, err := u.QueryCars().All(ctx)
- if err != nil {
- return fmt.Errorf("failed querying user %s cars: %w", u.Name, err)
- }
- log.Println("returned all cars: ", cars)
- // query the inverse edge
- for _, car := range cars {
- owner, err := car.QueryOwner().Only(ctx)
- if err != nil {
- return fmt.Errorf("failed querying cat %s owner: %v", car.Model, err)
- }
- log.Printf("card %s owner: %q\n", car.Model, owner.Name)
- }
- return nil
- }
- func Open() (*ent.Client, error) {
- const db = "ent.db"
- err := os.Remove(db)
- if err != nil {
- pathErr, ok := err.(*os.PathError)
- if !ok {
- log.Fatalf("os.Remove returned a non-PathError: %w", err)
- }
- log.Printf("Error removing database: %s", pathErr.Error())
- }
- // Running client.Schema.Create will panic is DB exists already.
- client, err := ent.Open("sqlite3", strings.Join([]string{
- "file:",
- db,
- "?mode=rwc&cache=shared&_fk=1",
- },
- "",
- ))
- // client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
- return client, err
- }
- func BasicDemo(ctx context.Context, client *ent.Client) {
- u, err := CreateUser(ctx, client)
- if err != nil {
- panic(err)
- }
- _, err = QueryUser(ctx, client)
- if err != nil {
- panic(err)
- }
- _, err = CreateCars(ctx, client)
- if err != nil {
- panic(err)
- }
- err = QueryCars(ctx, u)
- if err != nil {
- panic(err)
- }
- err = QueryCarUsers(ctx, u)
- if err != nil {
- panic(err)
- }
- }
- func CreateGraph(ctx context.Context, client *ent.Client) error {
- ariel, err := client.User.
- Create().
- SetAge(30).
- SetName("ariel").
- Save(ctx)
- if err != nil {
- return err
- }
- neta, err := client.User.
- Create().
- SetAge(28).
- SetName("neta").
- Save(ctx)
- if err != nil {
- return err
- }
- // then, create the cars, and attach them to the users in the creation.
- _, err = client.Car.
- Create().
- SetModel("tesla").
- SetRegisteredAt(time.Now()). // ignore the time in the graph.
- SetOwner(ariel). // attach this graph to Ariel.
- Save(ctx)
- if err != nil {
- return err
- }
- _, err = client.Car.
- Create().
- SetModel("mazda").
- SetRegisteredAt(time.Now()). // ignore the time in the graph.
- SetOwner(ariel). // attach this graph to Ariel.
- Save(ctx)
- if err != nil {
- return err
- }
- _, err = client.Car.
- Create().
- SetModel("ford").
- SetRegisteredAt(time.Now()).
- SetOwner(neta).
- Save(ctx)
- if err != nil {
- return err
- }
- // create the groups, and add their users in the creation.
- _, err = client.Group.
- Create().
- SetName("GitLab").
- AddUsers(neta, ariel).
- Save(ctx)
- if err != nil {
- return err
- }
- _, err = client.Group.
- Create().
- SetName("GitHub").
- AddUsers(ariel).
- Save(ctx)
- if err != nil {
- return err
- }
- log.Println("The graph was created successfully")
- return nil
- }
- func QueryGithub(ctx context.Context, client *ent.Client) error {
- const name = "GitHub"
- cars, err := client.Group.
- Query().
- Where(group.Name(name)). // (Group(Name=GitHub),)
- QueryUsers(). // (User(Name=Ariel, Age=30),)
- QueryCars(). // (Car(Model=Tesla, RegisteredAt=<Time>), Car(Model=Mazda, RegisteredAt=<Time>),)
- All(ctx)
- if err != nil {
- return fmt.Errorf("failed getting %s cars: %w", name, err)
- }
- log.Println("cars returned: ", cars)
- // Output: (Car(Model=tesla, RegisteredAt=<Time>), Car(Model=mazda, RegisteredAt=<Time>),)
- return nil
- }
- // Get the cars of the users of all users in Ariel groups, except for the Mazda.
- func QueryAriel(ctx context.Context, client *ent.Client) error {
- const name = "ariel"
- // First get user ariel
- ariel := client.User.
- Query().
- Where(
- user.HasCars(), // Useless ?
- user.Name(name),
- ).
- OnlyX(ctx)
- cars, err := ariel.
- QueryGroups(). // Get Ariel's groups
- QueryUsers(). // Get the users in those groups
- QueryCars(). // Get the cars of the users in those groups
- Where(
- car.Not(
- car.ModelEQ("mazda"),
- ),
- ).
- All(ctx)
- if err != nil {
- return fmt.Errorf("failed getting %s cars: %w", name, err)
- }
- log.Println("cars returned: ", cars)
- // Output: (Car(Model=tesla, RegisteredAt=<Time>), Car(Model=ford, RegisteredAt=<Time>),)
- return nil
- }
- func QueryGroupsWithUsers(ctx context.Context, client *ent.Client) error {
- groups, err := client.Group.
- Query().
- Where(
- group.HasUsers(),
- ).
- All(ctx)
- if err != nil {
- return fmt.Errorf("failed gettings groups with users: %w", err)
- }
- log.Println("groups with users: ", groups)
- return nil
- }
- func main() {
- client, err := Open()
- if err != nil {
- log.Fatalf("failed opening connection to sqlite: %v", err)
- }
- defer client.Close()
- // Run the auto-migration tool.
- if err := client.Schema.Create(context.Background()); err != nil {
- log.Fatalf("failed creating schema resources: %v", err)
- }
- bg := context.Background()
- // BasicDemo(bg, client)
- CreateGraph(bg, client)
- QueryGithub(bg, client)
- QueryAriel(bg, client)
- QueryGroupsWithUsers(bg, client)
- }
|