Skip to content

Commit 948adeb

Browse files
authored
Update the example in module net.box (#3186)
Fixes #2271 * Rewrite the example * Move text to how-to section * Translate page, update translation
1 parent 4be17cb commit 948adeb

File tree

5 files changed

+290
-248
lines changed

5 files changed

+290
-248
lines changed
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
.. _getting_started_net_box:
2+
3+
Getting started with net.box
4+
============================
5+
6+
The tutorial shows how to work with some common ``net.box`` methods.
7+
8+
For more information about the ``net.box`` module,
9+
check the :ref:`corresponding module reference <net_box-module>`.
10+
11+
Sandbox configuration
12+
---------------------
13+
14+
The sandbox configuration for the tutorial assumes that:
15+
16+
* The Tarantool instance is running on ``localhost 127.0.0.1:3301``.
17+
* There is a space named ``tester`` with a numeric primary key.
18+
* The space contains a tuple with the key value = ``800``.
19+
* The current user has read, write, and execute privileges.
20+
21+
Use the commands below for a quick sandbox setup:
22+
23+
.. code-block:: lua
24+
25+
box.cfg{listen = 3301}
26+
s = box.schema.space.create('tester')
27+
s:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}})
28+
t = s:insert({800, 'TEST'})
29+
box.schema.user.grant('guest', 'read,write,execute', 'universe')
30+
31+
Creating a net.box connection
32+
-----------------------------
33+
34+
First, load the ``net.box`` module with the ``require('net.box')`` method:
35+
36+
.. code-block:: tarantoolsession
37+
38+
tarantool> net_box = require('net.box')
39+
40+
The next step is to create a new connection.
41+
In ``net.box``, self-connection is pre-established.
42+
That is, ``conn = net_box.connect('localhost:3301')`` command can be replaced with the ``conn = net_box.self`` object call:
43+
44+
.. code-block:: tarantoolsession
45+
46+
tarantool> conn = net_box.self
47+
48+
Then, make a ping:
49+
50+
.. code-block:: tarantoolsession
51+
52+
tarantool> conn:ping()
53+
---
54+
- true
55+
...
56+
57+
Using data operations
58+
---------------------
59+
60+
Select all tuples in the ``tester`` space where the key value is ``800``:
61+
62+
.. code-block:: tarantoolsession
63+
64+
tarantool> conn.space.tester:select{800}
65+
---
66+
- - [800, 'TEST']
67+
...
68+
69+
Insert two tuples into the space:
70+
71+
.. code-block:: tarantoolsession
72+
73+
tarantool> conn.space.tester:insert({700, 'TEST700'})
74+
---
75+
- [700, 'TEST700']
76+
...
77+
tarantool> conn.space.tester:insert({600, 'TEST600'})
78+
---
79+
- [600, 'TEST600']
80+
...
81+
82+
After the insert, there is one tuple where the key value is ``600``.
83+
To select this tuple, you can use the ``get()`` method.
84+
Unlike the ``select()`` command, ``get()`` returns only one tuple that satisfies the stated condition.
85+
86+
.. code-block:: tarantoolsession
87+
88+
tarantool> conn.space.tester:get({600})
89+
---
90+
- [600, 'TEST600']
91+
...
92+
93+
To update the existing tuple, you can use either ``update()`` or ``upsert()``.
94+
The ``update()`` method can be used for assignment, arithmetic (if the field is numeric),
95+
cutting and pasting fragments of a field, and deleting or inserting a field.
96+
97+
In this tutorial, the ``update()`` command is used to update the tuple identified by primary key value = ``800``.
98+
The operation assigns a new value to the second field in the tuple:
99+
100+
.. code-block:: tarantoolsession
101+
102+
tarantool> conn.space.tester:update(800, {{'=', 2, 'TEST800'}})
103+
---
104+
- [800, 'TEST800']
105+
...
106+
107+
As for the ``upsert`` function, if there is an existing tuple that matches the key field of tuple, then the command
108+
has the same effect as ``update()``.
109+
Otherwise, the effect is equal to the ``insert()`` method.
110+
111+
.. code-block:: tarantoolsession
112+
113+
tarantool> conn.space.tester:upsert({500, 'TEST500'}, {{'=', 2, 'TEST'}})
114+
115+
To delete a tuple where the key value is ``600``, run the ``delete()`` method below:
116+
117+
.. code-block:: tarantoolsession
118+
119+
tarantool> conn.space.tester:delete{600}
120+
---
121+
- [600, 'TEST600']
122+
...
123+
124+
Then, replace the existing tuple with a new one:
125+
126+
.. code-block:: tarantoolsession
127+
128+
tarantool> conn.space.tester:replace{500, 'New data', 'Extra data'}
129+
---
130+
- [500, 'New data', 'Extra data']
131+
...
132+
133+
Finally, select all tuples from the space:
134+
135+
.. code-block:: tarantoolsession
136+
137+
tarantool> conn.space.tester:select{}
138+
---
139+
- - [800, 'TEST800']
140+
- [500, 'New data', 'Extra data']
141+
- [700, 'TEST700']
142+
...
143+
144+
Closing the connection
145+
----------------------
146+
147+
In the end, close the connection when it is no longer needed:
148+
149+
.. code-block:: tarantoolsession
150+
151+
tarantool> conn:close()
152+
---
153+
...

