Skip to main content

sqlx_json/
traits.rs

1//! Row-to-JSON conversion and query-result traits.
2
3use serde_json::Value;
4use sqlx::ColumnIndex;
5
6use crate::row::{DecodeCell, entries};
7
8/// Converts a database row into JSON.
9pub trait RowExt {
10    /// Converts this row's columns to a JSON object.
11    ///
12    /// Each column becomes a key in the returned object, with values
13    /// converted to the most appropriate JSON type. `NULL` columns
14    /// produce [`Value::Null`].
15    fn to_object(&self) -> Value;
16
17    /// Converts this row's columns to ordered `(name, value)` entries.
18    ///
19    /// Keeps column order and duplicate names; values match [`Self::to_object`].
20    fn to_entries(&self) -> Vec<(String, Value)>;
21}
22
23impl<R> RowExt for R
24where
25    R: DecodeCell,
26    usize: ColumnIndex<R>,
27{
28    fn to_object(&self) -> Value {
29        Value::Object(entries(self).collect())
30    }
31
32    fn to_entries(&self) -> Vec<(String, Value)> {
33        entries(self).collect()
34    }
35}
36
37/// Extracts the affected row count and insert id from a backend query result.
38///
39/// sqlx's `Database::QueryResult` associated type exposes these as
40/// inherent methods on each concrete backend type.  This trait provides
41/// a single generic bound so the blanket `Connection` impl can call them
42/// without knowing the concrete type.
43pub trait QueryResult {
44    /// Returns the number of rows affected by the executed statement.
45    fn rows_affected(&self) -> u64;
46
47    /// Returns the id the executed statement generated, if the backend knows it.
48    fn last_insert_id(&self) -> Option<u64>;
49}
50
51impl QueryResult for sqlx::mysql::MySqlQueryResult {
52    fn rows_affected(&self) -> u64 {
53        self.rows_affected()
54    }
55
56    /// The first `AUTO_INCREMENT` id; `MySQL` reports `0` when none was generated.
57    fn last_insert_id(&self) -> Option<u64> {
58        Some(self.last_insert_id()).filter(|id| *id != 0)
59    }
60}
61
62impl QueryResult for sqlx::postgres::PgQueryResult {
63    fn rows_affected(&self) -> u64 {
64        self.rows_affected()
65    }
66
67    /// Always `None`: `PostgreSQL` returns generated keys through `RETURNING`.
68    fn last_insert_id(&self) -> Option<u64> {
69        None
70    }
71}
72
73impl QueryResult for sqlx::sqlite::SqliteQueryResult {
74    fn rows_affected(&self) -> u64 {
75        self.rows_affected()
76    }
77
78    /// Always `None`: `SQLite` keeps the last rowid per connection, not per statement.
79    fn last_insert_id(&self) -> Option<u64> {
80        None
81    }
82}