prefix . 'wpi_configs'; } public static function acquire_lock(string $key): bool { global $wpdb; $table = self::table(); return (bool) $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET config_value = 1 WHERE config_key = %s AND config_value = 0", $key ) ); } /** * Check config exists */ private static function exists(string $key): bool { global $wpdb; return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT 1 FROM " . self::table() . " WHERE config_key = %s LIMIT 1", $key ) ); } /** * Insert or update config */ public static function set_config(string $key, $value, string $description = null) { global $wpdb; $table = self::table(); $now = current_time('mysql'); $data = [ 'config_value' => wp_json_encode($value), 'updated_at' => $now, ]; if ($description !== null) { $data['description'] = $description; } if (self::exists($key)) { // UPDATE only $wpdb->update( $table, $data, ['config_key' => $key], ['%s', '%s', '%s'], ['%s'] ); } else { // INSERT new $wpdb->insert( $table, array_merge($data, [ 'config_key' => $key, 'created_at' => $now, ]), ['%s', '%s', '%s', '%s'] ); } } /** * Get config (auto json decode) */ public static function get_config(string $key, $default = null) { global $wpdb; $value = $wpdb->get_var( $wpdb->prepare( "SELECT config_value FROM " . self::table() . " WHERE config_key = %s", $key ) ); return $value !== null ? json_decode($value, true) : $default; } public static function any_worker_running(): bool { global $wpdb; $table = self::table(); $rows = $wpdb->get_results( "SELECT config_value FROM {$table} WHERE config_key LIKE 'sync_status_%'" ); if (empty($rows)) { // Không có worker nào return false; } foreach ($rows as $row) { $value = json_decode($row->config_value, true); if ((int) $value !== 1) { return false; } } return true; } public static function claim_next_page(): int { global $wpdb; $table = self::table(); // Atomic increment $updated = $wpdb->query( "UPDATE {$table} SET config_value = config_value + 1 WHERE config_key = 'current_page'" ); if ($updated === false) { return 0; } // Lấy page vừa claim $page = (int) $wpdb->get_var( "SELECT config_value FROM {$table} WHERE config_key = 'current_page'" ); return $page; } }