Skip to content

Commit 869f52c

Browse files
fix(sqlalchemy): normalize BitString types and enable Windows pytest loop
1 parent 344bd82 commit 869f52c

6 files changed

Lines changed: 73 additions & 27 deletions

File tree

‎CONTEXT_AND_RESULTS.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,16 @@ In `pgvector/sqlalchemy/bit.py`, `VECTOR`, `HALFVEC`, and `SPARSEVEC` implemente
1313
sqlalchemy.exc.CompileError: No literal value renderer is available for literal value "'101'" with datatype BIT
1414
```
1515

16-
Additionally, passing a `pgvector.Bit` instance directly into SQLAlchemy `BIT` bind/literal paths required explicit conversion to bit-string text.
16+
Additionally, passing `pgvector.Bit`, SQLAlchemy 2.1 `postgresql.BitString` (whose `str` validation fails inside `String.literal_processor`), or `asyncpg.BitString` into SQLAlchemy `BIT` bind/literal paths required explicit normalization to plain bit-string text.
1717

1818
### Code Changes (`pgvector/sqlalchemy/bit.py` & `tests/test_sqlalchemy.py`)
1919
- **`pgvector/sqlalchemy/bit.py`**:
20-
- Added `_string = String()` and implemented `BIT.literal_processor(self, dialect: Dialect)` using `self._string._cached_literal_processor(dialect)` while converting `pgvector.Bit` instances via `.to_text()`.
21-
- Updated `BIT.process_bind_param` so `pgvector.Bit` instances are converted via `.to_text()` before `asyncpg.BitString` conversion or return.
20+
- Added shared helper `BIT._to_text` normalizing `pgvector.Bit`, `str` subclasses (such as SQLAlchemy 2.1's `postgresql.BitString`), and `asyncpg.BitString` to plain `str` bit text.
21+
- Added `_string = String()` and implemented `BIT.literal_processor(self, dialect: Dialect)` using `self._string._cached_literal_processor(dialect)` over `self._to_text(value)`.
22+
- Updated `BIT.process_bind_param` to normalize inputs via `self._to_text(value)` before `asyncpg.BitString` conversion or return.
2223
- **`tests/test_sqlalchemy.py`**:
23-
- Added regression assertions inside `TestSqlalchemy.test_literal_binds` verifying `compile_kwargs={'literal_binds': True}` for:
24-
- `Item.binary_embedding.hamming_distance('101')`
25-
- `Item.binary_embedding.hamming_distance(Bit('101'))`
26-
- `Item.binary_embedding.jaccard_distance('101')`
24+
- Added regression assertions inside `TestSqlalchemy.test_literal_binds` verifying `compile_kwargs={'literal_binds': True}` for `'101'`, `Bit('101')`, `postgresql.BitString('101')`, `asyncpg.BitString('101')`, and `jaccard_distance('101')`.
25+
- Expanded `TestSqlalchemy.test_bit` and `TestSqlalchemyAsync.test_bit` to verify persisting and reading back `Bit` instances across sync and async engines.
2726

2827
## Local Environment and Step-by-Step Execution (Windows + Docker)
2928

@@ -59,14 +58,20 @@ Additionally, passing a `pgvector.Bit` instance directly into SQLAlchemy `BIT` b
5958
```
6059

6160
4. **Run the full 581-test suite on Windows**
62-
On Windows, Python's default `asyncio.ProactorEventLoop` is rejected by `psycopg` async connections (`psycopg.InterfaceError`). Running `pytest` with `WindowsSelectorEventLoopPolicy` enables all sync and async tests across all drivers and ORMs:
61+
On Windows, Python's default `asyncio.ProactorEventLoop` is rejected by `psycopg` async connections (`psycopg.InterfaceError`). `tests/conftest.py` registers a `pytest_asyncio_loop_factories` hook on `win32` returning `asyncio.SelectorEventLoop`, so plain `pytest` passes all sync and async tests across every driver and ORM:
6362
```powershell
6463
$env:PGHOST = "localhost"
6564
$env:PGUSER = "bit"
66-
.\.venv\Scripts\python.exe -c "import asyncio, sys, pytest; asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()); sys.exit(pytest.main())"
65+
.\.venv\Scripts\python.exe -m pytest
6766
```
6867

