#!/usr/bin/env tarantool
local test = require("sqltester")
local identifier = require("identifier")
test:plan(9)

local test_prefix = "identifier_char-"

local testcases = {
	-- table creation testcase
	{"table",
	-- create
	function (id)
		-- sql autogenerated index name rules add "sql_autoindex_") prefix
		if string.len(id) == box.schema.NAME_MAX then
			id = string.sub(id, string.len(id))
		end
		test:execsql(string.format("create table \"%s\" (a INT primary key);", id))
	end,
	-- cleanup
	function (id)
		if string.len(id) == box.schema.NAME_MAX then
			id = string.sub(id, string.len(id))
		end
		test:execsql(string.format("drop table \"%s\";", id))
	end},
	{"column name",
	function (id)
		test:execsql(string.format("create table table1(a INT primary key, \"%s\" INT);", id))
	end,
	function (id)
		test:execsql(string.format("drop table table1;", id))
	end},
	{"view as select",
	function (id)
		test:execsql(string.format("create view \"%s\" as select * from test;", id))
	end,
	function (id)
		test:execsql(string.format("drop view \"%s\";", id))
	end},
	{"view column name",
	function (id)
		test:execsql(string.format("create view v1 (\"%s\") as select b from test;", id))
	end,
	function (id)
		test:execsql(string.format("drop view v1;", id))
	end},
	{"as column name",
	function (id)
		test:execsql(string.format("create view v1 as select b as \"%s\" from test;", id))
	end,
	function (id)
		test:execsql(string.format("drop view v1;", id))
	end},
	{"index name",
	function (id)
		test:execsql(string.format("create index \"%s\" on test(b,c);", id))
	end,
	function (id)
		test:execsql(string.format("drop index \"%s\" on test", id))
	end},
	{"savepoint name",
	function (id)
		test:execsql("START TRANSACTION")
		local ok, res = pcall(test.execsql, test, string.format("savepoint \"%s\"", id))
		test:execsql("commit")
		if ok == false then error(res) end
	end,
	function (id) end},
	{"trigger name",
		function (id)
			test:execsql(string.format([[
				CREATE TRIGGER "%s" UPDATE ON test
                FOR EACH ROW
				BEGIN
					SELECT RAISE(ABORT, 'newer');
				END;]], id));
		end,
		function (id)
			test:execsql(string.format("drop trigger \"%s\"", id))
		end}
}

test:do_execsql_test(
	test_prefix.."preparition",
	"create table test(a  INT primary key, b INT, c INT)")

for _, testcase in ipairs(testcases) do
	test:do_test(
		test_prefix..testcase[1],
		function ()
			return identifier.run_test(
			testcase[2],
			testcase[3])
		end,
		"All tests passed")
end

test:finish_test()
