Macro pgx::extension_sql

source ·
extension_sql!() { /* proc-macro */ }
Expand description

Declare SQL to be included in generated extension script.

Accepts a String literal, a name attribute, and optionally others:

  • name = "item": Set the unique identifier to "item" for use in requires declarations.
  • requires = [item, item_two]: References to other names or Rust items which this SQL should be present after.
  • creates = [ Type(submod::Cust), Enum(Pre), Function(defined)]: Communicates that this SQL block creates certain entities. Please note it does not create matching Rust types.
  • bootstrap (Unique): Communicates that this is SQL intended to go before all other generated SQL.
  • finalize (Unique): Communicates that this is SQL intended to go after all other generated SQL.

You can declare some SQL without any positioning information, meaning it can end up anywhere in the generated SQL:

use pgx_macros::extension_sql;

extension_sql!(
    r#"
    -- SQL statements
    "#,
    name = "demo",
);

To cause the SQL to be output at the start of the generated SQL:

use pgx_macros::extension_sql;

extension_sql!(
    r#"
    -- SQL statements
    "#,
    name = "demo",
    bootstrap,
);

To cause the SQL to be output at the end of the generated SQL:

use pgx_macros::extension_sql;

extension_sql!(
    r#"
    -- SQL statements
    "#,
    name = "demo",
    finalize,
);

To declare the SQL dependent, or a dependency of, other items:

use pgx_macros::extension_sql;

struct Treat;

mod dog_characteristics {
    enum DogAlignment {
        Good
    }
}

extension_sql!(r#"
    -- SQL statements
    "#,
    name = "named_one",
);

extension_sql!(r#"
    -- SQL statements
    "#,
    name = "demo",
    requires = [ "named_one", dog_characteristics::DogAlignment ],
);

To declare the SQL defines some entity (Caution: This is not recommended usage):

use pgx::stringinfo::StringInfo;
use pgx::*;
use pgx_utils::get_named_capture;

#[derive(Debug)]
#[repr(C)]
struct Complex {
    x: f64,
    y: f64,
}

extension_sql!(r#"\
        CREATE TYPE complex;\
    "#,
    name = "create_complex_type",
    creates = [Type(Complex)],
);

#[pg_extern(immutable)]
fn complex_in(input: &core::ffi::CStr) -> PgBox<Complex> {
    todo!()
}

#[pg_extern(immutable)]
fn complex_out(complex: PgBox<Complex>) -> &'static core::ffi::CStr {
    todo!()
}

extension_sql!(r#"\
        CREATE TYPE complex (
            internallength = 16,
            input = complex_in,
            output = complex_out,
            alignment = double
        );\
    "#,
    name = "demo",
    requires = ["create_complex_type", complex_in, complex_out],
);