Top.Mail.Ru
Tarantool » latest » Руководство для начинающих » Connecting from your favorite language
 
Руководство для начинающих / Connecting from your favorite language
Руководство для начинающих / Connecting from your favorite language

Connecting from your favorite language

Connecting from your favorite language

Now that you have a Tarantool database, let’s see how to connect to it from Python, PHP and Go.

Connecting from Python

Pre-requisites

Before we proceed:

  1. Install the tarantool module. We recommend using python3 and pip3.

  2. 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}
    

    Важно

    Please do not close the terminal window where Tarantool is running – you’ll need it soon.

  3. In order to connect to Tarantool as an administrator, reset the password for the admin user:

    box.schema.user.passwd('pass')
    

Connecting to Tarantool

To get connected to the Tarantool server, say this:

>>> import tarantool
>>> connection = tarantool.connect("localhost", 3301)

You can also specify the user name and password, if needed:

>>> tarantool.connect("localhost", 3301, user=username, password=password)

The default user is guest.

Manipulating the data

A space is a container for tuples. To access a space as a named object, use connection.space:

>>> tester = connection.space('tester')

Inserting data

To insert a tuple into a space, use insert:

>>> tester.insert((4, 'ABBA', 1972))
[4, 'ABBA', 1972]

Querying data

Let’s start with selecting a tuple by the primary key (in our example, this is the index named primary, based on the id field of each tuple). Use select:

>>> tester.select(4)
[4, 'ABBA', 1972]

Next, select tuples by a secondary key. For this purpose, you need to specify the number or name of the index.

First off, select tuples using the index number:

>>> tester.select('Scorpions', index=1)
[2, 'Scorpions', 2015]

(We say index=1 because index numbers in Tarantool start with 0, and we’re using our second index here.)

Now make a similar query by the index name and make sure that the result is the same:

>>> tester.select('Scorpions', index='secondary')
[2, 'Scorpions', 2015]

Finally, select all the tuples in a space via a select with no arguments:

>>> tester.select()

Updating data

Update a field value using update:

>>> tester.update(4, [('=', 1, 'New group'), ('+', 2, 2)])

This updates the value of field 1 and increases 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.

Now use replace to totally replace the tuple that matches the primary key. If a tuple with this primary key doesn’t exist, Tarantool will do nothing.

>>> tester.replace((4, 'New band', 2015))

You can also update the data using upsert that works similarly to update, but creates a new tuple if the old one was not found.

>>> tester.upsert((4, 'Another band', 2000), [('+', 2, 5)])

This increases by 5 the value of field 2 in the tuple with id = 4, – or inserts the tuple (4, "Another band", 2000) if a tuple with this id doesn’t exist.

Deleting data

To delete a tuple, use delete(primary_key):

>>> tester.delete(4)
[4, 'New group', 2012]

To delete all tuples in a space (or to delete an entire space), use call. We’ll focus on this function in more detail in the next section.

To delete all tuples in a space, call space:truncate:

>>> connection.call('box.space.tester:truncate', ())

To delete an entire space, call space:drop. This requires connecting to Tarantool as the admin user:

>>> connection.call('box.space.tester:drop', ())

Executing stored procedures

Switch to the terminal window where Tarantool is running.

Примечание

If you don’t have a terminal window with remote connection to Tarantool, check out these guides:

Define a simple Lua function:

function sum(a, b)
    return a + b
end

Now we have a Lua function defined in Tarantool. To invoke this function from python, use call:

>>> connection.call('sum', (3, 2))
5

To send bare Lua code for execution, use eval:

>>> connection.eval('return 4 + 5')
9

Connecting from PHP

Pre-requisites

Before we proceed:

  1. Install the tarantool/client library.

  2. 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}
    

    Важно

    Please do not close the terminal window where Tarantool is running – you’ll need it soon.

  3. In order to connect to Tarantool as an administrator, reset the password for the admin user:

    box.schema.user.passwd('pass')
    

Connecting to Tarantool

To get connected to the Tarantool server, say this:

use Tarantool\Client\Client;

require __DIR__.'/vendor/autoload.php';
$client = Client::fromDefaults();

You can also specify the user name and password, if needed:

$client = Client::fromOptions([
    'uri' => 'tcp://127.0.0.1:3301',
    'username' => '<username>',
    'password' => '<password>'
]);

The default user is guest.

Manipulating the data

A space is a container for tuples. To access a space as a named object, use getSpace:

$tester = $client->getSpace('tester');

Inserting data

To insert a tuple into a space, use insert:

$result = $tester->insert([4, 'ABBA', 1972]);

Querying data

Let’s start with selecting a tuple by the primary key (in our example, this is the index named primary, based on the id field of each tuple). Use select:

