Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API Reference

This page provides complete technical reference for the pg_ai_query extension API.

Extension Information

PropertyValue
Namepg_ai_query
Version1.0
Schemapublic
DependenciesPostgreSQL 12+

SQL API

CREATE EXTENSION

CREATE EXTENSION [IF NOT EXISTS] pg_ai_query [WITH] [SCHEMA schema_name];

Creates the extension and installs all functions.

Example:

CREATE EXTENSION IF NOT EXISTS pg_ai_query;

DROP EXTENSION

DROP EXTENSION [IF EXISTS] pg_ai_query [CASCADE | RESTRICT];

Removes the extension and all its functions.

Example:

DROP EXTENSION IF EXISTS pg_ai_query CASCADE;

Core Functions API

generate_query()

Signature:

generate_query(
    natural_language_query text,
    api_key text DEFAULT NULL,
    provider text DEFAULT 'auto'
) RETURNS text

Parameters:

ParameterTypeConstraintsDescription
natural_language_querytextNOT NULL, max 4096 charsNatural language description of desired query
api_keytextNULL allowedAPI key for AI provider (optional if configured)
providertext‘openai’, ‘anthropic’, ‘auto’AI provider selection

Returns:

  • Type: text
  • Format: Valid PostgreSQL SQL query
  • Constraints: Always includes LIMIT clause for SELECT statements

Exceptions:

  • EXTERNAL_ROUTINE_EXCEPTION: AI API communication failures
  • INVALID_PARAMETER_VALUE: Invalid provider or malformed input
  • CONFIGURATION_FILE_ERROR: Configuration issues

Example:

SELECT generate_query('show top 10 customers by revenue');

get_database_tables()

Signature:

get_database_tables() RETURNS text

Parameters: None

Returns:

  • Type: text
  • Format: JSON array
  • Content: Table metadata objects

JSON Schema:

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "table_name": {"type": "string"},
      "schema_name": {"type": "string"},
      "table_type": {"type": "string"},
      "estimated_rows": {"type": "integer"},
      "table_size": {"type": "string"}
    },
    "required": ["table_name", "schema_name", "table_type"]
  }
}

Exceptions:

  • EXTERNAL_ROUTINE_EXCEPTION: Database introspection failures

Example:

SELECT get_database_tables();

get_table_details()

Signature:

get_table_details(
    table_name text,
    schema_name text DEFAULT 'public'
) RETURNS text

Parameters:

ParameterTypeConstraintsDescription
table_nametextNOT NULL, must existName of table to analyze
schema_nametextValid schema nameSchema containing the table

Returns:

  • Type: text
  • Format: JSON object
  • Content: Detailed table structure information

JSON Schema:

{
  "type": "object",
  "properties": {
    "table_name": {"type": "string"},
    "schema_name": {"type": "string"},
    "columns": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "column_name": {"type": "string"},
          "data_type": {"type": "string"},
          "is_nullable": {"type": "boolean"},
          "column_default": {"type": ["string", "null"]},
          "character_maximum_length": {"type": ["integer", "null"]},
          "numeric_precision": {"type": ["integer", "null"]},
          "is_primary_key": {"type": "boolean"},
          "is_unique": {"type": "boolean"}
        }
      }
    },
    "constraints": {"type": "array"},
    "foreign_keys": {"type": "array"},
    "indexes": {"type": "array"}
  }
}

Exceptions:

  • INVALID_PARAMETER_VALUE: Table does not exist
  • EXTERNAL_ROUTINE_EXCEPTION: Database introspection failures

Example:

SELECT get_table_details('users', 'public');

Configuration API

Configuration File Location

The extension reads configuration from:

~/.pg_ai.config

Configuration Structure

[general]
# General settings
log_level = "INFO" | "DEBUG" | "WARNING" | "ERROR"
enable_logging = true | false
enable_postgresql_elog = true | false
request_timeout_ms = <integer>
max_retries = <integer>

[query]
# Query generation settings
enforce_limit = true | false
default_limit = <integer>

[openai]
# OpenAI provider settings
api_key = "<api_key_string>"
default_model = "gpt-4o" | "gpt-4" | "gpt-3.5-turbo"

[anthropic]
# Anthropic provider settings
api_key = "<api_key_string>"
default_model = "claude-3-5-sonnet-20241022"

Configuration Validation Rules

SettingTypeRange/ValuesDefault
log_levelstringDEBUG, INFO, WARNING, ERRORINFO
enable_loggingbooleantrue, falsefalse
enable_postgresql_elogbooleantrue, falsetrue
request_timeout_msinteger1000-30000030000
max_retriesinteger0-103
enforce_limitbooleantrue, falsetrue
default_limitinteger1-10000001000
api_keystringProvider-specific format“”
default_modelstringProvider-specific valuesProvider default

Error Codes

Extension Error Codes

CodeNameDescription
22023INVALID_PARAMETER_VALUEInvalid function parameter
38001CONTAINING_SQL_NOT_PERMITTEDUnsafe SQL operation attempted
38003PROHIBITED_SQL_STATEMENT_ATTEMPTEDForbidden query type
39001EXTERNAL_ROUTINE_EXCEPTIONAI API communication error
58030IO_ERRORFile system or network I/O error
XX000INTERNAL_ERRORUnexpected internal error

AI Provider Error Codes

OpenAI Errors

HTTP CodeError TypeDescription
400invalid_request_errorInvalid request parameters
401authentication_errorInvalid API key
403permission_errorInsufficient permissions
429rate_limit_errorRate limit exceeded
500api_errorOpenAI server error

Anthropic Errors

HTTP CodeError TypeDescription
400invalid_request_errorInvalid request format
401authentication_errorInvalid API key
403permission_errorAccess denied
429rate_limit_errorRate limit exceeded
500api_errorAnthropic server error

Internal APIs

Schema Discovery Engine

The extension uses these internal functions for schema analysis:

-- Internal function signatures (not callable by users)
_pg_ai_analyze_schema() RETURNS schema_info;
_pg_ai_get_table_relationships() RETURNS relationship_map;
_pg_ai_validate_query(query text) RETURNS boolean;

Query Generation Pipeline

  1. Input Validation: Validates natural language input
  2. Schema Discovery: Analyzes database structure
  3. Context Building: Creates AI prompt with schema context
  4. AI Request: Sends request to configured provider
  5. Response Parsing: Extracts SQL from AI response
  6. Query Validation: Validates generated SQL for safety
  7. Result Return: Returns validated SQL query

Security Validation

The extension performs these security checks:

  • SQL Injection Prevention: Sanitizes all inputs
  • System Table Protection: Blocks access to pg_* and information_schema
  • DDL Restriction: Can generate DDL but with warnings
  • Privilege Respect: Honors PostgreSQL permission system

Performance Characteristics

Memory Usage

OperationMemory UsageDuration
Schema Analysis~1MB per 100 tables100-500ms
Query Generation~5-10MB per request1-5 seconds
Configuration Load~1KB<10ms

Network Requirements

ProviderEndpointProtocolBandwidth
OpenAIapi.openai.comHTTPS1-10KB per request
Anthropicapi.anthropic.comHTTPS1-10KB per request

Caching Behavior

  • Schema Information: Cached per PostgreSQL session
  • Configuration: Cached until session restart
  • AI Responses: Not cached (each request is fresh)

Extension Metadata

System Catalog Integration

The extension registers these entries:

-- Extension registration
SELECT * FROM pg_extension WHERE extname = 'pg_ai_query';

-- Function registration
SELECT * FROM pg_proc WHERE proname LIKE '%generate%';

-- Dependencies
SELECT * FROM pg_depend WHERE refobjid IN (
    SELECT oid FROM pg_extension WHERE extname = 'pg_ai_query'
);

Version Information

-- Check extension version
SELECT extversion FROM pg_extension WHERE extname = 'pg_ai_query';

-- Function definitions
\df+ generate_query
\df+ get_database_tables
\df+ get_table_details

Compatibility

PostgreSQL Versions

PostgreSQL VersionSupport StatusNotes
12.x✅ SupportedMinimum required version
13.x✅ SupportedFull compatibility
14.x✅ SupportedRecommended
15.x✅ SupportedFull compatibility
16.x✅ SupportedLatest tested

Operating Systems

OSSupport StatusNotes
Linux (RHEL/CentOS)✅ SupportedPrimary development platform
Linux (Ubuntu/Debian)✅ SupportedWell tested
macOS✅ SupportedDevelopment and testing
Windows⚠️ ExperimentalLimited testing

AI Provider Compatibility

ProviderAPI VersionModels Supported
OpenAIv1GPT-4o, GPT-4, GPT-3.5-turbo
Anthropicv1Claude 3.5 Sonnet

This completes the technical API reference for the pg_ai_query extension.