69-
5. **Run the bulk loading example (`examples/loading/example.py`)**
68+
5. **Run type checks and linter (from `pgvector-python`)**
69+
```powershell
70+
.\.venv\Scripts\python.exe -m mypy
71+
.\.venv\Scripts\python.exe -m pycodestyle . --ignore=E501,E704,W504 --exclude=.venv
72+
```
73+
74+
6. **Run the bulk loading example (`examples/loading/example.py`)**
7075
```powershell
7176
$env:PGHOST = "localhost"
7277
$env:PGUSER = "bit"
@@ -79,6 +84,9 @@ Additionally, passing a `pgvector.Bit` instance directly into SQLAlchemy `BIT` b
7984
| --- | --- | --- | --- |
8085
| Offline unit tests | `pytest tests/test_bit.py tests/test_half_vector.py tests/test_sparse_vector.py tests/test_vector.py` | **122 passed** (`1.25s`) | Pure Python, NumPy, and SciPy vector/bit tests |
8186
| Offline SQLAlchemy `BIT` compilation | `Item.binary_embedding.hamming_distance('101' / Bit('101'))` & `jaccard_distance('101')` with `literal_binds=True` | **Passed** | Compiled cleanly to `<~> '101'` and `<%%> '101'` |
82-
| Full suite (default Windows event loop) | `.\.venv\Scripts\python.exe -m pytest` | **568 passed, 13 failed** (`67.54s`) | All 13 failures were `psycopg` async tests due to Windows default `ProactorEventLoop` |
83-
| Full suite (`WindowsSelectorEventLoopPolicy`) | `pytest.main()` with `WindowsSelectorEventLoopPolicy` | **581 passed** (`25.43s`) | All 12 test modules passed (`asyncpg`, `bit`, `django`, `half_vector`, `peewee`, `pg8000`, `psycopg`, `psycopg2`, `sparse_vector`, `sqlalchemy`, `sqlmodel`, `vector`) |
87+
| Full suite (before `conftest.py` hook) | `.\.venv\Scripts\python.exe -m pytest` | **568 passed, 13 failed** (`67.54s`) | Baseline before adding `SelectorEventLoop` hook; all 13 failures were `psycopg` async under `ProactorEventLoop` |
88+
| Full suite (with `conftest.py` `SelectorEventLoop` hook) | `.\.venv\Scripts\python.exe -m pytest` | **581 passed** | All 12 test modules passed (`asyncpg`, `bit`, `django`, `half_vector`, `peewee`, `pg8000`, `psycopg`, `psycopg2`, `sparse_vector`, `sqlalchemy`, `sqlmodel`, `vector`) |
89+
| Type check (`mypy`) | `.\.venv\Scripts\python.exe -m mypy` | **Passed** (`0` issues) | `Success: no issues found in 54 source files` |
90+
| Linter (`pycodestyle`) | `.\.venv\Scripts\python.exe -m pycodestyle . --ignore=E501,E704,W504 --exclude=.venv` | **Passed** (`0` issues) | Clean across codebase and tests |
91+
| Type check (`ty`) | `.\.venv\Scripts\ty.exe check` | **21 diagnostics** | All 21 in upstream `tests/test_sqlmodel.py` (`sqlmodel 0.0.50` tuple inference); 0 in `pgvector/` or modified test files |
8492
| Bulk loading example | `.\.venv\Scripts\python.exe examples\loading\example.py` | **Success** | Loaded `1000000` 128-dimensional vector rows via binary `COPY` into `pgvector_example` |

‎README.md‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -825,14 +825,14 @@ arr = vec.to_coo()
825825

826826
## History
827827

828-
View the [changelog](https://github.com/pgvector/pgvector-python/blob/master/CHANGELOG.md)
828+
View the [changelog](CHANGELOG.md)
829829

830830
## Contributing
831831

832832
Everyone is encouraged to help improve this project. Here are a few ways you can help:
833833

834-
- [Report bugs](https://github.com/pgvector/pgvector-python/issues)
835-
- Fix bugs and [submit pull requests](https://github.com/pgvector/pgvector-python/pulls)
834+
- [Report bugs](https://github.com/shikhar-gangwar/pgvector-python/issues)
835+
- Fix bugs and [submit pull requests](https://github.com/shikhar-gangwar/pgvector-python/pulls)
836836
- Write, clarify, or fix documentation
837837
- Suggest or add new features
838838

@@ -846,14 +846,14 @@ createdb pgvector_python_test
846846
pytest
847847
```
848848

