Skip to content

Update the example in module net.box #3186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions doc/how-to/getting_started_net_box.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
.. _getting_started_net_box:

Getting started with net.box
============================

The tutorial shows how to work with some common ``net.box`` methods.

For more information about the ``net.box`` module,
check the :ref:`corresponding module reference <net_box-module>`.

Sandbox configuration
---------------------

The sandbox configuration for the tutorial assumes that:

* The Tarantool instance is running on ``localhost 127.0.0.1:3301``.
* There is a space named ``tester`` with a numeric primary key.
* The space contains a tuple with the key value = ``800``.
* The current user has read, write, and execute privileges.

Use the commands below for a quick sandbox setup:

.. code-block:: lua

box.cfg{listen = 3301}
s = box.schema.space.create('tester')
s:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}})
t = s:insert({800, 'TEST'})
box.schema.user.grant('guest', 'read,write,execute', 'universe')

Creating a net.box connection
-----------------------------

First, load the ``net.box`` module with the ``require('net.box')`` method:

.. code-block:: tarantoolsession

tarantool> net_box = require('net.box')

The next step is to create a new connection.
In ``net.box``, self-connection is pre-established.
That is, ``conn = net_box.connect('localhost:3301')`` command can be replaced with the ``conn = net_box.self`` object call:

.. code-block:: tarantoolsession

tarantool> conn = net_box.self

Then, make a ping:

.. code-block:: tarantoolsession

tarantool> conn:ping()
---
- true
...

Using data operations
---------------------

Select all tuples in the ``tester`` space where the key value is ``800``:

.. code-block:: tarantoolsession

tarantool> conn.space.tester:select{800}
---
- - [800, 'TEST']
...

Insert two tuples into the space:

.. code-block:: tarantoolsession

tarantool> conn.space.tester:insert({700, 'TEST700'})
---
- [700, 'TEST700']
...
tarantool> conn.space.tester:insert({600, 'TEST600'})
---
- [600, 'TEST600']
...

After the insert, there is one tuple where the key value is ``600``.
To select this tuple, you can use the ``get()`` method.
Unlike the ``select()`` command, ``get()`` returns only one tuple that satisfies the stated condition.

.. code-block:: tarantoolsession

tarantool> conn.space.tester:get({600})
---
- [600, 'TEST600']
...

To update the existing tuple, you can use either ``update()`` or ``upsert()``.
The ``update()`` method can be used for assignment, arithmetic (if the field is numeric),
cutting and pasting fragments of a field, and deleting or inserting a field.

In this tutorial, the ``update()`` command is used to update the tuple identified by primary key value = ``800``.
The operation assigns a new value to the second field in the tuple:

.. code-block:: tarantoolsession

tarantool> conn.space.tester:update(800, {{'=', 2, 'TEST800'}})
---
- [800, 'TEST800']
...

As for the ``upsert`` function, if there is an existing tuple that matches the key field of tuple, then the command
has the same effect as ``update()``.
Otherwise, the effect is equal to the ``insert()`` method.

.. code-block:: tarantoolsession

tarantool> conn.space.tester:upsert({500, 'TEST500'}, {{'=', 2, 'TEST'}})

To delete a tuple where the key value is ``600``, run the ``delete()`` method below:

.. code-block:: tarantoolsession

tarantool> conn.space.tester:delete{600}
---
- [600, 'TEST600']
...

Then, replace the existing tuple with a new one:

.. code-block:: tarantoolsession

tarantool> conn.space.tester:replace{500, 'New data', 'Extra data'}
---
- [500, 'New data', 'Extra data']
...

Finally, select all tuples from the space:

.. code-block:: tarantoolsession

tarantool> conn.space.tester:select{}
---
- - [800, 'TEST800']
- [500, 'New data', 'Extra data']
- [700, 'TEST700']
...

Closing the connection
----------------------

In the end, close the connection when it is no longer needed:

.. code-block:: tarantoolsession

tarantool> conn:close()
---
...
1 change: 1 addition & 0 deletions doc/how-to/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ If you are new to Tarantool, please see our
getting_started_connectors
getting_started_cartridge
db/index
getting_started_net_box
vshard_quick
app/index
replication/index
Expand Down
88 changes: 2 additions & 86 deletions doc/reference/reference_lua/net_box.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ variant, to be discussed later, is for connecting to MySQL or MariaDB or Postgre
(see :ref:`SQL DBMS modules <dbms_modules>` reference). The other variant, which
is discussed in this section, is for connecting to Tarantool server instances via a
network.
For a quick start with ``net.box``, refer to the :ref:`tutorial <getting_started_net_box>`.

