From 59d0bd2150452c722697f27cacebae3bac45453e Mon Sep 17 00:00:00 2001 From: Vinzenz Klass <76391770+VinzenzKlass@users.noreply.github.com> Date: Mon, 6 Nov 2023 20:00:39 +0100 Subject: [PATCH] feat: acquire advisory lock before creating extension in pgvector (#12935) - **Description:** Acquire advisory lock before attempting to create extension on postgres server, preventing errors in concurrent executions. - **Issue:** #12933 - **Dependencies:** None --------- Co-authored-by: Eugene Yurtsev --- libs/langchain/langchain/vectorstores/pgvector.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/libs/langchain/langchain/vectorstores/pgvector.py b/libs/langchain/langchain/vectorstores/pgvector.py index a0e61a67b7..1e8456718a 100644 --- a/libs/langchain/langchain/vectorstores/pgvector.py +++ b/libs/langchain/langchain/vectorstores/pgvector.py @@ -159,7 +159,17 @@ class PGVector(VectorStore): def create_vector_extension(self) -> None: try: with Session(self._conn) as session: - statement = sqlalchemy.text("CREATE EXTENSION IF NOT EXISTS vector") + # The advisor lock fixes issue arising from concurrent + # creation of the vector extension. + # https://github.com/langchain-ai/langchain/issues/12933 + # For more information see: + # https://www.postgresql.org/docs/16/explicit-locking.html#ADVISORY-LOCKS + statement = sqlalchemy.text( + "BEGIN;" + "SELECT pg_advisory_xact_lock(1573678846307946496);" + "CREATE EXTENSION IF NOT EXISTS vector;" + "COMMIT;" + ) session.execute(statement) session.commit() except Exception as e: