NyxCode / ormx

bringing orm-like features to sqlx
MIT License
287 stars 32 forks source link

Omit returning clause when no default fields (PostgreSQL) #14

Closed bram209 closed 3 years ago

bram209 commented 3 years ago

Problem

When a ormx::Table does not have any fields marked as default, it would generate a SQL insert statement with a RETURNING clause that does not have any arguments. This results in a database error.

Example

#[derive(Debug, SimpleObject, ormx::Table)]
#[ormx(table = "addresses", id = id, insertable)]
pub struct Address {
    id: Uuid,
    address_line1: Option<String>,
    address_line2: Option<String>,
    city: Option<String>,
    province_code: Option<String>, // ISO 3166-2
    country_code: Option<String>,
    postal_code: Option<String>,
}
error: error returned from database: syntax error at end of input
   --> src/domain.rs:113:31
    |
113 | #[derive(Debug, SimpleObject, ormx::Table)]
    |                               ^^^^^^^^^^^
    |
    = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

Database logs:

2021-07-22 20:14:16.009 UTC [57] ERROR:  syntax error at end of input at character 152
2021-07-22 20:14:16.009 UTC [57] STATEMENT:  INSERT INTO addresses (id, address_line1, address_line2, city, province_code, country_code, postal_code) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING 

Solution

When ormx table has no default fields:

  1. Omit the RETURNING clause
  2. Use sqlx's execute function instead of fetch_one (as the latter expects atleast one returning value)
NyxCode commented 3 years ago

Ah, yes! This is still here because, in an earlier version, ormx was designed for tables with database-generated IDs, so there was always at least one generated column. Great work, thanks!