Crate pg_query

source ·
Expand description

Rust pg_query   Build Status Latest Version Docs Badge

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

It also allows you to normalize queries (replacing constant values with $1, etc.) and parse these normalized queries into a parse tree again.

When you build this library, it builds parts of the PostgreSQL server source (see libpg_query), and then statically links it into this library.

You can find further examples and a longer rationale for the original Ruby implementation here. The Rust version tries to have a very similar API.

Getting started

Add the following to your Cargo.toml

[dependencies]
pg_query = "5.0"

Example: Parsing a query

use pg_query::NodeRef;

let result = pg_query::parse("SELECT * FROM contacts");
assert!(result.is_ok());
let result = result.unwrap();
assert_eq!(result.tables(), vec!["contacts"]);
assert!(matches!(result.protobuf.nodes()[0].0, NodeRef::SelectStmt(_)));

Re-exports

  • pub use protobuf::Node;
  • pub use protobuf::node::Node as NodeEnum;

Modules

Structs

  • Represents the resulting fingerprint containing both the raw integer form as well as the corresponding 16 character hex value.

Enums

Functions

  • Converts a parsed tree back into a string.
  • Fingerprints the given SQL statement. Useful for comparing parse trees across different implementations of libpg_query.
  • Normalizes the given SQL statement, returning a parametized version.
  • Parses the given SQL statement into the given abstract syntax tree.
  • An experimental API which parses a PLPGSQL function. This currently returns the raw JSON structure.
  • Scan a sql query into a its component of tokens.
  • Split a well-formed query into separate statements.
  • Split a potentially-malformed query into separate statements. Note that invalid tokens will be skipped

Type Aliases

  • Convenient Result alias for returning pg_query::Error.