use Tarantool\Client\Schema\Criteria;

$result = $tester->select(Criteria::key([4]));
printf(json_encode($result));
[[4, 'ABBA', 1972]]

Next, select tuples by a secondary key. For this purpose, you need to specify the number or name of the index.

First off, select tuples using the index number:

$result = $tester->select(Criteria::index(1)->andKey(['Scorpions']));
printf(json_encode($result));
[2, 'Scorpions', 2015]

(We say index(1) because index numbers in Tarantool start with 0, and we’re using our second index here.)

Now make a similar query by the index name and make sure that the result is the same:

$result = $tester->select(Criteria::index('secondary')->andKey(['Scorpions']));
printf(json_encode($result));
[2, 'Scorpions', 2015]

Finally, select all the tuples in a space via a select:

$result = $tester->select(Criteria::allIterator());

Updating data

Update a field value using update:

use Tarantool\Client\Schema\Operations;

$result = $tester->update([4], Operations::set(1, 'New group')->andAdd(2, 2));

This updates the value of field 1 and increases 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.

Now use replace to totally replace the tuple that matches the primary key. If a tuple with this primary key doesn’t exist, Tarantool will do nothing.

$result = $tester->replace([4, 'New band', 2015]);

You can also update the data using upsert that works similarly to update, but creates a new tuple if the old one was not found.

use Tarantool\Client\Schema\Operations;

$tester->upsert([4, 'Another band', 2000], Operations::add(2, 5));

This increases by 5 the value of field 2 in the tuple with id = 4, – or inserts the tuple (4, "Another band", 2000) if a tuple with this id doesn’t exist.

Deleting data

To delete a tuple, use delete(primary_key):

$result = $tester->delete([4]);

To delete all tuples in a space (or to delete an entire space), use call. We’ll focus on this function in more detail in the next section.

To delete all tuples in a space, call space:truncate:

$result = $client->call('box.space.tester:truncate');

To delete an entire space, call space:drop. This requires connecting to Tarantool as the admin user:

$result = $client->call('box.space.tester:drop');

Executing stored procedures

Switch to the terminal window where Tarantool is running.

Примечание

If you don’t have a terminal window with remote connection to Tarantool, check out these guides:

Define a simple Lua function:

function sum(a, b)
    return a + b
end

Now we have a Lua function defined in Tarantool. To invoke this function from php, use call:

$result = $client->call('sum', 3, 2);

To send bare Lua code for execution, use eval:

$result = $client->evaluate('return 4 + 5');

Connecting from Go

Pre-requisites

Before we proceed:

  1. Install the go-tarantool library.

  2. 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}
    

    Важно

    Please do not close the terminal window where Tarantool is running – you’ll need it soon.

  3. In order to connect to Tarantool as an administrator, reset the password for the admin user:

    box.schema.user.passwd('pass')
    

Connecting to Tarantool

To get connected to the Tarantool server, write a simple Go program:

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
}

The default user is guest.

Manipulating the data

Inserting data

To insert a tuple into a space, use Insert:

resp, err = conn.Insert("tester", []interface{}{4, "ABBA", 1972})

This inserts the tuple (4, "ABBA", 1972) into a space named tester.

The response code and data are available in the tarantool.Response structure:

code := resp.Code
data := resp.Data

Querying 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).

Next, select tuples by a secondary key.

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

Updating data

Update a field value using 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.

Now use Replace to totally replace the tuple that matches the primary key. If a tuple with this primary key doesn’t exist, Tarantool will do nothing.

resp, err = conn.Replace("tester", []interface{}{4, "New band", 2011})

You can also update the data using Upsert that works similarly to Update, but creates a new tuple if the old one was not found.

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.

Deleting data

To delete a tuple, use сonnection.Delete:

resp, err = conn.Delete("tester", "primary", []interface{}{4})

To delete all tuples in a space (or to delete an entire space), use Call. We’ll focus on this function in more detail in the next section.

To delete all tuples in a space, call space:truncate:

resp, err = conn.Call("box.space.tester:truncate", []interface{}{})

To delete an entire space, call space:drop. This requires connecting to Tarantool as the admin user:

resp, err = conn.Call("box.space.tester:drop", []interface{}{})

Executing stored procedures

Switch to the terminal window where Tarantool is running.

Примечание

If you don’t have a terminal window with remote connection to Tarantool, check out these guides:

Define a simple Lua function:

function sum(a, b)
    return a + b
end

Now we have a Lua function defined in Tarantool. To invoke this function from go, use Call:

resp, err = conn.Call("sum", []interface{}{2, 3})

To send bare Lua code for execution, use Eval:

resp, err = connection.Eval("return 4 + 5", []interface{}{})