SET @users_username_exists = (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'username'
);
SET @users_username_sql = IF(
    @users_username_exists = 0,
    "ALTER TABLE users ADD COLUMN username VARCHAR(80) NULL AFTER name",
    'SELECT 1'
);
PREPARE users_username_stmt FROM @users_username_sql;
EXECUTE users_username_stmt;
DEALLOCATE PREPARE users_username_stmt;

SET @users_avatar_exists = (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'avatar_url'
);
SET @users_avatar_sql = IF(
    @users_avatar_exists = 0,
    "ALTER TABLE users ADD COLUMN avatar_url VARCHAR(500) NULL AFTER bio",
    'SELECT 1'
);
PREPARE users_avatar_stmt FROM @users_avatar_sql;
EXECUTE users_avatar_stmt;
DEALLOCATE PREPARE users_avatar_stmt;

SET @users_username_index_exists = (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND INDEX_NAME = 'uniq_users_username'
);
SET @users_username_index_sql = IF(
    @users_username_index_exists = 0,
    "ALTER TABLE users ADD UNIQUE KEY uniq_users_username (username)",
    'SELECT 1'
);
PREPARE users_username_index_stmt FROM @users_username_index_sql;
EXECUTE users_username_index_stmt;
DEALLOCATE PREPARE users_username_index_stmt;
