|
| 1 | +// Start Tarantool instance before example execution: |
| 2 | +// Terminal 1: |
| 3 | +// $ TT_LISTEN=3013 TT_WORK_DIR=$(mktemp -d -t 'tarantool.XXX') tarantool config.lua |
| 4 | +// |
| 5 | +// Terminal 2: |
| 6 | +// $ go test -v example_schema_test.go |
| 7 | +package tarantool_test |
| 8 | + |
| 9 | +import ( |
| 10 | + "fmt" |
| 11 | + "log" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/tarantool/go-tarantool" |
| 15 | +) |
| 16 | + |
| 17 | +func Example_schema() { |
| 18 | + server := "127.0.0.1:3013" |
| 19 | + opts := tarantool.Opts{ |
| 20 | + Timeout: 500 * time.Millisecond, |
| 21 | + Reconnect: 1 * time.Second, |
| 22 | + MaxReconnects: 3, |
| 23 | + User: "test", |
| 24 | + Pass: "test", |
| 25 | + } |
| 26 | + client, err := tarantool.Connect(server, opts) |
| 27 | + if err != nil { |
| 28 | + log.Fatalf("Failed to connect: %s", err.Error()) |
| 29 | + } |
| 30 | + |
| 31 | + // Save Schema to local variable to avoid races |
| 32 | + schema := client.Schema |
| 33 | + if schema.SpacesById == nil { |
| 34 | + log.Fatalf("schema.SpacesById is nil") |
| 35 | + } |
| 36 | + if schema.Spaces == nil { |
| 37 | + log.Fatalf("schema.Spaces is nil") |
| 38 | + } |
| 39 | + |
| 40 | + // Access Space objects by name or id |
| 41 | + space1 := schema.Spaces["test"] |
| 42 | + space2 := schema.SpacesById[514] // it's a map |
| 43 | + fmt.Printf("Space 1 ID %d %s %s\n", space1.Id, space1.Name, space1.Engine) |
| 44 | + fmt.Printf("Space 1 ID %d %t\n", space1.FieldsCount, space1.Temporary) |
| 45 | + |
| 46 | + // Access index information by name or id |
| 47 | + index1 := space1.Indexes["primary"] |
| 48 | + index2 := space2.IndexesById[3] // it's a map |
| 49 | + fmt.Printf("Index %d %s\n", index1.Id, index1.Name) |
| 50 | + |
| 51 | + // Access index fields information by index |
| 52 | + indexField1 := index1.Fields[0] // It's a slice |
| 53 | + indexField2 := index2.Fields[1] // It's a slice |
| 54 | + fmt.Println(indexField1, indexField2) |
| 55 | + |
| 56 | + // Access space fields information by name or id (index) |
| 57 | + spaceField1 := space2.Fields["name0"] |
| 58 | + spaceField2 := space2.FieldsById[3] |
| 59 | + fmt.Printf("SpaceField 1 %s %s\n", spaceField1.Name, spaceField1.Type) |
| 60 | + fmt.Printf("SpaceField 2 %s %s\n", spaceField2.Name, spaceField2.Type) |
| 61 | + |
| 62 | + // Output: |
| 63 | + // Space 1 ID 512 test memtx |
| 64 | + // Space 1 ID 0 false |
| 65 | + // Index 0 primary |
| 66 | + // &{0 unsigned} &{2 string} |
| 67 | + // SpaceField 1 name0 unsigned |
| 68 | + // SpaceField 2 name3 unsigned |
| 69 | + |
| 70 | +} |
0 commit comments