mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
ent/doc: add indexes doc and example
Summary: Pull Request resolved: https://github.com/facebookexternal/fbc/pull/1380 Reviewed By: alexsn Differential Revision: D17075317 fbshipit-source-id: 021cb0bde3849af5a5d842b715a7b7dbd861c54f
This commit is contained in:
committed by
Facebook Github Bot
parent
373769dfaf
commit
e00a7d96a4
68
examples/edgeindex/edgeindex.go
Normal file
68
examples/edgeindex/edgeindex.go
Normal file
@@ -0,0 +1,68 @@
|
||||
// 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/facebookincubator/ent/examples/edgeindex/ent"
|
||||
|
||||
"github.com/facebookincubator/ent/dialect/sql"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
db, err := sql.Open("sqlite3", "file:o2o2types?mode=memory&cache=shared&_fk=1")
|
||||
if err != nil {
|
||||
log.Fatalf("failed opening connection to sqlite: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
client := ent.NewClient(ent.Driver(db))
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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