• Stars
    star
    1,173
  • Rank 39,852 (Top 0.8 %)
  • Language
    C
  • License
    BSD 3-Clause "New...
  • Created about 9 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

C library for accessing the PostgreSQL parser outside of the server environment

libpg_query

C library for accessing the PostgreSQL parser outside of the server.

This library uses the actual PostgreSQL server source to parse SQL queries and return the internal PostgreSQL parse tree.

Note that this is mostly intended as a base library for pg_query (Ruby), pg_query.go (Go), pgsql-parser (Node), psqlparse (Python) and pglast (Python 3).

You can find further background to why a query's parse tree is useful here: https://pganalyze.com/blog/parse-postgresql-queries-in-ruby.html

Installation

git clone -b 15-latest git://github.com/pganalyze/libpg_query
cd libpg_query
make

Due to compiling parts of PostgreSQL, running make will take a bit. Expect up to 3 minutes.

For a production build, its best to use a specific git tag (see CHANGELOG).

Usage: Parsing a query

A full example that parses a query looks like this:

#include <pg_query.h>
#include <stdio.h>

int main() {
  PgQueryParseResult result;

  result = pg_query_parse("SELECT 1");

  printf("%s\n", result.parse_tree);

  pg_query_free_parse_result(result);
}

Compile it like this:

cc -Ilibpg_query -Llibpg_query example.c -lpg_query

This will output the parse tree (whitespace adjusted here for better readability):

{
    "version": 150001,
    "stmts": [
        {
            "stmt": {
                "SelectStmt": {
                    "targetList": [
                        {
                            "ResTarget": {
                                "val": {
                                    "A_Const": {
                                        "val": {
                                            "Integer": {
                                                "ival": 1
                                            }
                                        },
                                        "location": 7
                                    }
                                },
                                "location": 7
                            }
                        }
                    ],
                    "limitOption": "LIMIT_OPTION_DEFAULT",
                    "op": "SETOP_NONE"
                }
            }
        }
    ]
}

Usage: Scanning a query into its tokens using the PostgreSQL scanner/lexer

pg_query also exposes the underlying scanner of Postgres, which is also used in the very first part in the parsing process. It can be useful on its own for e.g. syntax highlighting, where one is mostly concerned with differentiating keywords from identifiers and other parts of the query:

#include <stdio.h>

#include <pg_query.h>
#include "protobuf/pg_query.pb-c.h"

int main() {
  PgQueryScanResult result;
  PgQuery__ScanResult *scan_result;
  PgQuery__ScanToken *scan_token;
  const ProtobufCEnumValue *token_kind;
  const ProtobufCEnumValue *keyword_kind;
  const char *input = "SELECT update AS left /* comment */ FROM between";

  result = pg_query_scan(input);
  scan_result = pg_query__scan_result__unpack(NULL, result.pbuf.len, (void *) result.pbuf.data);

  printf("  version: %d, tokens: %ld, size: %d\n", scan_result->version, scan_result->n_tokens, result.pbuf.len);
  for (size_t j = 0; j < scan_result->n_tokens; j++) {
    scan_token = scan_result->tokens[j];
    token_kind = protobuf_c_enum_descriptor_get_value(&pg_query__token__descriptor, scan_token->token);
    keyword_kind = protobuf_c_enum_descriptor_get_value(&pg_query__keyword_kind__descriptor, scan_token->keyword_kind);
    printf("  \"%.*s\" = [ %d, %d, %s, %s ]\n", scan_token->end - scan_token->start, &(input[scan_token->start]), scan_token->start, scan_token->end, token_kind->name, keyword_kind->name);
  }

  pg_query__scan_result__free_unpacked(scan_result, NULL);
  pg_query_free_scan_result(result);

  return 0;
}

This will output the following:

  version: 150001, tokens: 7, size: 77
  "SELECT" = [ 0, 6, SELECT, RESERVED_KEYWORD ]
  "update" = [ 7, 13, UPDATE, UNRESERVED_KEYWORD ]
  "AS" = [ 14, 16, AS, RESERVED_KEYWORD ]
  "left" = [ 17, 21, LEFT, TYPE_FUNC_NAME_KEYWORD ]
  "/* comment */" = [ 22, 35, C_COMMENT, NO_KEYWORD ]
  "FROM" = [ 36, 40, FROM, RESERVED_KEYWORD ]
  "between" = [ 41, 48, BETWEEN, COL_NAME_KEYWORD ]

Where the each element in the token list has the following fields:

  1. Start location in the source string
  2. End location in the source string
  3. Token value - see Token type in protobuf/pg_query.proto
  4. Keyword type - see KeywordKind type in protobuf/pg_query.proto, possible values: NO_KEYWORD: Not a keyword UNRESERVED_KEYWORD: Unreserved keyword (available for use as any kind of unescaped name) COL_NAME_KEYWORD: Unreserved keyword (can be unescaped column/table/etc names, cannot be unescaped function or type name) TYPE_FUNC_NAME_KEYWORD: Reserved keyword (can be unescaped function or type name, cannot be unescaped column/table/etc names) RESERVED_KEYWORD: Reserved keyword (cannot be unescaped column/table/variable/type/function names)

Note that whitespace does not show as tokens.

Usage: Fingerprinting a query

Fingerprinting allows you to identify similar queries that are different only because of the specific object that is being queried for (i.e. different object ids in the WHERE clause), or because of formatting.

Example:

#include <pg_query.h>
#include <stdio.h>

int main() {
  PgQueryFingerprintResult result;

  result = pg_query_fingerprint("SELECT 1");

  printf("%s\n", result.fingerprint_str);

  pg_query_free_fingerprint_result(result);
}

This will output:

50fde20626009aba

See https://github.com/pganalyze/libpg_query/wiki/Fingerprinting for the full fingerprinting rules.

Usage: Parsing a PL/pgSQL function

A full example that parses a PL/pgSQL method looks like this:

#include <pg_query.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
  PgQueryPlpgsqlParseResult result;

  result = pg_query_parse_plpgsql(" \
  CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar, \
                                                  v_version varchar) \
RETURNS varchar AS $$ \
BEGIN \
    IF v_version IS NULL THEN \
        RETURN v_name; \
    END IF; \
    RETURN v_name || '/' || v_version; \
END; \
$$ LANGUAGE plpgsql;");

  if (result.error) {
    printf("error: %s at %d\n", result.error->message, result.error->cursorpos);
  } else {
    printf("%s\n", result.plpgsql_funcs);
  }

  pg_query_free_plpgsql_parse_result(result);

  return 0;
}

This will output:

[
{"PLpgSQL_function":{"datums":[{"PLpgSQL_var":{"refname":"found","datatype":{"PLpgSQL_type":{"typname":"UNKNOWN"}}}}],"action":{"PLpgSQL_stmt_block":{"lineno":1,"body":[{"PLpgSQL_stmt_if":{"lineno":1,"cond":{"PLpgSQL_expr":{"query":"SELECT v_version IS NULL"}},"then_body":[{"PLpgSQL_stmt_return":{"lineno":1,"expr":{"PLpgSQL_expr":{"query":"SELECT v_name"}}}}]}},{"PLpgSQL_stmt_return":{"lineno":1,"expr":{"PLpgSQL_expr":{"query":"SELECT v_name || '/' || v_version"}}}}]}}}}
]

Versions

For stability, it is recommended you use individual tagged git versions, see CHANGELOG.

Each major version is maintained in a dedicated git branch. Only the latest Postgres stable release receives active updates.

PostgreSQL Major Version Branch Status
15 15-latest Active development
14 14-latest Critical fixes only
13 13-latest Critical fixes only
12 (n/a) Not supported
11 (n/a) Not supported
10 10-latest No longer supported
9.6 (n/a) Not supported
9.5 9.5-latest No longer supported
9.4 9.4-latest No longer supported

Resources

pg_query wrappers in other languages:

Products, tools and libraries built on pg_query:

Please feel free to open a PR to add yours! :)

Authors

License

PostgreSQL server source code, used under the PostgreSQL license.
Portions Copyright (c) 1996-2023, The PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California

All other parts are licensed under the 3-clause BSD license, see LICENSE file for details.
Copyright (c) 2015, Lukas Fittl [email protected] Copyright (c) 2016-2023, Duboce Labs, Inc. (pganalyze) [email protected]

More Repositories

1

pg_query

Ruby extension to parse, deparse and normalize SQL queries using the PostgreSQL query parser
C
778
star
2

pg_query_go

Go library to parse and normalize SQL queries using the PostgreSQL query parser
C
642
star
3

collector

pganalyze statistics collector for gathering PostgreSQL metrics and log data
Go
333
star
4

pg_query.rs

Rust library to parse, deparse and normalize SQL queries using the PostgreSQL query parser
Rust
125
star
5

pg-query-emscripten

Emscripten Port of pg_query to easily play with it in the browser
C++
76
star
6

activerecord-copy

Supports binary COPY into PostgreSQL with activerecord
Ruby
41
star
7

queryparser

DEPRECATED - use libpg_query instead! https://github.com/lfittl/libpg_query
C
38
star
8

lint

Check for missing indexes during development using constraint programming
Rust
35
star
9

materialized-views-demo

Example for using Materialized Views in Rails
Ruby
18
star
10

sidekiq_server.rs

A Sidekiq server implemented in Rust
Rust
16
star
11

pg_simulator

PostgreSQL Schema Simulator - Load schema and statistics information into a database and run EXPLAIN on queries
Ruby
15
star
12

react-svg-example

Example of how to build UI components with React and SVG
TypeScript
14
star
13

subqueries-rails-example

Ruby
11
star
14

pgcon2023

Simple index selection model using constraint programming presented at PGCon 2023
Python
10
star
15

pganalyze-docs

Documentation for pganalyze - PostgreSQL Performance Monitoring
MDX
10
star
16

graphql-batch-example

Code example for "Efficient GraphQL queries in Ruby on Rails & Postgres" blog post
Ruby
9
star
17

cp-sat-python-example

Python
9
star
18

postgis_mock

Simplified version of the PostGIS extension functions, types and operators, to be used for parsing/planning queries that depend on PostGIS APIs, but without calling actual PostGIS code.
PLpgSQL
3
star
19

pgday-chicago-2024

Python
3
star
20

full-text-search-rails

Example for article "Full Text Search in Milliseconds with Rails and PostgreSQL"
Ruby
2
star
21

collector-snapshot

Protocol Buffers definition for the pganalyze collector
1
star
22

heroku-plugin-psql

Like heroku pg:psql but for any Postgres database
TypeScript
1
star
23

postgres-local-sync

Heroku helper app to synchronize your staging database to local development, via S3
Ruby
1
star
24

index-advisor-feedback

1
star