Подключение из Go
Перед тем как идти дальше, выполним следующие действия:
Install the
go-tarantool
library.Start Tarantool (locally or in Docker) and make sure that you have created and populated a database as we suggested earlier:
box.cfg{listen = 3301} s = box.schema.space.create('tester') s:format({ {name = 'id', type = 'unsigned'}, {name = 'band_name', type = 'string'}, {name = 'year', type = 'unsigned'} }) s:create_index('primary', { type = 'hash', parts = {'id'} }) s:create_index('secondary', { type = 'hash', parts = {'band_name'} }) s:insert{1, 'Roxette', 1986} s:insert{2, 'Scorpions', 2015} s:insert{3, 'Ace of Base', 1993}
Важно
Не закрывайте окно терминала с запущенным Tarantool – оно пригодится нам позднее.
Чтобы иметь возможность подключаться к Tarantool в качестве администратора, сменим пароль пользователя
admin
:box.schema.user.passwd('pass')
Простая программа, выполняющая подключение к серверу, будет выглядеть так:
package main
import (
"fmt"
"github.com/tarantool/go-tarantool"
)
func main() {
conn, err := tarantool.Connect("127.0.0.1:3301", tarantool.Opts{
User: "admin",
Pass: "pass",
})
if err != nil {
log.Fatalf("Connection refused")
}
defer conn.Close()
// Your logic for interacting with the database
}
По умолчанию используется пользователь guest
.
To insert a tuple into a space, use Insert
:
resp, err = conn.Insert("tester", []interface{}{4, "ABBA", 1972})
В этом примере в спейс tester
вставляется кортеж (4, "ABBA", 1972)
.
The response code and data are available in the tarantool.Response structure:
code := resp.Code
data := resp.Data
To select a tuple from a space, use Select:
resp, err = conn.Select("tester", "primary", 0, 1, tarantool.IterEq, []interface{}{4})
This selects a tuple by the primary key with offset = 0
and limit = 1
from a space named tester
(in our example, this is the index named primary
,
based on the id
field of each tuple).
Теперь поищем по вторичному ключу:
resp, err = conn.Select("tester", "secondary", 0, 1, tarantool.IterEq, []interface{}{"ABBA"})
Finally, it would be nice to select all the tuples in a space. But there is no one-liner for this in Go; you would need a script like this one.
For more examples, see https://github.com/tarantool/go-tarantool#usage
Обновим значение поля с помощью Update
:
resp, err = conn.Update("tester", "primary", []interface{}{4}, []interface{}{[]interface{}{"+", 2, 3}})
This increases by 3 the value of field 2
in the tuple with id = 4
.
If a tuple with this id
doesn’t exist, Tarantool will return an error.
Теперь с помощью функции Replace
мы полностью заменим кортеж с совпадающим первичным ключом. Если кортежа с указанным первичным ключом не существует, то эта операция ни к чему не приведет.
resp, err = conn.Replace("tester", []interface{}{4, "New band", 2011})
Также мы можем обновлять данные с помощью функции Upsert
, которая работает аналогично Update
, но создает новый кортеж, если старый не был найден.
resp, err = conn.Upsert("tester", []interface{}{4, "Another band", 2000}, []interface{}{[]interface{}{"+", 2, 5}})
This increases by 5 the value of the third field in the tuple with id = 4
, or
inserts the tuple (4, "Another band", 2000)
if a tuple with this id
doesn’t exist.
Чтобы удалить кортеж, воспользуемся функцией сonnection.Delete
:
resp, err = conn.Delete("tester", "primary", []interface{}{4})
Для удаления всех кортежей в спейсе (или всего спейса целиком), нужно воспользоваться функцией Call
. Мы поговорим о ней подробнее в следующем разделе.
Чтобы удалить все кортежи в спейсе, нужно вызвать функцию space:truncate
:
resp, err = conn.Call("box.space.tester:truncate", []interface{}{})
Чтобы удалить весь спейс, нужно вызвать функцию space:drop
. Для выполнения следующей команды необходимо подключиться из-под пользователя admin
:
resp, err = conn.Call("box.space.tester:drop", []interface{}{})
Перейдем в терминал с запущенным Tarantool.
Примечание
О том, как установить удаленное подключение к Tarantool, можно прочитать здесь:
Напишем простую функцию на Lua:
function sum(a, b)
return a + b
end
Итак, теперь у нас есть функция, описанная в Tarantool. Чтобы вызвать ее из go
, нам нужна функция Call
:
resp, err = conn.Call("sum", []interface{}{2, 3})
Также мы можем передать на выполнение любой Lua-код. Для этого воспользуемся функцией Eval
:
resp, err = connection.Eval("return 4 + 5", []interface{}{})