baserow_rs/api/
table_operations.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use crate::{
    api::client::BaserowClient,
    filter::{Filter, FilterTriple},
    mapper::{FieldMapper, TableMapper},
    Baserow, BaserowTable, OrderDirection,
};
use async_trait::async_trait;
use reqwest::{header::AUTHORIZATION, Client, StatusCode};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
use std::{collections::HashMap, error::Error, vec};

/// Response structure for table row queries
///
/// Contains the query results along with pagination information.
#[derive(Deserialize, Serialize, Debug)]
pub struct RowsResponse {
    /// Total count of records that match the query criteria, not just the current page
    pub count: i32,
    /// URL for the next page of results, if available
    pub next: Option<String>,
    /// URL for the previous page of results, if available
    pub previous: Option<String>,
    /// The actual rows returned by the query
    pub results: Vec<HashMap<String, Value>>,
}

/// Response structure for typed table row queries
///
/// Contains the query results along with pagination information, where results
/// are deserialized into the specified type.
#[derive(Deserialize, Serialize, Debug)]
pub struct TypedRowsResponse<T> {
    /// Total count of records that match the query criteria, not just the current page
    pub count: i32,
    /// URL for the next page of results, if available
    pub next: Option<String>,
    /// URL for the previous page of results, if available
    pub previous: Option<String>,
    /// The actual rows returned by the query, deserialized into type T
    pub results: Vec<T>,
}

/// Represents a query request for table rows
///
/// This struct encapsulates all the parameters that can be used to query rows
/// from a Baserow table, including filtering, sorting, and pagination options.
#[derive(Clone, Debug)]
pub struct RowRequest {
    /// Optional view ID to query rows from a specific view
    pub view_id: Option<i32>,
    /// Optional sorting criteria
    pub order: Option<HashMap<String, OrderDirection>>,
    /// Optional filter conditions
    pub filter: Option<Vec<FilterTriple>>,
    /// Optional page size for pagination
    pub page_size: Option<i32>,
    /// Optional offset for pagination
    pub offset: Option<i32>,
}

impl Default for RowRequest {
    fn default() -> Self {
        Self {
            view_id: None,
            order: None,
            filter: None,
            page_size: None,
            offset: None,
        }
    }
}

/// Builder for constructing table row queries
///
/// Provides a fluent interface for building queries with filtering, sorting,
/// and other options.
pub struct RowRequestBuilder {
    baserow: Option<Baserow>,
    table: Option<BaserowTable>,
    request: RowRequest,
}

impl RowRequestBuilder {
    pub(crate) fn new() -> Self {
        Self {
            baserow: None,
            table: None,
            request: RowRequest::default(),
        }
    }

    /// Set the view ID to query rows from a specific view
    pub fn view(mut self, id: i32) -> Self {
        self.request.view_id = Some(id);
        self
    }

    /// Set the number of rows to return per page
    pub fn page_size(mut self, size: i32) -> Self {
        self.request.page_size = Some(size);
        self
    }

    /// Set the offset for pagination
    pub fn offset(mut self, offset: i32) -> Self {
        self.request.offset = Some(offset);
        self
    }

    pub fn with_table(self, table: BaserowTable) -> Self {
        Self {
            table: Some(table),
            ..self
        }
    }

    pub fn with_baserow(self, baserow: Baserow) -> Self {
        Self {
            baserow: Some(baserow),
            ..self
        }
    }

    /// Add sorting criteria to the query
    pub fn order_by(mut self, field: &str, direction: OrderDirection) -> Self {
        match self.request.order {
            Some(mut order) => {
                order.insert(String::from(field), direction);
                self.request.order = Some(order);
            }
            None => {
                let mut order = HashMap::new();
                order.insert(String::from(field), direction);
                self.request.order = Some(order);
            }
        }
        self
    }

    /// Add a filter condition to the query
    pub fn filter_by(mut self, field: &str, filter_op: Filter, value: &str) -> Self {
        match self.request.filter {
            Some(mut filter) => {
                filter.push(FilterTriple {
                    field: String::from(field),
                    filter: filter_op,
                    value: String::from(value),
                });
                self.request.filter = Some(filter);
            }
            None => {
                let mut filter: Vec<FilterTriple> = vec![];
                filter.push(FilterTriple {
                    field: String::from(field),
                    filter: filter_op,
                    value: String::from(value),
                });
                self.request.filter = Some(filter);
            }
        }
        self
    }

