You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.6 KiB
PHP

<?php
require_once 'config.php';
try {
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
ensureOptionalSchema($pdo);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
function ensureOptionalSchema(PDO $pdo) {
static $done = false;
if ($done || DB_PREFIX === '') {
return;
}
$done = true;
$usersTable = DB_PREFIX . "users";
try {
$columns = $pdo->query("SHOW COLUMNS FROM {$usersTable}")->fetchAll(PDO::FETCH_COLUMN, 0);
$indexes = $pdo->query("SHOW INDEX FROM {$usersTable}")->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
error_log($e->getMessage());
return;
}
$indexNames = array_column($indexes, 'Key_name');
$statements = [];
if (!in_array('email', $columns, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD COLUMN email varchar(255) DEFAULT NULL AFTER username";
}
if (!in_array('display_name', $columns, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD COLUMN display_name varchar(255) DEFAULT NULL AFTER email";
}
if (!in_array('oauth_provider', $columns, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD COLUMN oauth_provider varchar(50) DEFAULT NULL AFTER role";
}
if (!in_array('oauth_subject', $columns, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD COLUMN oauth_subject varchar(191) DEFAULT NULL AFTER oauth_provider";
}
if (!in_array('oauth_tenant_id', $columns, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD COLUMN oauth_tenant_id varchar(64) DEFAULT NULL AFTER oauth_subject";
}
if (!in_array('last_login_at', $columns, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD COLUMN last_login_at datetime DEFAULT NULL AFTER oauth_tenant_id";
}
if (!in_array('uniq_users_email', $indexNames, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD UNIQUE KEY uniq_users_email (email)";
}
if (!in_array('idx_users_oauth_identity', $indexNames, true)) {
$statements[] = "ALTER TABLE {$usersTable} ADD KEY idx_users_oauth_identity (oauth_provider, oauth_subject, oauth_tenant_id)";
}
foreach ($statements as $statement) {
try {
$pdo->exec($statement);
} catch (\PDOException $e) {
error_log($e->getMessage());
}
}
}
?>