drop schema if exists liquidnet_seq;
create database liquidnet_seq character set utf8mb4 collate utf8mb4_unicode_ci;
-- >>------------------------------------------------------------------------------------
drop table if exists liquidnet_seq.sys_sequence;
create table liquidnet_seq.sys_sequence
(
    seq_name    varchar(50) not null, -- sequence key
    current_val bigint      not null, -- sequence value
    increment   int         not null default 1,
    primary key (seq_name)
) engine = innodb;
-- -----------------------------
set global log_bin_trust_function_creators = true;
drop function if exists liquidnet_seq._currval;
delimiter ;;
create function liquidnet_seq._currval(sn varchar(50))
    returns long
    reads sql data
begin
    declare current long;
    set current = 0;
    select current_val
    into current
    from sys_sequence
    where seq_name = sn;
    return current;
end
;;
delimiter ;
-- -----------------------------
drop function if exists liquidnet_seq._nextval;
delimiter ;;
create function liquidnet_seq._nextval(sn varchar(50))
    returns long
    language sql
    deterministic
    contains sql
    sql security definer
    comment ''
begin
    update liquidnet_seq.sys_sequence
    set current_val = current_val + increment
    where seq_name = sn;
    return liquidnet_seq._currval(sn);
end
;;
delimiter ;

# insert into liquidnet_seq.sys_sequence values ('SEQ_AC_N01', 0, 1);
# select liquidnet_seq._nextval('seq_account_no');
-- -----------------------------
drop function if exists liquidnet_seq._setval;
delimiter ;;
create function liquidnet_seq._setval(sn varchar(50), value long)
    returns long
    language sql
    deterministic
    contains sql
    sql security definer
    comment ''
begin
    update liquidnet_seq.sys_sequence
    set current_val = value
    where seq_name = sn;
    return liquidnet_seq._currval(sn);
end
;;
delimiter ;
-- >>------------------------------------------------------------------------------------

-- >>------------------------------------------------------------------------------------
-- >>------------------------------------------------------------------------------------