    /// Execute the query and return typed results
    pub async fn get<T>(self) -> Result<TypedRowsResponse<T>, Box<dyn Error>>
    where
        T: DeserializeOwned + 'static,
    {
        let table = self.table.expect("Table instance is missing");
        let baserow = self.baserow.expect("Baserow instance is missing");
        table.get(baserow, self.request).await
    }
}

/// Trait defining the public operations available on a Baserow table
///
/// This trait provides the core CRUD operations for working with Baserow tables.
/// All operations are async and return Results to handle potential errors.
///
/// # Example
/// ```no_run
/// use baserow_rs::{ConfigBuilder, Baserow, BaserowTableOperations, api::client::BaserowClient};
/// use std::collections::HashMap;
/// use serde_json::Value;
///
/// #[tokio::main]
/// async fn main() {
///     let config = ConfigBuilder::new()
///         .base_url("https://api.baserow.io")
///         .api_key("your-api-key")
///         .build();
///
///     let baserow = Baserow::with_configuration(config);
///     let table = baserow.table_by_id(1234);
///
///     // Create a new record
///     let mut data = HashMap::new();
///     data.insert("Name".to_string(), Value::String("Test".to_string()));
///     let result = table.create_one(data).await.unwrap();
/// }
/// ```
#[async_trait]
pub trait BaserowTableOperations {
    /// Automatically maps the table fields to their corresponding types
    ///
    /// This method fetches the table schema and sets up field mappings for type conversion.
    /// Call this before performing operations if you need type-safe field access.
    async fn auto_map(self) -> Result<BaserowTable, Box<dyn Error>>;

    /// Creates a new query builder for constructing complex table queries
    ///
    /// This is the preferred method for building queries with filters, sorting,
    /// and pagination options. The builder provides a fluent interface for
    /// constructing queries.
    ///
    /// # Example
    /// ```no_run
    /// use baserow_rs::{ConfigBuilder, Baserow, BaserowTableOperations, OrderDirection, filter::Filter};
    /// use baserow_rs::api::client::BaserowClient;
    /// use std::collections::HashMap;
    /// use serde_json::Value;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let baserow = Baserow::with_configuration(ConfigBuilder::new().build());
    ///     let table = baserow.table_by_id(1234);
    ///
    ///     let results = table.query()
    ///         .filter_by("Status", Filter::Equal, "Active")
    ///         .order_by("Created", OrderDirection::Desc)
    ///         .get::<HashMap<String, Value>>()
    ///         .await
    ///         .unwrap();
    /// }
    /// ```
    fn query(self) -> RowRequestBuilder;

    #[deprecated(since = "0.1.0", note = "Use the query() method instead")]
    fn rows(self) -> RowRequestBuilder;

    /// Execute a row request and return typed results
    ///
    /// # Type Parameters
    /// * `T` - The type to deserialize the results into
    ///
    /// # Arguments
    /// * `request` - The query parameters encapsulated in a RowRequest
    ///
    /// # Returns
    /// A TypedRowsResponse containing the query results and pagination information
    async fn get<T>(
        &self,
        baserow: Baserow,
        request: RowRequest,
    ) -> Result<TypedRowsResponse<T>, Box<dyn Error>>
    where
        T: DeserializeOwned + 'static;

    /// Creates a single record in the table
    ///
    /// # Arguments
    /// * `data` - A map of field names to values representing the record to create
    ///
    /// # Returns
    /// The created record including any auto-generated fields (like ID)
    async fn create_one(
        self,
        data: HashMap<String, Value>,
    ) -> Result<HashMap<String, Value>, Box<dyn Error>>;

