Skip to content

Conversation

@tobyhede
Copy link
Contributor

@tobyhede tobyhede commented Dec 11, 2025

Summary

  • Refactor simple PL/pgSQL functions to LANGUAGE SQL for better performance
  • Add function language choice guidelines to CLAUDE.md documenting when to use SQL vs PL/pgSQL

Rationale

PostgreSQL can inline simple SQL functions into calling queries, eliminating function call overhead. This is particularly important for functions used in index expressions (GIN indexes) where the function is called on every row insert/update.

Test plan

  • Verify tests pass
  • Review documentation renders correctly

Convert 7 simple wrapper functions from plpgsql to SQL language to enable
PostgreSQL query planner to inline them, improving performance.

Functions converted:
- eql_v2.to_encrypted(jsonb) - cast JSONB to encrypted type
- eql_v2.to_encrypted(text) - cast text to encrypted type
- eql_v2.to_jsonb(eql_v2_encrypted) - extract JSONB from encrypted type
- eql_v2.ciphertext(eql_v2_encrypted) - extract ciphertext wrapper
- eql_v2.meta_data(jsonb) - extract metadata from JSONB
- eql_v2.meta_data(eql_v2_encrypted) - extract metadata wrapper
- eql_v2.compare_literal() - literal comparison for btree fallback

All functions are marked STRICT, making NULL checks in plpgsql code redundant.
SQL language functions are eligible for inlining by the query planner, while
plpgsql functions are always treated as opaque function calls.

Files modified:
- src/encrypted/casts.sql (3 functions)
- src/encrypted/functions.sql (3 functions)
- src/encrypted/compare.sql (1 function)
Document when to use LANGUAGE SQL vs LANGUAGE plpgsql for PostgreSQL
functions. SQL is preferred for simple functions due to inlining benefits
and better index performance. PL/pgSQL should be used when procedural
features (variables, exception handling, loops, dynamic SQL) are needed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants