pgrx icon indicating copy to clipboard operation
pgrx copied to clipboard

Safe wrappers for SQL string interpolation functions

Open olirice opened this issue 2 years ago • 0 comments

Provide safe implementations of postgres quoting functions in support of dynamic SQL / query building

Function List Docs

parse_ident ( qualified_identifier text [, strict_mode boolean DEFAULT true ] ) → text[]
-- parse_ident('"SomeSchema".someTable') → {SomeSchema,sometable}

quote_ident ( text ) → text
-- quote_ident('Foo bar') → "Foo bar"

quote_literal ( text ) → text
-- quote_literal(E'O\'Reilly') → 'O''Reilly'

quote_literal ( anyelement ) → text
-- quote_literal(42.5) → '42.5'

format ( formatstr text [, formatarg "any" [, ...] ] ) → text
-- format('Hello %s, %1$s', 'World') → Hello World, World

The implementation for those functions is here


From discord comment it is currently possible to wrap these functions in user code using:

Re-expose via SQL

use pgx::*;

#[pg_extern]
fn quote_ident(ident: String) -> Option<String> {
    let quoted_ident = unsafe {
        direct_function_call::<String>(pg_sys::quote_ident, vec![ident.into_datum()]).unwrap()
    };
    Spi::get_one::<String>(&format!("SELECT {quoted_ident} FROM some_table"))
}

Expose to rust

use pgx::*;

#[pg_extern]
fn quote_ident(ident: String) -> String {
    unsafe {
        direct_function_call::<String>(pg_sys::quote_ident, vec![ident.into_datum()]).unwrap()
    }
}

olirice avatar May 10 '22 19:05 olirice