Skip to content

Commit

Permalink
Added pool example and tests for Psycopg 3 - closes #100
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Nov 5, 2024
1 parent 25a3026 commit 06a48c4
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,15 @@ from pgvector.psycopg import register_vector
register_vector(conn)
```

For [connection pools](https://www.psycopg.org/psycopg3/docs/advanced/pool.html), use

```python
def configure(conn):
register_vector(conn)

pool = ConnectionPool(configure=configure)
```

For [async connections](https://www.psycopg.org/psycopg3/docs/advanced/async.html), use

```python
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ asyncpg
Django
numpy
peewee
psycopg[binary]
psycopg[binary,pool]
psycopg2-binary
pytest
pytest-asyncio
Expand Down
29 changes: 29 additions & 0 deletions tests/test_psycopg.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
from pgvector.psycopg import register_vector, register_vector_async, Bit, HalfVector, SparseVector, Vector
import psycopg
from psycopg_pool import ConnectionPool, AsyncConnectionPool
import pytest

conn = psycopg.connect(dbname='pgvector_python_test', autocommit=True)
Expand Down Expand Up @@ -176,6 +177,18 @@ def test_vector_array(self):
assert np.array_equal(res[0][0], embeddings[0])
assert np.array_equal(res[0][1], embeddings[1])

def test_pool(self):
def configure(conn):
register_vector(conn)

pool = ConnectionPool(conninfo='postgres://localhost/pgvector_python_test', open=True, configure=configure)

with pool.connection() as conn:
res = conn.execute("SELECT '[1,2,3]'::vector").fetchone()
assert np.array_equal(res[0], np.array([1, 2, 3]))

pool.close()

@pytest.mark.asyncio
async def test_async(self):
conn = await psycopg.AsyncConnection.connect(dbname='pgvector_python_test', autocommit=True)
Expand All @@ -195,3 +208,19 @@ async def test_async(self):
assert np.array_equal(res[0][1], embedding)
assert res[0][1].dtype == np.float32
assert res[1][1] is None

@pytest.mark.asyncio
async def test_async_pool(self):
async def configure(conn):
await register_vector_async(conn)

pool = AsyncConnectionPool(conninfo='postgres://localhost/pgvector_python_test', open=False, configure=configure)
await pool.open()

async with pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT '[1,2,3]'::vector")
res = await cur.fetchone()
assert np.array_equal(res[0], np.array([1, 2, 3]))

await pool.close()

0 comments on commit 06a48c4

Please sign in to comment.