Skip to content

Commit

Permalink
feat: support calling PostgreSQL procedures with the macros
Browse files Browse the repository at this point in the history
Fixes launchbadge#1449 (I think). I verified that the code fixes the new test.

I used INOUT in setup.sql because older versions of Postgres don't
support OUT parameters.
  • Loading branch information
bgeron committed Jan 2, 2023
1 parent 76ae286 commit e7cf862
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
20 changes: 15 additions & 5 deletions sqlx-core/src/postgres/connection/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,15 @@ SELECT oid FROM pg_catalog.pg_type WHERE typname ILIKE $1

let mut nullables = Vec::new();

if let Some(outputs) = &explain.plan.output {
if let Explain::Plan(
plan @ Plan {
output: Some(outputs),
..
},
) = &explain
{
nullables.resize(outputs.len(), None);
visit_plan(&explain.plan, outputs, &mut nullables);
visit_plan(&plan, outputs, &mut nullables);
}

Ok(nullables)
Expand Down Expand Up @@ -488,9 +494,13 @@ fn visit_plan(plan: &Plan, outputs: &[String], nullables: &mut Vec<Option<bool>>
}

#[derive(serde::Deserialize)]
struct Explain {
#[serde(rename = "Plan")]
plan: Plan,
enum Explain {
/// {"Plan": ...} -- returned for most statements
Plan(Plan),
/// The string "Utility Statement" -- returned for
/// a CALL statement
#[serde(rename = "Utility Statement")]
UtilityStatement,
}

#[derive(serde::Deserialize)]
Expand Down
13 changes: 13 additions & 0 deletions tests/postgres/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ async fn test_void() -> anyhow::Result<()> {
Ok(())
}

#[sqlx_macros::test]
async fn test_call_procedure() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;

let row = sqlx::query!(r#"CALL forty_two(null)"#)
.fetch_one(&mut conn)
.await?;

assert_eq!(row.forty_two, Some(42));

Ok(())
}

#[sqlx_macros::test]
async fn test_query_file() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
Expand Down
3 changes: 3 additions & 0 deletions tests/postgres/setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@ CREATE TABLE products (
name TEXT,
price NUMERIC CHECK (price > 0)
);

CREATE OR REPLACE PROCEDURE forty_two(INOUT forty_two INT = NULL)
LANGUAGE plpgsql AS 'begin forty_two := 42; end;';

0 comments on commit e7cf862

Please sign in to comment.