doc/how-to/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ If you are new to Tarantool, please see our
2020
getting_started_connectors
2121
getting_started_cartridge
2222
db/index
23+
getting_started_net_box
2324
vshard_quick
2425
app/index
2526
replication/index

doc/reference/reference_lua/net_box.rst

Lines changed: 2 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ variant, to be discussed later, is for connecting to MySQL or MariaDB or Postgre
1313
(see :ref:`SQL DBMS modules <dbms_modules>` reference). The other variant, which
1414
is discussed in this section, is for connecting to Tarantool server instances via a
1515
network.
16+
For a quick start with ``net.box``, refer to the :ref:`tutorial <getting_started_net_box>`.
1617

1718
You can call the following methods:
1819

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

886887
Details about trigger characteristics are in the
887-
:ref:`triggers <triggers-box_triggers>` section.
888-
889-
============================================================================
890-
Example
891-
============================================================================
892-
893-
This example shows the use of most of the ``net.box`` methods.
894-
895-
The sandbox configuration for this example assumes that:
896-
897-
* the Tarantool instance is running on ``localhost 127.0.0.1:3301``,
898-
* there is a space named ``tester`` with a numeric primary key and with a tuple
899-
that contains a key value = 800,
900-
* the current user has read, write and execute privileges.
901-
902-
Here are commands for a quick sandbox setup:
903-
904-
.. code-block:: lua
905-
906-
box.cfg{listen = 3301}
907-
s = box.schema.space.create('tester')
908-
s:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}})
909-
t = s:insert({800, 'TEST'})
910-
box.schema.user.grant('guest', 'read,write,execute', 'universe')
911-
912-
And here starts the example:
913-
914-
.. code-block:: tarantoolsession
915-
916-
tarantool> net_box = require('net.box')
917-
---
918-
...
919-
tarantool> function example()
920-
> local conn, wtuple
921-
> if net_box.self:ping() then
922-
> table.insert(ta, 'self:ping() succeeded')
923-
> table.insert(ta, ' (no surprise -- self connection is pre-established)')
924-
> end
925-
> if box.cfg.listen == '3301' then
926-
> table.insert(ta,'The local server listen address = 3301')
927-
> else
928-
> table.insert(ta, 'The local server listen address is not 3301')
929-
> table.insert(ta, '( (maybe box.cfg{...listen="3301"...} was not stated)')
930-
> table.insert(ta, '( (so connect will fail)')
931-
> end
932-
> conn = net_box.connect('127.0.0.1:3301')
933-
> conn.space.tester:delete({800})
934-
> table.insert(ta, 'conn delete done on tester.')
935-
> conn.space.tester:insert({800, 'data'})
936-
> table.insert(ta, 'conn insert done on tester, index 0')
937-
> table.insert(ta, ' primary key value = 800.')
938-
> wtuple = conn.space.tester:select({800})
939-
> table.insert(ta, 'conn select done on tester, index 0')
940-
> table.insert(ta, ' number of fields = ' .. #wtuple)
941-
> conn.space.tester:delete({800})
942-
> table.insert(ta, 'conn delete done on tester')
943-
> conn.space.tester:replace({800, 'New data', 'Extra data'})
944-
> table.insert(ta, 'conn:replace done on tester')
945-
> conn.space.tester:update({800}, {{'=', 2, 'Fld#1'}})
946-
> table.insert(ta, 'conn update done on tester')
947-
> conn:close()
948-
> table.insert(ta, 'conn close done')
949-
> end
950-
---
951-
...
952-
tarantool> ta = {}
953-
---
954-
...
955-
tarantool> example()
956-
---
957-
...
958-
tarantool> ta
959-
---
960-
- - self:ping() succeeded
961-
- ' (no surprise -- self connection is pre-established)'
962-
- The local server listen address = 3301
963-
- conn delete done on tester.
964-
- conn insert done on tester, index 0
965-
- ' primary key value = 800.'
966-
- conn select done on tester, index 0
967-
- ' number of fields = 1'
968-
- conn delete done on tester
969-
- conn:replace done on tester
970-
- conn update done on tester
971-
- conn close done
972-
...
888+
:ref:`triggers <triggers-box_triggers>` section.
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
2+
msgid "Getting started with net.box"
3+
msgstr "Начало работы с net.box"
4+
5+
msgid "The tutorial shows how to work with some common ``net.box`` methods."
6+
msgstr "Ниже приводится пример использования большинства методов ``net.box``."
7+
8+
msgid ""
9+
"For more information about the ``net.box`` module, "
10+
"check the :ref:`corresponding module reference <net_box-module>`."
11+
msgstr ""
12+
"Подробную информацию о модуле ``net.box`` вы найдете "
13+
"в соответствующем :ref:`разделе справочника по модулям <net_box-module>`."
14+
15+
msgid "Sandbox configuration"
16+
msgstr "Настройка песочницы"
17+
18+
msgid "The sandbox configuration for the tutorial assumes that:"
19+
msgstr ""
20+
"Данный пример сработает на конфигурации из песочницы, предполагается, что:"
21+
22+
msgid "The Tarantool instance is running on ``localhost 127.0.0.1:3301``."
23+
msgstr "экземпляр Tarantool запущен на ``localhost 127.0.0.1:3301``;"
24+
25+
msgid "There is a space named ``tester`` with a numeric primary key."
26+
msgstr "создан спейс под названием ``tester`` с первичным числовым ключом;"
27+
28+
msgid "The space contains a tuple with the key value = ``800``."
29+
msgstr "спейс содержит кортеж, в котором есть ключ со значением = 800;"
30+
31+
msgid "The current user has read, write, and execute privileges."
32+
msgstr "у текущего пользователя есть права на чтение, запись и выполнение."
33+
34+
msgid "Use the commands below for a quick sandbox setup:"
35+
msgstr "Используйте команды ниже для быстрой настройки песочницы:"
36+
37+
msgid "Creating a net.box connection"
38+
msgstr "Создание подключения"
39+
40+
msgid ""
41+
"First, load the ``net.box`` module with "
42+
"the ``require('net.box')`` method:"
43+
msgstr ""
44+
"Чтобы начать работу, запустите модуль ``net.box``, "
45+
"используя команду ``require('net.box')``:"
46+
47+
msgid ""
48+
"The next step is to create a new connection. "
49+
"In ``net.box``, self-connection is pre-established. That is, "
50+
"``conn = net_box.connect('localhost:3301')`` command can be "
51+
"replaced with the ``conn = net_box.self`` object call:"
52+
msgstr ""
53+
"Далее необходимо создать новое подключение. "
54+
"В ``net.box`` для локального Tarantool-сервера есть заданный объект ``self`` всегда "
55+
"установленного подключения. Таким образом, команду ``conn = net_box.connect('localhost:3301')`` "
56+
"можно заменить на вызов объекта ``conn = net_box.self``."
57+
58+
msgid "Then, make a ping:"
59+
msgstr "Запустите команду ``ping()``:"
60+
61+
msgid "Using data operations"
62+
msgstr "Операции с данными"
63+
64+
msgid "Select all tuples in the ``tester`` space where the key value is ``800``:"
65+
msgstr "Сделайте выборку всех кортежей в спейсе ``tester``, у которых значение ключа равно ``800``:"
66+
67+
msgid "Insert two tuples into the space:"
68+
msgstr "Вставьте два кортежа в спейс:"
69+
70+
msgid ""
71+
"After the insert, there is one tuple where the key value is ``600``. "
72+
"To select this tuple, you can use the ``get()`` method. "
73+
"Unlike the ``select()`` command, ``get()`` returns only one tuple "
74+
"that satisfies the stated condition."
75+
msgstr ""
76+
"После вставки в спейсе появился один кортеж со значением ключа ``600``. "
77+
"Для выбора этого кортежа вы можете использовать метод ``get()``. "
78+
"В отличие от команды ``select()``, метод ``get()`` возвращает только один кортеж, "
79+
"удовлетворяющий заданным условиям."
80+
81+
msgid ""
82+
"To update the existing tuple, you can use either ``update()`` or ``upsert()``. "
83+
"The ``update()`` method can be used for assignment, "
84+
"arithmetic (if the field is numeric), "
85+
"cutting and pasting fragments of a field, and deleting or inserting a field."
86+
msgstr ""
87+
"Чтобы обновить существующий кортеж, вы можете использовать как метод ``update()``, так и метод ``upsert()``. "
88+
"Функция ``update()`` может использоваться для присваивания, "
89+
"арифметических операций (если поле числовое), вырезания и вставки фрагментов"
90+
" поля, а также для удаления или вставки поля."
91+
92+
msgid ""
93+
"In this tutorial, the ``update()`` command is used to update the tuple "
94+
"identified by primary key value = ``800``. "
95+
"The operation assigns a new value to the second field in the tuple:"
96+
msgstr ""
97+
"В этом руководстве команда ``update()`` используется для обновления кортежа, "
98+
"определенного значением ключа ``800``. "
99+
"Операция присваивает новое значение второму полю в кортеже:"
100+
101+
msgid ""
102+
"As for the ``upsert`` function, if there is an existing tuple "
103+
"that matches the key field of tuple, then the command "
104+
"has the same effect as ``update()``. "
105+
"Otherwise, the effect is equal to the ``insert()`` method."
106+
msgstr ""
107+
"Для функции ``upsert``, если уже существует кортеж, "
108+
"который совпадает с ключевыми полями tuple, запрос приведет к тому же "
109+
"результату, что и метод ``update()``. Если подходящего кортежа нет,"
110+
" запрос приведет к тому же результату, что и метод ``insert()``."
111+
112+
msgid ""
113+
"To delete a tuple where the key value is ``600``, "
114+
"run the ``delete()`` method below:"
115+
msgstr ""
116+
"Чтобы удалить кортеж, в котором значение ключа равно ``600``, "
117+
"запустите метод ``delete()``:"
118+
119+
msgid "Then, replace the existing tuple with a new one:"
120+
msgstr "Затем замените существующий кортеж на новый:"
121+
122+
msgid "Finally, select all tuples from the space:"
123+
msgstr "Наконец, сделайте выборку по всем кортежам из спейса:"
124+
125+
msgid "Closing the connection"
126+
msgstr "Закрытие подключения"
127+
128+
msgid "In the end, close the connection when it is no longer needed:"
129+
msgstr "Закройте соединение явным образом, когда оно больше не используется:"

0 commit comments

Comments
 (0)