Skip to main content

tank_core/
row.rs

1use crate::{AsValue, QueryResult, Value, ValueOwned};
2use std::{
3    borrow::Cow,
4    fmt::{self, Debug, Formatter},
5    iter,
6    sync::Arc,
7    vec,
8};
9
10/// Result of a modifying operation (INSERT/UPDATE/DELETE).
11#[derive(Default, Clone, Copy, Debug)]
12pub struct RowsAffected {
13    /// Number of rows modified (if supported by backend).
14    pub rows_affected: Option<u64>,
15    /// Last inserted ID (driver-dependent).
16    pub last_affected_id: Option<i64>,
17}
18
19impl Extend<RowsAffected> for RowsAffected {
20    fn extend<T: IntoIterator<Item = RowsAffected>>(&mut self, iter: T) {
21        for elem in iter {
22            if self.rows_affected.is_some() || elem.rows_affected.is_some() {
23                self.rows_affected = Some(
24                    self.rows_affected.unwrap_or_default() + elem.rows_affected.unwrap_or_default(),
25                );
26            }
27            if elem.last_affected_id.is_some() {
28                self.last_affected_id = elem.last_affected_id;
29            }
30        }
31    }
32}
33
34/// Shared column labels.
35pub type RowLabels = Arc<[String]>;
36
37/// A labeled row, either materialized or decoded from a native driver view.
38pub trait Row: Debug + Send + Sync {
39    /// Column names in result order.
40    fn labels(&self) -> &[String];
41
42    /// Number of columns.
43    fn len(&self) -> usize;
44
45    /// Borrows a stored value or returns a freshly decoded value.
46    /// SQL NULL is a `Value`; `None` means no value at this index.
47    fn value(&self, index: usize) -> Option<Cow<'_, Value<'_>>>;
48
49    fn is_empty(&self) -> bool {
50        self.len() == 0
51    }
52
53    fn get_column(&self, name: &str) -> Option<Cow<'_, Value<'_>>> {
54        self.labels()
55            .iter()
56            .position(|label| label == name)
57            .and_then(|index| self.value(index))
58    }
59
60    /// Iterates values without cloning stored payloads, stopping at a missing cell.
61    fn values(&self) -> impl Iterator<Item = Cow<'_, Value<'_>>> {
62        (0..self.len()).map_while(|index| self.value(index))
63    }
64
65    fn iter(&self) -> impl Iterator<Item = (&str, Cow<'_, Value<'_>>)> {
66        iter::zip(self.labels().iter().map(String::as_str), self.values())
67    }
68
69    /// Consumes the row into an iterator of owned values.
70    fn into_values(self) -> impl Iterator<Item = ValueOwned>
71    where
72        Self: Sized,
73    {
74        let row = self;
75        let mut index = 0;
76        iter::from_fn(move || {
77            let value = row.value(index)?.as_value().into_owned();
78            index += 1;
79            Some(value)
80        })
81    }
82
83    /// Copies names and owns all borrowed value payloads.
84    ///
85    /// Native row views override this to share their cached
86    /// [`RowLabels`] instead of re-allocating it.
87    fn into_owned(self) -> RowOwned
88    where
89        Self: Sized,
90    {
91        RowOwned::new(
92            self.labels().into(),
93            self.values()
94                .map(|value| value.into_owned().into_owned())
95                .collect(),
96        )
97    }
98}
99
100impl<R: Row + ?Sized> Row for &R {
101    #[inline(always)]
102    fn labels(&self) -> &[String] {
103        (**self).labels()
104    }
105
106    #[inline(always)]
107    fn len(&self) -> usize {
108        (**self).len()
109    }
110
111    #[inline(always)]
112    fn value(&self, index: usize) -> Option<Cow<'_, Value<'_>>> {
113        (**self).value(index)
114    }
115
116    #[inline(always)]
117    fn is_empty(&self) -> bool {
118        (**self).is_empty()
119    }
120
121    #[inline(always)]
122    fn get_column(&self, name: &str) -> Option<Cow<'_, Value<'_>>> {
123        (**self).get_column(name)
124    }
125
126    #[inline(always)]
127    fn values(&self) -> impl Iterator<Item = Cow<'_, Value<'_>>> {
128        (**self).values()
129    }
130
131    #[inline(always)]
132    fn iter(&self) -> impl Iterator<Item = (&str, Cow<'_, Value<'_>>)> {
133        (**self).iter()
134    }
135}
136
137/// An owning row with shared column names.
138#[derive(Clone, Default)]
139pub struct RowOwned {
140    pub labels: RowLabels,
141    pub values: Vec<ValueOwned>,
142}
143
144impl RowOwned {
145    pub fn new(labels: RowLabels, values: Vec<ValueOwned>) -> Self {
146        Self { labels, values }
147    }
148}
149
150impl Debug for RowOwned {
151    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
152        f.debug_struct("RowOwned")
153            .field("labels", &self.labels)
154            .field("len", &self.values.len())
155            .finish()
156    }
157}
158
159impl IntoIterator for RowOwned {
160    type Item = ValueOwned;
161    type IntoIter = vec::IntoIter<ValueOwned>;
162
163    #[inline(always)]
164    fn into_iter(self) -> Self::IntoIter {
165        self.values.into_iter()
166    }
167}
168
169impl Row for RowOwned {
170    #[inline(always)]
171    fn labels(&self) -> &[String] {
172        &self.labels
173    }
174
175    #[inline(always)]
176    fn len(&self) -> usize {
177        self.values.len()
178    }
179
180    #[inline(always)]
181    fn value(&self, index: usize) -> Option<Cow<'_, Value<'_>>> {
182        self.values.get(index).map(Cow::Borrowed)
183    }
184
185    fn into_values(self) -> impl Iterator<Item = ValueOwned> {
186        self.values.into_iter()
187    }
188
189    #[inline(always)]
190    fn into_owned(self) -> RowOwned {
191        self
192    }
193}
194
195impl<R: Row> From<R> for QueryResult<R> {
196    fn from(value: R) -> Self {
197        QueryResult::Row(value)
198    }
199}
200
201impl<R> From<RowsAffected> for QueryResult<R> {
202    fn from(value: RowsAffected) -> Self {
203        QueryResult::Affected(value)
204    }
205}