如何在 init 函数失败时避免 box.once('init', function ...) 的注册?

我想在 Tarantool 中实现一个 init 函数,仅在 box.once() 下执行一次,但仅当 init 成功执行时对我有用。

问题:如何使 " onceinit" 记录仅在成功运行 init 时有效?

重现此情况

以下 init 函数的代码失败,因为没有 create_space_BAD 函数,但在扫描架构时已注册执行。

如何解决此问题?

代码如下:

local function start()
    box.cfg{}
    box.once('init', function()
        if not pcall(box.schema.create_space_BAD, 'myspace') then
            print('ERROR: create_space_BAD NOT EXIST')
            return false
        end
   ...
   end)
end

探索结构:

tarantool> box.space._schema:select{}
---
- - ['cluster', '1cb21086-51a3-46fb-900e-1983609fc396']
  - ['max_id', 511]
  - ['onceinit']
  - ['version', 1, 10, 2]
...
点赞
用户12940555
用户12940555

这个问题可以使用 box.space._schema:delete('onceinit') 来显式地注销你的 init 函数来解决。

例如:

local function start()
  box.cfg{}
  box.once('init', function()
      if not pcall(box.schema.create_space_BAD, 'myspace') then
    print('ERROR: create_space_BAD NOT EXIST')
    box.space._schema:delete('onceinit')
    return false
      end
        end)
end

然后你将会看到:

tarantool> box.space._schema:select{}
---
- - ['cluster', 'd6a9d97b-3a3f-4f69-8d1a-65ae5a073c16']
  - ['max_id', 511]
  - ['version', 2, 3, 1]
...

更多细节请参见 https://www.tarantool.io/en/doc/1.10/reference/reference_lua/box_once/

2020-05-05 15:44:04
用户3722288
用户3722288

注意,如果您创建了多个 space/index,则使用 box.space._schema:delete 的方法将不起作用。推荐的方法是使用 if_not_exists 选项而不是 box.once

请参阅 https://www.tarantool.io/en/doc/2.3/reference/reference_lua/box_schema/#box-schema-space-createhttps://www.tarantool.io/en/doc/2.3/reference/reference_lua/box_space/#box-space-create-index

2020-05-05 16:15:27