849-
On Windows with Docker Desktop (`pgvector/pgvector:pg17`), start PostgreSQL and run the full suite with `WindowsSelectorEventLoopPolicy` (required for `psycopg` async tests on Windows):
849+
On Windows with Docker Desktop (`pgvector/pgvector:pg17`), start PostgreSQL and run the full test suite (`tests/conftest.py` automatically configures `SelectorEventLoop` on Windows for `psycopg` async tests):
850850

851851
```powershell
852852
docker run -d --name pgvector-test -e POSTGRES_USER=bit -e POSTGRES_DB=pgvector_python_test -e POSTGRES_HOST_AUTH_METHOD=trust -p 5432:5432 pgvector/pgvector:pg17
853853
docker exec -it pgvector-test createdb -U bit pgvector_example
854854
$env:PGHOST = "localhost"
855855
$env:PGUSER = "bit"
856-
.\.venv\Scripts\python.exe -c "import asyncio, sys, pytest; asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()); sys.exit(pytest.main())"
856+
.\.venv\Scripts\python.exe -m pytest
857857
```
858858

859859
To run an example:
@@ -874,8 +874,9 @@ For full technical context, implementation notes, and verified test/example outp
874874
### Specific Changes in this Repository
875875
- **SQLAlchemy `BIT` literal binds and object support (`pgvector/sqlalchemy/bit.py`)**:
876876
- Implemented `literal_processor` for `BIT` in SQLAlchemy to support compiling queries with `compile_kwargs={'literal_binds': True}`. Previously, while `VECTOR`, `HALFVEC`, and `SPARSEVEC` implemented `literal_processor`, `BIT` inherited the default from `PGBit` (which returns `None`), causing `sqlalchemy.exc.CompileError: No literal value renderer is available for literal value "'101'" with datatype BIT`.
877-
- Added support in `BIT.process_bind_param` and `BIT.literal_processor` for `pgvector.Bit` instances by converting them to bit string text, allowing `Bit` objects to be passed cleanly across SQLAlchemy queries and expressions.
878-
- Added regression test assertions to `test_literal_binds` in `tests/test_sqlalchemy.py`.
879-
- **Context, Verification, and Documentation (`CONTEXT_AND_RESULTS.md`, `README.md`)**:
880-
- Verified all **581 tests** pass against `pgvector/pgvector:pg17` (including all sync/async driver and ORM suites when using `WindowsSelectorEventLoopPolicy` on Windows) and verified `examples/loading/example.py` loading 1,000,000 rows into PostgreSQL.
877+
- Added shared normalization (`BIT._to_text`) in `BIT.process_bind_param` and `BIT.literal_processor` for `pgvector.Bit`, `postgresql.BitString` (SQLAlchemy >= 2.1), and `asyncpg.BitString` instances by converting them to plain bit string text, allowing `Bit` and dialect `BitString` objects to be passed cleanly across SQLAlchemy queries and literal-bind expressions.
878+
- Added regression test assertions to `test_literal_binds`, `TestSqlalchemy.test_bit`, and `TestSqlalchemyAsync.test_bit` in `tests/test_sqlalchemy.py`.
879+
- **Context, Verification, and Documentation (`CONTEXT_AND_RESULTS.md`, `README.md`, `tests/conftest.py`)**:
880+
- Added a Windows-only `pytest_asyncio_loop_factories` hook in `tests/conftest.py` so plain `pytest` uses `SelectorEventLoop` on Windows.
881+
- Verified all **581 tests** pass against `pgvector/pgvector:pg17` (plus `mypy` and `pycodestyle` clean) and verified `examples/loading/example.py` loading 1,000,000 rows into PostgreSQL.
881882

‎pgvector/sqlalchemy/bit.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,19 @@ class BIT(TypeDecorator[Any]):
1010
cache_ok = True
1111
_string = String()
1212

