mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
examples/edgeindex: move example from main to example_test (#706)
This commit is contained in:
67
examples/edgeindex/example_test.go
Normal file
67
examples/edgeindex/example_test.go
Normal file
@@ -0,0 +1,67 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/facebook/ent/examples/edgeindex/ent"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func Example_EdgeIndex() {
|
||||
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
|
||||
if err != nil {
|
||||
log.Fatalf("failed opening connection to sqlite: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
// Run the auto migration tool.
|
||||
if err := client.Schema.Create(ctx); err != nil {
|
||||
log.Fatalf("failed creating schema resources: %v", err)
|
||||
}
|
||||
if err := Do(ctx, client); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Output:
|
||||
}
|
||||
|
||||
func Do(ctx context.Context, client *ent.Client) error {
|
||||
// Unlike `Save`, `SaveX` panics if an error occurs.
|
||||
tlv := client.City.
|
||||
Create().
|
||||
SetName("TLV").
|
||||
SaveX(ctx)
|
||||
nyc := client.City.
|
||||
Create().
|
||||
SetName("NYC").
|
||||
SaveX(ctx)
|
||||
// Add a street "ST" to "TLV".
|
||||
client.Street.
|
||||
Create().
|
||||
SetName("ST").
|
||||
SetCity(tlv).
|
||||
SaveX(ctx)
|
||||
// This operation will fail because "ST"
|
||||
// is already created under "TLV".
|
||||
_, err := client.Street.
|
||||
Create().
|
||||
SetName("ST").
|
||||
SetCity(tlv).
|
||||
Save(ctx)
|
||||
if err == nil {
|
||||
return fmt.Errorf("expecting creation to fail")
|
||||
}
|
||||
// Add a street "ST" to "NYC".
|
||||
client.Street.
|
||||
Create().
|
||||
SetName("ST").
|
||||
SetCity(nyc).
|
||||
SaveX(ctx)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user