You can call the following methods:

Expand Down Expand Up @@ -884,89 +885,4 @@ With the ``net.box`` module, you can use the following
existing trigger functions.

Details about trigger characteristics are in the
:ref:`triggers <triggers-box_triggers>` section.

============================================================================
Example
============================================================================

This example shows the use of most of the ``net.box`` methods.

The sandbox configuration for this example assumes that:

* the Tarantool instance is running on ``localhost 127.0.0.1:3301``,
* there is a space named ``tester`` with a numeric primary key and with a tuple
that contains a key value = 800,
* the current user has read, write and execute privileges.

Here are commands for a quick sandbox setup:

.. code-block:: lua

box.cfg{listen = 3301}
s = box.schema.space.create('tester')
s:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}})
t = s:insert({800, 'TEST'})
box.schema.user.grant('guest', 'read,write,execute', 'universe')

And here starts the example:

.. code-block:: tarantoolsession

tarantool> net_box = require('net.box')
---
...
tarantool> function example()
> local conn, wtuple
> if net_box.self:ping() then
> table.insert(ta, 'self:ping() succeeded')
> table.insert(ta, ' (no surprise -- self connection is pre-established)')
> end
> if box.cfg.listen == '3301' then
> table.insert(ta,'The local server listen address = 3301')
> else
> table.insert(ta, 'The local server listen address is not 3301')
> table.insert(ta, '( (maybe box.cfg{...listen="3301"...} was not stated)')
> table.insert(ta, '( (so connect will fail)')
> end
> conn = net_box.connect('127.0.0.1:3301')
> conn.space.tester:delete({800})
> table.insert(ta, 'conn delete done on tester.')
> conn.space.tester:insert({800, 'data'})
> table.insert(ta, 'conn insert done on tester, index 0')
> table.insert(ta, ' primary key value = 800.')
> wtuple = conn.space.tester:select({800})
> table.insert(ta, 'conn select done on tester, index 0')
> table.insert(ta, ' number of fields = ' .. #wtuple)
> conn.space.tester:delete({800})
> table.insert(ta, 'conn delete done on tester')
> conn.space.tester:replace({800, 'New data', 'Extra data'})
> table.insert(ta, 'conn:replace done on tester')
> conn.space.tester:update({800}, {{'=', 2, 'Fld#1'}})
> table.insert(ta, 'conn update done on tester')
> conn:close()
> table.insert(ta, 'conn close done')
> end
---
...
tarantool> ta = {}
---
...
tarantool> example()
---
...
tarantool> ta
---
- - self:ping() succeeded
- ' (no surprise -- self connection is pre-established)'
- The local server listen address = 3301
- conn delete done on tester.
- conn insert done on tester, index 0
- ' primary key value = 800.'
- conn select done on tester, index 0
- ' number of fields = 1'
- conn delete done on tester
- conn:replace done on tester
- conn update done on tester
- conn close done
...
:ref:`triggers <triggers-box_triggers>` section.
129 changes: 129 additions & 0 deletions locale/ru/LC_MESSAGES/how-to/getting_started_net_box.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@

msgid "Getting started with net.box"
msgstr "Начало работы с net.box"

msgid "The tutorial shows how to work with some common ``net.box`` methods."
msgstr "Ниже приводится пример использования большинства методов ``net.box``."

msgid ""
"For more information about the ``net.box`` module, "
"check the :ref:`corresponding module reference <net_box-module>`."
msgstr ""
"Подробную информацию о модуле ``net.box`` вы найдете "
"в соответствующем :ref:`разделе справочника по модулям <net_box-module>`."

msgid "Sandbox configuration"
msgstr "Настройка песочницы"

msgid "The sandbox configuration for the tutorial assumes that:"
msgstr ""
"Данный пример сработает на конфигурации из песочницы, предполагается, что:"

msgid "The Tarantool instance is running on ``localhost 127.0.0.1:3301``."
msgstr "экземпляр Tarantool запущен на ``localhost 127.0.0.1:3301``;"

msgid "There is a space named ``tester`` with a numeric primary key."
msgstr "создан спейс под названием ``tester`` с первичным числовым ключом;"

msgid "The space contains a tuple with the key value = ``800``."
msgstr "спейс содержит кортеж, в котором есть ключ со значением = 800;"

msgid "The current user has read, write, and execute privileges."
msgstr "у текущего пользователя есть права на чтение, запись и выполнение."

msgid "Use the commands below for a quick sandbox setup:"
msgstr "Используйте команды ниже для быстрой настройки песочницы:"

msgid "Creating a net.box connection"
msgstr "Создание подключения"

msgid ""
"First, load the ``net.box`` module with "
"the ``require('net.box')`` method:"
msgstr ""
"Чтобы начать работу, запустите модуль ``net.box``, "
"используя команду ``require('net.box')``:"

msgid ""
"The next step is to create a new connection. "
"In ``net.box``, self-connection is pre-established. That is, "
"``conn = net_box.connect('localhost:3301')`` command can be "
"replaced with the ``conn = net_box.self`` object call:"
msgstr ""
"Далее необходимо создать новое подключение. "
"В ``net.box`` для локального Tarantool-сервера есть заданный объект ``self`` всегда "
"установленного подключения. Таким образом, команду ``conn = net_box.connect('localhost:3301')`` "
"можно заменить на вызов объекта ``conn = net_box.self``."

msgid "Then, make a ping:"
msgstr "Запустите команду ``ping()``:"

msgid "Using data operations"
msgstr "Операции с данными"

msgid "Select all tuples in the ``tester`` space where the key value is ``800``:"
msgstr "Сделайте выборку всех кортежей в спейсе ``tester``, у которых значение ключа равно ``800``:"

msgid "Insert two tuples into the space:"
msgstr "Вставьте два кортежа в спейс:"

msgid ""
"After the insert, there is one tuple where the key value is ``600``. "
"To select this tuple, you can use the ``get()`` method. "
"Unlike the ``select()`` command, ``get()`` returns only one tuple "
"that satisfies the stated condition."
msgstr ""
"После вставки в спейсе появился один кортеж со значением ключа ``600``. "
"Для выбора этого кортежа вы можете использовать метод ``get()``. "
"В отличие от команды ``select()``, метод ``get()`` возвращает только один кортеж, "
"удовлетворяющий заданным условиям."

msgid ""
"To update the existing tuple, you can use either ``update()`` or ``upsert()``. "
"The ``update()`` method can be used for assignment, "
"arithmetic (if the field is numeric), "
"cutting and pasting fragments of a field, and deleting or inserting a field."
msgstr ""
"Чтобы обновить существующий кортеж, вы можете использовать как метод ``update()``, так и метод ``upsert()``. "
"Функция ``update()`` может использоваться для присваивания, "
"арифметических операций (если поле числовое), вырезания и вставки фрагментов"
" поля, а также для удаления или вставки поля."

msgid ""
"In this tutorial, the ``update()`` command is used to update the tuple "
"identified by primary key value = ``800``. "
"The operation assigns a new value to the second field in the tuple:"
msgstr ""
"В этом руководстве команда ``update()`` используется для обновления кортежа, "
"определенного значением ключа ``800``. "
"Операция присваивает новое значение второму полю в кортеже:"

msgid ""
"As for the ``upsert`` function, if there is an existing tuple "
"that matches the key field of tuple, then the command "
"has the same effect as ``update()``. "
"Otherwise, the effect is equal to the ``insert()`` method."
msgstr ""
"Для функции ``upsert``, если уже существует кортеж, "
"который совпадает с ключевыми полями tuple, запрос приведет к тому же "
"результату, что и метод ``update()``. Если подходящего кортежа нет,"
" запрос приведет к тому же результату, что и метод ``insert()``."

msgid ""
"To delete a tuple where the key value is ``600``, "
"run the ``delete()`` method below:"
msgstr ""
"Чтобы удалить кортеж, в котором значение ключа равно ``600``, "
"запустите метод ``delete()``:"

msgid "Then, replace the existing tuple with a new one:"
msgstr "Затем замените существующий кортеж на новый:"

msgid "Finally, select all tuples from the space:"
msgstr "Наконец, сделайте выборку по всем кортежам из спейса:"

msgid "Closing the connection"
msgstr "Закрытие подключения"

msgid "In the end, close the connection when it is no longer needed:"
msgstr "Закройте соединение явным образом, когда оно больше не используется:"
Loading