BEGIN
    DECLARE v_error BOOLEAN DEFAULT FALSE;
    DECLARE db_quoted VARCHAR(64);
    DECLARE table_quoted VARCHAR(64);
    DECLARE v_table_type VARCHAR(16) DEFAULT '';
    DECLARE v_system_db BOOLEAN
        DEFAULT LOWER(in_db) IN ('information_schema', 'performance_schema');
    DECLARE CONTINUE HANDLER FOR 1050 SET v_error = TRUE;
    DECLARE CONTINUE HANDLER FOR 1146 SET v_error = TRUE;
    SET out_exists = '';
    SET db_quoted = sys.quote_identifier(in_db);
    SET table_quoted = sys.quote_identifier(in_table);
    IF (EXISTS(SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = in_db AND TABLE_NAME = in_table)) THEN
        IF v_system_db = FALSE THEN
            SET @sys.tmp.table_exists.SQL = CONCAT('CREATE TEMPORARY TABLE ',
                                                    db_quoted,
                                                    '.',
                                                    table_quoted,
                                                    '(id INT PRIMARY KEY)');
            PREPARE stmt_create_table FROM @sys.tmp.table_exists.SQL;
            EXECUTE stmt_create_table;
            DEALLOCATE PREPARE stmt_create_table;
            SET @sys.tmp.table_exists.SQL = CONCAT('DROP TEMPORARY TABLE ',
                                                                db_quoted,
                                                                '.',
                                                                table_quoted);
            PREPARE stmt_drop_table FROM @sys.tmp.table_exists.SQL;
            EXECUTE stmt_drop_table;
            DEALLOCATE PREPARE stmt_drop_table;
        END IF;
        IF (v_error) THEN
            SET out_exists = 'TEMPORARY';
        ELSE
            SET v_table_type = (SELECT TABLE_TYPE FROM information_schema.TABLES WHERE TABLE_SCHEMA = in_db AND TABLE_NAME = in_table);
            IF v_table_type = 'SYSTEM VERSIONED' THEN
                SET out_exists = 'BASE TABLE';
            ELSE
                SET out_exists = v_table_type;
            END IF;
        END IF;
    ELSE
        IF v_system_db = FALSE THEN
            SET @sys.tmp.table_exists.SQL = CONCAT('SELECT COUNT(*) FROM ',
                                                            db_quoted,
                                                            '.',
                                                            table_quoted);
            PREPARE stmt_select FROM @sys.tmp.table_exists.SQL;
            IF (NOT v_error) THEN
                DEALLOCATE PREPARE stmt_select;
                SET out_exists = 'TEMPORARY';
            END IF;
        END IF;
    END IF;
END