    /// Retrieves a single record from the table by ID
    ///
    /// # Type Parameters
    /// * `T` - The type to deserialize into. Defaults to HashMap<String, Value>.
    ///         When using a custom type, the table must be mapped using `auto_map()` first.
    ///
    /// # Arguments
    /// * `id` - The unique identifier of the record to retrieve
    ///
    /// # Returns
    /// The requested record if found, either as a HashMap or deserialized into type T
    ///
    /// # Example
    /// ```no_run
    /// use baserow_rs::{ConfigBuilder, Baserow, BaserowTableOperations, api::client::BaserowClient};
    /// use serde::Deserialize;
    /// use std::collections::HashMap;
    /// use serde_json::Value;
    ///
    /// #[derive(Deserialize)]
    /// struct User {
    ///     name: String,
    ///     email: String,
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = ConfigBuilder::new()
    ///         .base_url("https://api.baserow.io")
    ///         .api_key("your-api-key")
    ///         .build();
    ///
    ///     let baserow = Baserow::with_configuration(config);
    ///     let table = baserow.table_by_id(1234);
    ///
    ///     // Get as HashMap (default)
    ///     let row: HashMap<String, Value> = table.clone().get_one(1).await.unwrap();
    ///
    ///     // Get as typed struct
    ///     let user: User = table.auto_map()
    ///         .await
    ///         .unwrap()
    ///         .get_one(1)
    ///         .await
    ///         .unwrap();
    /// }
    /// ```
    async fn get_one<T>(self, id: u64) -> Result<T, Box<dyn Error>>
    where
        T: DeserializeOwned + 'static;

    /// Updates a single record in the table
    ///
    /// # Arguments
    /// * `id` - The unique identifier of the record to update
    /// * `data` - A map of field names to new values
    ///
    /// # Returns
    /// The updated record
    async fn update(
        self,
        id: u64,
        data: HashMap<String, Value>,
    ) -> Result<HashMap<String, Value>, Box<dyn Error>>;

    /// Deletes a single record from the table
    ///
    /// # Arguments
    /// * `id` - The unique identifier of the record to delete
    async fn delete(self, id: u64) -> Result<(), Box<dyn Error>>;
}

#[async_trait]
impl BaserowTableOperations for BaserowTable {
    async fn auto_map(mut self) -> Result<BaserowTable, Box<dyn Error>> {
        let id = self.id.ok_or("Table ID is missing")?;

        let baserow = self.baserow.clone().ok_or("Baserow instance is missing")?;
        let fields = baserow.table_fields(id).await?;

        let mut mapper = TableMapper::new();
        mapper.map_fields(fields.clone());
        self.mapper = Some(mapper);

        Ok(self)
    }

    fn query(self) -> RowRequestBuilder {
        RowRequestBuilder::new()
            .with_baserow(self.baserow.clone().unwrap())
            .with_table(self.clone())
    }

    fn rows(self) -> RowRequestBuilder {
        self.query()
    }

