首页 > 解决方案 > Tarantool 现有空间迁移

问题描述

我需要向现有空间添加一个参数并保留现有数据。

空间是这样创建的:

function create_user()
    local space = box.schema.create_space('user', { engine = 'memtx' })
    space:format({
        { name = 'user_id', type = 'unsigned' },
        { name = 'name', type = 'string' },
        { name = 'is_active', type = 'boolean' },
    })
    space:create_index('users_id', { type = 'TREE', parts = { 'user_id', 'name' } })
end

我需要添加以下参数

{ name = 'is_online', type = 'boolean' }
{ name = 'session_id', type = 'unsigned', is_nullable = true }

如何编写所需的迁移脚本?

标签: migrationtarantool

解决方案


这是我的解决方案

function migrate_users()
    local counter = 0
    local space = box.space.users
    space:format({})

    for _, tuple in space:pairs(
            nil, {iterator=box.index.ALL}
        ) do

            local user_tuple = tuple:totable()
            user_tuple[4] = nil
            user_tuple[5] = false
            space:replace(user_tuple)

            counter = counter + 1
            if counter % 10000 == 0 then
                fiber.sleep(0)
            end
    end

    space:format({
        { name = 'user_id', type = 'unsigned' },
        { name = 'name', type = 'string' },
        { name = 'is_active', type = 'boolean' },
        { name = 'session_id', type = 'unsigned', is_nullable = true },
        { name = 'is_online', type = 'boolean' }
    })

    space:create_index('session_id', { type = 'TREE', unique = false, parts = { 'session_id' } })
end

推荐阅读