13-
def process_bind_param(self, value: Any, dialect: Any) -> Any:
13+
@staticmethod
14+
def _to_text(value: Any) -> Any:
1415
if isinstance(value, Bit):
15-
value = value.to_text()
16+
return value.to_text()
17+
if isinstance(value, str):
18+
# Convert str subclasses (e.g. postgresql.BitString) to plain str
19+
return str(value)
20+
if value is not None and value.__class__.__module__.startswith('asyncpg') and value.__class__.__name__ == 'BitString':
21+
return value.as_string()
22+
return value
23+
24+
def process_bind_param(self, value: Any, dialect: Any) -> Any:
25+
value = self._to_text(value)
1626
if dialect.__class__.__name__ == 'PGDialect_asyncpg' and isinstance(value, str):
1727
import asyncpg
1828
return asyncpg.BitString(value) # type: ignore
@@ -22,9 +32,7 @@ def literal_processor(self, dialect: Dialect) -> Any:
2232
string_literal_processor = self._string._cached_literal_processor(dialect)
2333

2434
def process(value: Any) -> Any:
25-
if isinstance(value, Bit):
26-
value = value.to_text()
27-
return string_literal_processor(value) # type: ignore
35+
return string_literal_processor(self._to_text(value)) # type: ignore
2836
return process
2937

3038
class Comparator(TypeDecorator.Comparator[Any]): # type: ignore

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ dependencies = [
1616
]
1717

1818
[project.urls]
19-
Homepage = "https://github.com/pgvector/pgvector-python"
19+
Homepage = "https://github.com/shikhar-gangwar/pgvector-python"
2020

2121
[dependency-groups]
2222
dev = [

‎tests/conftest.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
1+
import asyncio
2+
from collections.abc import Callable
3+
import sys
4+
import pytest
5+
16
try:
27
import numpy
38
except ImportError:
49
numpy = None # type: ignore
510

11+
if sys.platform == 'win32':
12+
# psycopg async mode requires SelectorEventLoop instead of Windows ProactorEventLoop
13+
def pytest_asyncio_loop_factories(
14+
config: pytest.Config,
15+
item: pytest.Item,
16+
) -> dict[str, Callable[[], asyncio.AbstractEventLoop]]:
17+
return {'selector': asyncio.SelectorEventLoop}
18+
619
__all__ = [
720
'numpy'
821
]

‎tests/test_sqlalchemy.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,10 +298,14 @@ def test_halfvec_l1_distance_orm(self, engine: Engine) -> None:
298298

299299
def test_bit(self, engine: Engine) -> None:
300300
with Session(engine) as session:
301+
bit_val: Any = Bit('110')
301302
session.add(Item(id=1, binary_embedding='101'))
303+
session.add(Item(id=2, binary_embedding=bit_val))
302304
session.commit()
303305
item = session.get_one(Item, 1)
304306
assert item.binary_embedding == '101'
307+
item2 = session.get_one(Item, 2)
308+
assert item2.binary_embedding == '110'
305309

306310
def test_bit_hamming_distance(self, engine: Engine) -> None:
307311
create_items()
@@ -524,6 +528,13 @@ def test_literal_binds(self, engine: Engine) -> None:
524528
sql = select(Item).order_by(Item.binary_embedding.hamming_distance(Bit('101'))).compile(engine, compile_kwargs={'literal_binds': True})
525529
assert "binary_embedding <~> '101'" in str(sql)
526530

531+
if sqlalchemy_version >= 2.1:
532+
sql = select(Item).order_by(Item.binary_embedding.hamming_distance(postgresql.BitString('101'))).compile(engine, compile_kwargs={'literal_binds': True}) # type: ignore
533+
assert "binary_embedding <~> '101'" in str(sql)
534+
535+
sql = select(Item).order_by(Item.binary_embedding.hamming_distance(asyncpg.BitString('101'))).compile(engine, compile_kwargs={'literal_binds': True}) # type: ignore
536+
assert "binary_embedding <~> '101'" in str(sql)
537+
527538
sql = select(Item).order_by(Item.binary_embedding.jaccard_distance('101')).compile(engine, compile_kwargs={'literal_binds': True})
528539
assert "binary_embedding <%> '101'" in str(sql) or "binary_embedding <%%> '101'" in str(sql)
529540

@@ -664,6 +675,11 @@ async def test_bit(self, engine: AsyncEngine) -> None:
664675
item = await session.get_one(Item, 2)
665676
assert item.binary_embedding == embedding
666677

678+
bit_val: Any = Bit('101')
679+
session.add(Item(id=3, binary_embedding=bit_val))
680+
item = await session.get_one(Item, 3)
681+
assert item.binary_embedding == embedding
682+
667683
await engine.dispose()
668684

669685
@pytest.mark.asyncio

0 commit comments

Comments
 (0)