-- --------------------------------------------------------
-- Server OS:                    Linux
-- HeidiSQL Version:             12.6.0.6765
-- --------------------------------------------------------


-- Dumping structure for function sa_dbdarbs.check_login
DELIMITER //
CREATE FUNCTION `check_login`(
    p_username VARCHAR(50),
    p_password VARCHAR(50)
) RETURNS int
    DETERMINISTIC
BEGIN
    DECLARE ok INT;

    SELECT COUNT(*) INTO ok
    FROM users
    WHERE username = p_username
    AND password_hash = SHA2(p_password,256);

    RETURN ok;
END//
DELIMITER ;

-- Dumping structure for function sa_dbdarbs.create_user
DELIMITER //
CREATE FUNCTION `create_user`(
    p_username VARCHAR(50),
    p_password VARCHAR(50)
) RETURNS int
    DETERMINISTIC
BEGIN
    DECLARE cnt INT;

    SELECT COUNT(*) INTO cnt
    FROM users
    WHERE username = p_username;

    IF cnt = 0 THEN
        INSERT INTO users(username, password_hash)
        VALUES (p_username, SHA2(p_password,256));
        RETURN 1;
    END IF;

    RETURN 0;
END//
DELIMITER ;

-- Dumping structure for function sa_dbdarbs.delete_user
DELIMITER //
CREATE FUNCTION `delete_user`(p_username VARCHAR(50)) RETURNS int
    DETERMINISTIC
BEGIN
    DELETE FROM users WHERE username = p_username;
    RETURN ROW_COUNT();
END//
DELIMITER ;

-- Dumping structure for function sa_dbdarbs.is_logged_in_user
DELIMITER //
CREATE FUNCTION `is_logged_in_user`(p_username VARCHAR(50)) RETURNS int
    DETERMINISTIC
BEGIN
    DECLARE status INT;

    SELECT is_logged_in INTO status
    FROM users
    WHERE username = p_username;

    RETURN status;
END//
DELIMITER ;

-- Dumping structure for table sa_dbdarbs.login_users
CREATE TABLE IF NOT EXISTS `login_users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Dumping data for table sa_dbdarbs.login_users: ~0 rows (approximately)

-- Dumping structure for function sa_dbdarbs.update_user_password
DELIMITER //
CREATE FUNCTION `update_user_password`(
    p_username VARCHAR(50),
    p_new_password VARCHAR(50)
) RETURNS int
    DETERMINISTIC
BEGIN
    UPDATE users
    SET password_hash = SHA2(p_new_password,256)
    WHERE username = p_username;

    RETURN ROW_COUNT();
END//
DELIMITER ;

-- Dumping structure for table sa_dbdarbs.users
CREATE TABLE IF NOT EXISTS `users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `repeatpassword` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Dumping data for table sa_dbdarbs.users: ~0 rows (approximately)

