semantic-kernel icon indicating copy to clipboard operation
semantic-kernel copied to clipboard

Python: Fix Postgres filter SQL composition

Open pragnyanramtha opened this issue 6 months ago • 1 comments

Motivation and Context

Fixes #13595.

Postgres vector-search lambda filters were parsed into plain strings and then passed through psycopg.sql.SQL.format(). psycopg treats non-composable values as SQL literals, so filter predicates could be embedded as quoted strings instead of SQL expressions. The filtered query also missed a leading space before WHERE.

Description

  • Build Postgres filter clauses with psycopg.sql composables instead of plain strings
  • Use sql.Identifier for field names and sql.Literal for constants
  • Preserve existing boolean/comparison/list filter behavior while composing AND, OR, NOT, IN, and chained comparisons as SQL fragments
  • Add regression tests for single and multiple filtered vector-search queries

Contribution Checklist

  • [x] The code builds clean without any errors or warnings
  • [x] The PR follows the SK Contribution Guidelines
  • [x] The code follows the Python coding conventions
  • [x] All unit tests pass, and I have added new tests where possible
  • [ ] I didn't break anyone :smile:

Validation

From python/:

  • .venv/bin/python -m pytest tests/unit/connectors/memory/test_postgres_store.py -q -> 22 passed
  • .venv/bin/ruff check semantic_kernel/connectors/postgres.py tests/unit/connectors/memory/test_postgres_store.py -> passed
  • .venv/bin/ruff format --check semantic_kernel/connectors/postgres.py tests/unit/connectors/memory/test_postgres_store.py -> passed
  • git diff --check -> passed

pragnyanramtha avatar May 16 '26 20:05 pragnyanramtha

Nice fix — using psycopg.sql composables instead of SQL.format() with plain strings is exactly the right approach here. The root issue (psycopg treating non-composable values as literals rather than SQL expressions) is a subtle but critical correctness bug. A few additional observations:

SQL Injection Safety

Beyond correctness, this migration also closes a potential SQL injection vector. Raw strings passed through SQL.format() with user-controlled field names or filter values could allow injection if input validation upstream is ever relaxed. Using sql.Identifier and sql.Literal makes the intent explicit and safe by construction.

NULL Comparison Handling

Good call on the null commit. The canonical SQL rule is:

  • field = NULL → always false (never matches anything in standard SQL)
  • Correct form: field IS NULL / field IS NOT NULL

The fix should special-case None comparisons in _build_filter before reaching the generic sql.Literal path:

if value is None:
    op_sql = sql.SQL("IS NULL" if op == "==" else "IS NOT NULL")
    return sql.SQL("{} {}").format(sql.Identifier(field), op_sql)

This also means != with None should emit IS NOT NULL, not != NULL.

Edge Cases to Test

Beyond basic comparison and list filters, it would be worth testing:

  1. None equality / inequality (already being addressed)
  2. Field names that are Postgres reserved words (e.g., "order", "limit") — sql.Identifier handles quoting automatically, but a test would confirm
  3. Nested boolean logic: AND/OR combinations with mixed types
  4. Empty list in IN filter: field IN () is invalid SQL in Postgres; should this raise early?

Leading Space Fix

The missing space before WHERE is a classic string concatenation bug. This confirms why composable building is safer — sql.SQL(" WHERE ").join(clauses) or explicit spacing in the composable chain never silently drops whitespace.

Overall this is a well-targeted fix for a real data correctness bug. The addition of the null comparison commit shows good attention to edge cases. +1 from me once the test coverage for null filters lands.

Quantum0uasar avatar May 27 '26 18:05 Quantum0uasar