fix: Replace raw SQL string interpolation with proper SQLAlchemy parameterized APIs in PostgresKVStore #20104
+232
−69
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR improves the PostgresKVStore implementation by replacing raw SQL string interpolation with proper SQLAlchemy parameterized APIs. While unlikely to be exploitable in practice (since identifiers are lowercased during initialization), using SQLAlchemy's built-in constructs is better practice and eliminates any theoretical injection vectors.
Changes
1. Schema Creation (
_create_schema_if_not_exists
)Before:
After:
2. Insert Operations (
put_all
/aput_all
)Before:
After:
Benefits
put_all
andaput_all
Testing
Added 4 new tests to verify the implementation:
test_schema_creation_uses_safe_api
- Verifies CreateSchema usagetest_put_all_uses_safe_insert
- Verifies parameterized insert APItest_aput_all_uses_safe_insert
- Verifies async parameterized inserttest_schema_name_with_special_characters
- Tests edge cases with special charactersAll tests pass (6/6). All pre-commit checks pass (ruff, mypy, codespell, formatting).
Code Changes
Modified Files
llama_index/storage/kvstore/postgres/base.py
tests/test_storage_kvstore_postgres.py
Breaking Changes
None - this is a drop-in replacement with full backward compatibility.