Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

graphile-sql-expression-validator

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphile-sql-expression-validator

Graphile plugin for SQL expression validation and AST normalization

Source
npmnpm
Version
0.2.2
Version published
Weekly downloads
328
-65.8%
Maintainers
1
Weekly downloads
 
Created
Source

graphile-sql-expression-validator

A Graphile plugin for SQL expression validation and AST normalization. This plugin validates SQL expressions at the GraphQL layer before they reach the database, preventing SQL injection and ensuring only safe expressions are executed.

Installation

npm install graphile-sql-expression-validator

Usage

Smart Comments

Tag columns that contain SQL expressions with @sqlExpression:

COMMENT ON COLUMN metaschema_public.field.default_value IS E'@sqlExpression';

The plugin will automatically look for a companion *_ast column (e.g., default_value_ast) to store the parsed AST.

Custom AST Field Name

By default, the plugin looks for a companion column named <column>_ast. You can override this with @rawSqlAstField:

-- Use a custom AST column name
COMMENT ON COLUMN metaschema_public.field.default_value IS E'@sqlExpression\n@rawSqlAstField my_custom_ast_column';

If @rawSqlAstField points to a non-existent column, the plugin will throw an error. If not specified, it falls back to the <column>_ast convention (and silently skips AST storage if that column doesn't exist).

Plugin Configuration

import SqlExpressionValidatorPlugin from 'graphile-sql-expression-validator';

const postgraphileOptions = {
  appendPlugins: [SqlExpressionValidatorPlugin],
  graphileBuildOptions: {
    sqlExpressionValidator: {
      // Optional: Additional allowed functions beyond defaults
      allowedFunctions: ['my_custom_function'],
      // Optional: Allowed schema names for schema-qualified functions
      allowedSchemas: ['my_schema'],
      // Optional: Maximum expression length (default: 10000)
      maxExpressionLength: 5000,
      // Optional: Auto-allow schemas owned by the current database
      // Queries: SELECT schema_name FROM metaschema_public.schema 
      //          WHERE database_id = jwt_private.current_database_id()
      allowOwnedSchemas: true,
      // Optional: Custom hook for dynamic schema resolution
      getAdditionalAllowedSchemas: async (context) => {
        // Return additional allowed schemas based on request context
        return ['dynamic_schema'];
      },
    },
  },
};

How It Works

  • On mutation input, the plugin detects fields tagged with @sqlExpression
  • If text is provided: Parses the SQL expression, validates the AST, and stores both the canonical text and AST
  • If AST is provided: Validates the AST and deparses to canonical text
  • Validation includes:
    • Node type allowlist (constants, casts, operators, function calls)
    • Function name allowlist for unqualified functions
    • Schema allowlist for schema-qualified functions
    • Rejection of dangerous constructs (subqueries, DDL, DML, column references)

Default Allowed Functions

  • uuid_generate_v4
  • gen_random_uuid
  • now
  • current_timestamp
  • current_date
  • current_time
  • localtime
  • localtimestamp
  • clock_timestamp
  • statement_timestamp
  • transaction_timestamp
  • timeofday
  • random
  • setseed

API

parseAndValidateSqlExpression(expression, options)

Parse and validate a SQL expression string.

import { parseAndValidateSqlExpression } from 'graphile-sql-expression-validator';

const result = parseAndValidateSqlExpression('uuid_generate_v4()');
// { valid: true, ast: {...}, canonicalText: 'uuid_generate_v4()' }

const invalid = parseAndValidateSqlExpression('SELECT * FROM users');
// { valid: false, error: 'Forbidden node type "SelectStmt"...' }

validateAst(ast, options)

Validate an existing AST and get canonical text.

import { validateAst } from 'graphile-sql-expression-validator';

const result = validateAst(myAst);
// { valid: true, canonicalText: 'uuid_generate_v4()' }

Security Notes

  • This plugin provides defense-in-depth at the GraphQL layer
  • It does not replace database-level security measures
  • Superuser/admin paths that bypass GraphQL are not protected
  • Always use RLS and proper database permissions as the primary security layer

Education and Tutorials

  • 🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.

  • 📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.

  • ✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.

  • 🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.

  • Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.

  • 💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.

  • 🔧 Troubleshooting Common issues and solutions for pgpm, PostgreSQL, and testing.

📦 Package Management

  • pgpm: 🖥️ PostgreSQL Package Manager for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.

🧪 Testing

  • pgsql-test: 📊 Isolated testing environments with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
  • pgsql-seed: 🌱 PostgreSQL seeding utilities for CSV, JSON, SQL data loading, and pgpm deployment.
  • supabase-test: 🧪 Supabase-native test harness preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
  • graphile-test: 🔐 Authentication mocking for Graphile-focused test helpers and emulating row-level security contexts.
  • pg-query-context: 🔒 Session context injection to add session-local context (e.g., SET LOCAL) into queries—ideal for setting role, jwt.claims, and other session settings.

🧠 Parsing & AST

  • pgsql-parser: 🔄 SQL conversion engine that interprets and converts PostgreSQL syntax.
  • libpg-query-node: 🌉 Node.js bindings for libpg_query, converting SQL into parse trees.
  • pg-proto-parser: 📦 Protobuf parser for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
  • @pgsql/enums: 🏷️ TypeScript enums for PostgreSQL AST for safe and ergonomic parsing logic.
  • @pgsql/types: 📝 Type definitions for PostgreSQL AST nodes in TypeScript.
  • @pgsql/utils: 🛠️ AST utilities for constructing and transforming PostgreSQL syntax trees.

Credits

🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.

Disclaimer

AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.

No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.

Keywords

postgraphile

FAQs

Package last updated on 06 Jan 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts