>key. */ private const COLUMNS = ['site' => 'text', 'post_type' => 'text', 'object_id' => 'bigint', 'lang' => 'text']; private const UPSERT_BATCH = 100; private const DELETE_BATCH = 500; private string $table; /** @var array{host: string, port: int, database: string, user: string, password: string, sslmode: string} */ private array $conn; private ?\PDO $pdo = null; /** * @param array{host?: string, port?: int, database?: string, user?: string, password?: string, sslmode?: string}|null $conn */ public function __construct(?string $table = null, ?array $conn = null) { $s = get_plugin_settings(); $this->table = $table ?? self::configuredTable(); $this->conn = ($conn ?? []) + [ 'host' => trim((string) ($s['pg_host'] ?? '')), 'port' => (int) ($s['pg_port'] ?? 5432), 'database' => trim((string) ($s['pg_database'] ?? '')), 'user' => trim((string) ($s['pg_user'] ?? '')), 'password' => self::password(), 'sslmode' => (string) ($s['pg_sslmode'] ?? 'prefer'), ]; } public static function available(): bool { return extension_loaded('pdo_pgsql'); } public function id(): string { return 'pgvector'; } public function indexName(): string { return $this->table; } public function isSiteOwn(): bool { return trim((string) (get_plugin_settings()['pg_table'] ?? '')) === ''; } public static function password(): string { $pw = (string) (get_plugin_settings()['pg_password'] ?? ''); if ($pw === '' && defined('AIPCF_PG_PASSWORD') && is_string(\AIPCF_PG_PASSWORD)) { $pw = \AIPCF_PG_PASSWORD; } return $pw; } public static function configuredTable(): string { $custom = trim((string) (get_plugin_settings()['pg_table'] ?? '')); if ($custom !== '') { return self::sanitizeName($custom); // may be shared: never suffixed, never dropped } $name = 'aipcf_' . (string) wp_parse_url(home_url(), PHP_URL_HOST); if (is_multisite() && !is_main_site()) { $name .= '_' . get_current_blog_id(); } return State::suffixed(self::sanitizeName($name), 63, '_'); } /** * A safe unquoted identifier: lowercase letters, digits, underscores, starting with a letter. */ public static function sanitizeName(string $name): string { $name = trim((string) preg_replace('/_+/', '_', (string) preg_replace('/[^a-z0-9_]+/', '_', strtolower($name))), '_'); if ($name === '' || !preg_match('/^[a-z]/', $name)) { $name = 'aipcf_' . $name; } return rtrim(substr($name, 0, 63), '_'); } public function test() { $pdo = $this->connect(); if (is_wp_error($pdo)) { return $pdo; } return $this->run(static function (\PDO $db) { $db->query('SELECT 1'); return true; }); } public function ensureIndex(int $dims, string $metric = 'cosine') { if ($metric !== 'cosine') { return new \WP_Error('aipcf_store_mismatch', __('PostgreSQL vector stores only support cosine similarity.', 'aipcf-ai-provider-for-cloudflare')); } if ($dims < 1 || $dims > 2000) { return new \WP_Error('aipcf_store_mismatch', sprintf( /* translators: %d: numbers in each vector the model makes */ __('PostgreSQL search indexes (pgvector) hold vectors of up to 2,000 numbers, but the model makes vectors of %d. Choose another model.', 'aipcf-ai-provider-for-cloudflare'), $dims )); } $table = $this->table; $own = $this->isSiteOwn(); return $this->run(static function (\PDO $db) use ($dims, $table, $own) { if (!$db->query("SELECT 1 FROM pg_extension WHERE extname = 'vector'")->fetchColumn()) { try { $db->exec('CREATE EXTENSION IF NOT EXISTS vector'); } catch (\PDOException $e) { return new \WP_Error('aipcf_store_auth', sprintf( /* translators: %s: error message from PostgreSQL */ __('The pgvector extension is not installed in this database, and this user may not create it. Run "CREATE EXTENSION vector;" as the database owner. (%s)', 'aipcf-ai-provider-for-cloudflare'), $e->getMessage() )); } } $existing = self::tableDims($db, $table); if ($existing === 0) { $db->exec("CREATE TABLE IF NOT EXISTS {$table} ( id text PRIMARY KEY, site text NOT NULL, object_id bigint NOT NULL, post_type text NOT NULL DEFAULT '', lang text NOT NULL DEFAULT '', embedding vector({$dims}) NOT NULL, metadata jsonb NOT NULL DEFAULT '{}'::jsonb, updated_at timestamptz NOT NULL DEFAULT now() )"); $db->exec("CREATE INDEX IF NOT EXISTS {$table}_hnsw ON {$table} USING hnsw (embedding vector_cosine_ops)"); $db->exec("CREATE INDEX IF NOT EXISTS {$table}_site_object ON {$table} (site, object_id)"); return ['created' => true]; } if ($existing !== $dims) { // Rebuild starts a new table only for the site's own one; a custom name is re-embedded in place. return new \WP_Error('aipcf_store_mismatch', sprintf( $own /* translators: 1: table name, 2: numbers in each stored vector, 3: numbers in each vector the model makes */ ? __('The table %1$s holds vectors of %2$d numbers, but the embedding model makes vectors of %3$d. Press Rebuild (under More actions) to start a new table.', 'aipcf-ai-provider-for-cloudflare') /* translators: 1: table name, 2: numbers in each stored vector, 3: numbers in each vector the model makes */ : __('The table %1$s holds vectors of %2$d numbers, but the embedding model makes vectors of %3$d. Enter a new table name, or go back to a model with the same vector size.', 'aipcf-ai-provider-for-cloudflare'), $table, $existing, $dims )); } $db->exec("CREATE INDEX IF NOT EXISTS {$table}_hnsw ON {$table} USING hnsw (embedding vector_cosine_ops)"); return ['created' => false]; }); } public function status() { $table = $this->table; return $this->run(static function (\PDO $db) use ($table) { $dims = self::tableDims($db, $table); if ($dims === 0) { return ['exists' => false, 'ready' => false, 'dims' => 0, 'metric' => '', 'vector_count' => null, 'settled' => true, 'missing_metadata' => []]; } $q = $db->prepare('SELECT 1 FROM pg_indexes WHERE schemaname = current_schema() AND indexname = ?'); $q->execute([$table . '_hnsw']); return [ 'exists' => true, 'ready' => (bool) $q->fetchColumn(), 'dims' => $dims, 'metric' => 'cosine', 'vector_count' => (int) $db->query("SELECT count(*) FROM {$table}")->fetchColumn(), 'settled' => true, 'missing_metadata' => [], ]; }); } public function upsert(array $vectors) { $rows = []; foreach ($vectors as $v) { $id = (string) ($v['id'] ?? ''); if ($id === '') { return new \WP_Error('aipcf_store_item', __('A vector has an empty ID.', 'aipcf-ai-provider-for-cloudflare'), ['ids' => ['']]); } $md = is_array($v['metadata'] ?? null) ? $v['metadata'] : []; $rows[] = [ $id, (string) ($md['site'] ?? ''), (int) ($md['object_id'] ?? 0), (string) ($md['post_type'] ?? ''), (string) ($md['lang'] ?? ''), self::literal((array) ($v['values'] ?? [])), (string) wp_json_encode($md), ]; } $table = $this->table; return $this->run(static function (\PDO $db) use ($rows, $table) { foreach (array_chunk($rows, self::UPSERT_BATCH) as $batch) { $values = implode(',', array_fill(0, count($batch), '(?, ?, ?, ?, ?, ?::vector, ?::jsonb, now())')); $stmt = $db->prepare("INSERT INTO {$table} (id, site, object_id, post_type, lang, embedding, metadata, updated_at) VALUES {$values} ON CONFLICT (id) DO UPDATE SET site = EXCLUDED.site, object_id = EXCLUDED.object_id, post_type = EXCLUDED.post_type, lang = EXCLUDED.lang, embedding = EXCLUDED.embedding, metadata = EXCLUDED.metadata, updated_at = now()"); $stmt->execute(array_merge(...$batch)); } return true; }); } public function delete(array $ids) { $ids = array_values(array_filter(array_map('strval', $ids), static fn($id): bool => $id !== '')); if ($ids === []) { return true; } $table = $this->table; return $this->run(static function (\PDO $db) use ($ids, $table) { foreach (array_chunk($ids, self::DELETE_BATCH) as $batch) { $db->prepare("DELETE FROM {$table} WHERE id IN (" . implode(',', array_fill(0, count($batch), '?')) . ')')->execute($batch); } return true; }); } public function query(array $vector, int $topK = 10, array $filter = [], bool $withMetadata = true) { $table = $this->table; $where = []; $params = [self::literal($vector)]; foreach ($filter as $key => $value) { $key = (string) $key; if (isset(self::COLUMNS[$key])) { $where[] = "{$key} = ?"; $params[] = self::COLUMNS[$key] === 'bigint' ? (int) $value : (string) $value; } else { $where[] = 'metadata->>? = ?'; $params[] = $key; $params[] = is_bool($value) ? ($value ? 'true' : 'false') : (string) $value; } } $sql = sprintf( 'SELECT id, 1 - (embedding <=> ?::vector) AS score%s FROM %s%s ORDER BY embedding <=> ?::vector LIMIT %d', $withMetadata ? ', metadata' : '', $table, $where !== [] ? ' WHERE ' . implode(' AND ', $where) : '', max(1, min($topK, 100)) ); $params[] = $params[0]; return $this->run(static function (\PDO $db) use ($sql, $params, $withMetadata) { $stmt = $db->prepare($sql); $stmt->execute($params); $out = []; foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO -- the site owner's external PostgreSQL vector store, not the WordPress database $md = $withMetadata ? json_decode((string) $row['metadata'], true) : []; $out[] = ['id' => (string) $row['id'], 'score' => (float) $row['score'], 'metadata' => is_array($md) ? $md : []]; } return $out; }); } public function vectors(array $ids) { $ids = array_values(array_unique(array_filter(array_map('strval', $ids), static fn($id): bool => $id !== ''))); $table = $this->table; if ($ids === []) { return []; } return $this->run(static function (\PDO $db) use ($ids, $table) { $out = []; foreach (array_chunk($ids, self::DELETE_BATCH) as $batch) { $stmt = $db->prepare("SELECT id, embedding::text AS v FROM {$table} WHERE id IN (" . implode(',', array_fill(0, count($batch), '?')) . ')'); $stmt->execute($batch); foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO -- the site owner's external PostgreSQL vector store, not the WordPress database // pgvector prints a vector as "[0.1,0.2,...]", which is valid JSON. $v = json_decode((string) $row['v'], true); if (is_array($v)) { $out[(string) $row['id']] = array_map('floatval', $v); } } } return $out; }); } public function dropIndex() { $table = $this->table; return $this->run(static function (\PDO $db) use ($table) { $db->exec("DROP TABLE IF EXISTS {$table}"); return true; }); } /** * @param array $values */ private static function literal(array $values): string { return '[' . implode(',', array_map(static fn($x): string => (string) round((float) $x, 6), $values)) . ']'; } /** * The vector column's dimensions, or 0 when the table does not exist. */ private static function tableDims(\PDO $db, string $table): int { $q = $db->prepare("SELECT format_type(a.atttypid, a.atttypmod) FROM pg_attribute a WHERE a.attrelid = to_regclass(?) AND a.attname = 'embedding' AND NOT a.attisdropped"); $q->execute([$table]); $type = (string) $q->fetchColumn(); return preg_match('/vector\((\d+)\)/', $type, $m) ? (int) $m[1] : 0; } /** * @return \PDO|\WP_Error */ private function connect() { if ($this->pdo !== null) { return $this->pdo; } if (!self::available()) { return new \WP_Error('aipcf_store_auth', __('This server\'s PHP has no pdo_pgsql extension, which PostgreSQL needs. Ask your host to enable it, or use Cloudflare Vectorize or Qdrant.', 'aipcf-ai-provider-for-cloudflare')); } if ($this->conn['host'] === '' || $this->conn['database'] === '' || $this->conn['user'] === '') { return new \WP_Error('aipcf_store_auth', __('Enter the PostgreSQL host, database and user.', 'aipcf-ai-provider-for-cloudflare')); } // Checked here as well as on save: the values go into a connection string, where // ";" or "=" would add parameters (e.g. sslmode=disable). if (!Endpoint::validHost($this->conn['host']) || !Endpoint::validName($this->conn['database']) || !Endpoint::validName($this->conn['user'])) { return new \WP_Error('aipcf_store_auth', __('The PostgreSQL host, database or user contains characters that are not allowed.', 'aipcf-ai-provider-for-cloudflare')); } $check = Endpoint::check($this->conn['host']); if ($check['reason'] !== '') { /* translators: %s: why the address is not allowed */ return new \WP_Error('aipcf_store_auth', sprintf(__('This PostgreSQL address is not allowed: %s', 'aipcf-ai-provider-for-cloudflare'), $check['reason'])); } $sslmode = in_array($this->conn['sslmode'], ['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full'], true) ? $this->conn['sslmode'] : 'prefer'; $dsn = sprintf('pgsql:host=%s;port=%d;dbname=%s;sslmode=%s;connect_timeout=10', $this->conn['host'], $this->conn['port'] > 0 ? $this->conn['port'] : 5432, $this->conn['database'], $sslmode); if ($check['ip'] !== '') { // Connect to the address that was just checked (libpq still verifies TLS against host). $dsn .= ';hostaddr=' . $check['ip']; } // No GSSAPI (Kerberos) encryption: libpq's attempt at it crashes PHP-FPM workers on macOS // (a forked process may not initialise the system's Kerberos), which takes the page down. // Vector stores use TLS (sslmode) instead. libpq before 12 does not know the option. foreach ([$dsn . ';gssencmode=disable', $dsn] as $attempt) { try { // The site owner's external PostgreSQL vector store (pgvector), not the WordPress database: // $wpdb cannot reach PostgreSQL, so PDO is the only way in. $this->pdo = new \PDO($attempt, $this->conn['user'], $this->conn['password'], [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_TIMEOUT => 10]); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO return $this->pdo; } catch (\PDOException $e) { if (stripos($e->getMessage(), 'gssencmode') === false) { return self::classify($e); } } } return new \WP_Error('aipcf_store_auth', __('Could not connect to PostgreSQL. Check the host, port and SSL setting.', 'aipcf-ai-provider-for-cloudflare')); } /** * Runs a callback on the connection, turning database errors into classified WP_Errors. * * @return mixed|\WP_Error */ private function run(callable $fn) { $db = $this->connect(); if (is_wp_error($db)) { return $db; } try { return $fn($db); } catch (\PDOException $e) { return self::classify($e); } } private static function classify(\PDOException $e): \WP_Error { $detail = trim((string) preg_replace('/\s+/', ' ', $e->getMessage())); /* translators: %s: error detail from PostgreSQL */ $message = sprintf(__('PostgreSQL returned an error: %s', 'aipcf-ai-provider-for-cloudflare'), $detail); // Connection errors carry the driver's code (e.g. 7) and the SQLSTATE only in the message. $state = (string) $e->getCode(); if (!preg_match('/^[0-9A-Z]{5}$/', $state) && preg_match('/SQLSTATE\[([0-9A-Z]{5})\]/', $detail, $m)) { $state = $m[1]; } $context = ['sqlstate' => $state]; if ($state === '42P01') { return new \WP_Error('aipcf_store_missing', $message, $context); } // Wrong credentials, database, role or access rules: the owner has to fix the settings. if ( in_array($state, ['28P01', '28000', '3D000', '42501'], true) || preg_match('/password authentication failed|no pg_hba\.conf entry|database "[^"]*" does not exist|role "[^"]*" does not exist|password is missing/i', $detail) ) { return new \WP_Error('aipcf_store_auth', $message, $context); } // Server down, refused, restarting or out of connections: try again later. if (preg_match('/^(08|57P0|53)/', $state) || preg_match('/could not connect|Connection refused|timeout expired|server closed the connection/i', $detail)) { return new \WP_Error('aipcf_retry', $message, $context); } if (stripos($detail, 'dimensions') !== false) { return new \WP_Error('aipcf_store_mismatch', $message, $context); } return new \WP_Error('aipcf_store_failed', $message, $context); } }