select(); $mapping = []; $keys = []; foreach ($rows as $row) { $site = isset($row['site']) && in_array($row['site'], ['center', 'xishui'], true) ? $row['site'] : ''; if ($site === '') { if (strpos($row['storage'], '习水') !== false) $site = 'xishui'; elseif (strpos($row['storage'], '中心库') !== false) $site = 'center'; else throw new Exception('Unknown site for granary ' . $row['id']); } $key = $site . ':' . $row['num']; if (isset($keys[$key])) throw new Exception('Duplicate site/number: ' . $key); $keys[$key] = true; $mapping[$row['id']] = $site; } $snapshot = $backup . '/granary-sites-before.json'; if (!file_exists($snapshot)) { file_put_contents($snapshot, json_encode(['granaries' => $rows, 'admin_scopes' => \think\Db::name('admin')->field('id,username')->select()], JSON_UNESCAPED_UNICODE)); chmod($snapshot, 0600); } $columns = array_column(\think\Db::query('SHOW COLUMNS FROM `' . $prefix . 'granary`'), 'Field'); if (!in_array('site', $columns)) \think\Db::execute('ALTER TABLE `' . $prefix . 'granary` ADD `site` varchar(16) NOT NULL DEFAULT \'\' COMMENT \'库区:center中心库,xishui习水库\' AFTER `storage`'); // Use bound SQL because this process may have cached the pre-migration fields. foreach ($mapping as $id => $site) \think\Db::execute('UPDATE `' . $prefix . 'granary` SET site = ? WHERE id = ?', [$site, $id]); $indexes = array_column(\think\Db::query('SHOW INDEX FROM `' . $prefix . 'granary`'), 'Key_name'); if (!in_array('uq_granary_site_num', $indexes)) \think\Db::execute('ALTER TABLE `' . $prefix . 'granary` ADD UNIQUE KEY `uq_granary_site_num` (`site`,`num`)'); $columns = array_column(\think\Db::query('SHOW COLUMNS FROM `' . $prefix . 'admin`'), 'Field'); if (!in_array('granary_sites', $columns)) \think\Db::execute('ALTER TABLE `' . $prefix . 'admin` ADD `granary_sites` varchar(16) NOT NULL DEFAULT \'all\' COMMENT \'库区权限:all/center/xishui/none\''); foreach (['granary', 'admin'] as $table) { $schema = RUNTIME_PATH . 'schema/' . config('database.database') . '.' . $prefix . $table . '.php'; if (is_file($schema)) { copy($schema, $backup . '/' . $table . '-schema-before.php'); unlink($schema); } } echo "GRANARY_SITES_READY\n";