    async fn get<T>(
        &self,
        baserow: Baserow,
        request: RowRequest,
    ) -> Result<TypedRowsResponse<T>, Box<dyn Error>>
    where
        T: DeserializeOwned + 'static,
    {
        let url = format!(
            "{}/api/database/rows/table/{}/",
            &baserow.configuration.base_url,
            self.id.unwrap()
        );

        let mut req = Client::new().get(url);

        if let Some(view_id) = request.view_id {
            req = req.query(&[("view_id", view_id.to_string())]);
        }

        if baserow.configuration.jwt.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("JWT {}", &baserow.configuration.database_token.unwrap()),
            );
        } else if baserow.configuration.database_token.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("Token {}", &baserow.configuration.database_token.unwrap()),
            );
        }

        if let Some(order) = request.order {
            let mut order_str = String::new();
            for (field, direction) in order {
                order_str.push_str(&format!(
                    "{}{}",
                    match direction {
                        OrderDirection::Asc => "",
                        OrderDirection::Desc => "-",
                    },
                    field
                ));
            }

            req = req.query(&[("order_by", order_str)]);
        }

        if let Some(filter) = request.filter {
            for triple in filter {
                req = req.query(&[(
                    &format!("filter__{}__{}", triple.field, triple.filter.as_str()),
                    triple.value,
                )]);
            }
        }

        if let Some(size) = request.page_size {
            req = req.query(&[("size", size.to_string())]);
        }

        if let Some(offset) = request.offset {
            req = req.query(&[("offset", offset.to_string())]);
        }

        let resp = req.send().await?;

        match resp.status() {
            StatusCode::OK => {
                let response: RowsResponse = resp.json().await?;

                // Try direct deserialization first
                let results_clone = response.results.clone();
                let typed_results = match serde_json::from_value::<Vec<T>>(Value::Array(
                    results_clone
                        .into_iter()
                        .map(|m| Value::Object(serde_json::Map::from_iter(m.into_iter())))
                        .collect(),
                )) {
                    Ok(results) => results,
                    Err(_) => {
                        // Fall back to mapper for custom types
                        let mapper = self.mapper.clone().ok_or("Table mapper is missing. Call auto_map() first when using typed responses.")?;
                        response
                            .results
                            .into_iter()
                            .map(|row| mapper.deserialize_row(row))
                            .collect::<Result<Vec<T>, _>>()?
                    }
                };

                Ok(TypedRowsResponse {
                    count: response.count,
                    next: response.next,
                    previous: response.previous,
                    results: typed_results,
                })
            }
            _ => Err(Box::new(resp.error_for_status().unwrap_err())),
        }
    }

    async fn create_one(
        self,
        data: HashMap<String, Value>,
    ) -> Result<HashMap<String, Value>, Box<dyn Error>> {
        let baserow = self.baserow.expect("Baserow instance is missing");

        let url = format!(
            "{}/api/database/rows/table/{}/",
            &baserow.configuration.base_url,
            self.id.unwrap()
        );

        let mut req = baserow.client.post(url);

        if baserow.configuration.jwt.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("JWT {}", &baserow.configuration.jwt.unwrap()),
            );
        } else if baserow.configuration.database_token.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("Token {}", &baserow.configuration.database_token.unwrap()),
            );
        }

        let resp = req.json(&data).send().await?;

        match resp.status() {
            StatusCode::OK => Ok(resp.json::<HashMap<String, Value>>().await?),
            _ => Err(Box::new(resp.error_for_status().unwrap_err())),
        }
    }

    async fn get_one<T>(mut self, id: u64) -> Result<T, Box<dyn Error>>
    where
        T: DeserializeOwned + 'static,
    {
        let baserow = self.baserow.expect("Baserow instance is missing");

        let url = format!(
            "{}/api/database/rows/table/{}/{}/",
            &baserow.configuration.base_url,
            self.id.unwrap(),
            id
        );

        let mut req = baserow.client.get(url);

        if baserow.configuration.jwt.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("JWT {}", &baserow.configuration.jwt.unwrap()),
            );
        } else if baserow.configuration.database_token.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("Token {}", &baserow.configuration.database_token.unwrap()),
            );
        }

        let resp = req.send().await?;

        match resp.status() {
            StatusCode::OK => {
                let row: HashMap<String, Value> = resp.json().await?;

                // For HashMap<String, Value>, use serde to convert
                if std::any::TypeId::of::<T>() == std::any::TypeId::of::<HashMap<String, Value>>() {
                    Ok(serde_json::from_value(serde_json::to_value(row)?)?)
                } else {
                    // For other types, use the mapper if available
                    let mapper = self.mapper.clone().ok_or("Table mapper is missing. Call auto_map() first when using typed responses.")?;
                    Ok(mapper.deserialize_row(row)?)
                }
            }
            _ => Err(Box::new(resp.error_for_status().unwrap_err())),
        }
    }

    async fn update(
        self,
        id: u64,
        data: HashMap<String, Value>,
    ) -> Result<HashMap<String, Value>, Box<dyn Error>> {
        let baserow = self.baserow.expect("Baserow instance is missing");

        let url = format!(
            "{}/api/database/rows/table/{}/{}/",
            &baserow.configuration.base_url,
            self.id.unwrap(),
            id
        );

        let mut req = baserow.client.patch(url);

        if baserow.configuration.jwt.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("JWT {}", &baserow.configuration.jwt.unwrap()),
            );
        } else if baserow.configuration.database_token.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("Token {}", &baserow.configuration.database_token.unwrap()),
            );
        }

        let resp = req.json(&data).send().await?;

        match resp.status() {
            StatusCode::OK => Ok(resp.json::<HashMap<String, Value>>().await?),
            _ => Err(Box::new(resp.error_for_status().unwrap_err())),
        }
    }

    async fn delete(self, id: u64) -> Result<(), Box<dyn Error>> {
        let baserow = self.baserow.expect("Baserow instance is missing");

        let url = format!(
            "{}/api/database/rows/table/{}/{}/",
            &baserow.configuration.base_url,
            self.id.unwrap(),
            id
        );

        let mut req = baserow.client.delete(url);

        if baserow.configuration.jwt.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("JWT {}", &baserow.configuration.jwt.unwrap()),
            );
        } else if baserow.configuration.database_token.is_some() {
            req = req.header(
                AUTHORIZATION,
                format!("Token {}", &baserow.configuration.database_token.unwrap()),
            );
        }

        let resp = req.send().await?;

        match resp.status() {
            StatusCode::OK => Ok(()),
            _ => Err(Box::new(resp.error_for_status().unwrap_err())),
        }
    }
}