filemaker_lib/
lib.rs

1//!
2//! # Filemaker Library (filemaker-lib)
3//!
4//! This project is a Rust library (`filemaker-lib`) designed to interact with the FileMaker Data API. It provides a simple API to perform key operations against FileMaker databases, such as fetching records, performing searches, updating records, deleting records, and manipulating database sessions.
5//!
6//! ## Features
7//!
8//! - **[Database Interaction](#fetching-databases)**: Fetch the list of available databases.
9//! - **[Authentication](#initialization)**: Securely manage session tokens for interacting with the FileMaker Data API.
10//! - **[Record Management](#record-management)**:
11//!   - [Fetch records](#fetching-records) (paginated or all at once).
12//!   - [Search for records](#searching-records) based on custom queries and sorting criteria.
13//!   - [Add single or multiple records](#adding-records).
14//!   - [Update specific records](#updating-records).
15//!   - [Delete records](#deleting-records) from a database.
16//! - **[Database Layouts](#fetching-available-layouts)**: Retrieve the layouts available in a given database.
17//! - **[Database Clearing](#clearing-the-database)**: Delete all records within a database.
18//! - **[Advanced Querying and Sorting](#searching-records)**: Search with advanced queries and sort results in ascending or descending order.
19//! - **Utility Functions**: Extract field names from records and encode database parameters safely.
20//!
21//! ## Installation
22//!
23//! Add `filemaker-lib` to your project's `Cargo.toml`:
24//!
25//! ```toml
26//! [dependencies]
27//! filemaker-lib = "0.1.0"
28//! ```
29//! or using git
30//!
31//! ```toml
32//! [dependencies]
33//! filemaker-lib = {git = "https://github.com/Drew-Chase/filemaker-lib.git"}
34//! ```
35//!
36//! ## Usage
37//!
38//! ### Initialization
39//!
40//! To create a `Filemaker` instance, you need to pass valid credentials (username and password), the name of the database, and the table you want to work with:
41//!
42//! ```rust
43//! use filemaker_lib::Filemaker;
44//! use anyhow::Result;
45//!
46//! #[tokio::main]
47//! async fn main() -> Result<()> {
48//!   std::env::set_var("FM_URL", "https://fm.example.com/fmi/data/vLatest"); // Replace with actual FileMaker server URL
49//!   let username = "your_username";
50//!   let password = "your_password";
51//!   let database = "your_database";
52//!   let table = "your_table";
53//!
54//!   let filemaker = Filemaker::new(username, password, database, table).await?;
55//!   println!("Filemaker instance created successfully.");
56//!   Ok(())
57//! }
58//! ```
59//!
60//! ### Fetching Records
61//!
62//! Retrieve specific records with pagination:
63//!
64//! ```rust
65//! let records = filemaker.get_records(1, 10).await?;
66//! println!("Fetched Records: {:?}", records);
67//! ```
68//!
69//! Fetch all records at once:
70//!
71//! ```rust
72//! let all_records = filemaker.get_all_records().await?;
73//! println!("All Records: {:?}", all_records);
74//! ```
75//!
76//! ### Adding Records
77//!
78//! #### Adding a Single Record
79//!
80//! To add a single record to your FileMaker database:
81//!
82//! ```rust
83//! use serde_json::Value;
84//! use std::collections::HashMap;
85//!
86//! let mut single_record_data = HashMap::new();
87//! single_record_data.insert("field_name1".to_string(), Value::String("Value 1".to_string()));
88//! single_record_data.insert("field_name2".to_string(), Value::String("Value 2".to_string()));
89//!
90//! let result = filemaker.add_record(single_record_data).await?;
91//! println!("Single record added: {:?}", result);
92//! ```
93//!
94//! #### Adding Multiple Records
95//!
96//! To add multiple records to your FileMaker database:
97//!
98//! ```rust
99//! use serde_json::Value;
100//! use std::collections::HashMap;
101//!
102//! let records = vec![
103//!   {
104//!     let mut record = HashMap::new();
105//!     record.insert("field_name1".to_string(), Value::String("First Record - Value 1".to_string()));
106//!     record.insert("field_name2".to_string(), Value::String("First Record - Value 2".to_string()));
107//!     record
108//!   },
109//!   {
110//!     let mut record = HashMap::new();
111//!     record.insert("field_name1".to_string(), Value::String("Second Record - Value 1".to_string()));
112//!     record.insert("field_name2".to_string(), Value::String("Second Record - Value 2".to_string()));
113//!     record
114//!   },
115//! ];
116//!
117//! for (i, record_data) in records.into_iter().enumerate() {
118//!   match filemaker.add_record(record_data).await {
119//!   Ok(result) => println!("Record {} added successfully: {:?}", i + 1, result),
120//!   Err(e) => eprintln!("Failed to add record {}: {}", i + 1, e),
121//!   }
122//! }
123//! ```
124//!
125//! ### Counting Records
126//!
127//! Count the total number of records available in the table:
128//!
129//! ```rust
130//! let total_records = filemaker.get_number_of_records().await?;
131//! println!("Total Records: {}", total_records);
132//! ```
133//!
134//! ### Searching Records
135//!
136//! Perform a query with search parameters and sorting:
137//!
138//! ```rust
139//! use std::collections::HashMap;
140//!
141//! let mut query = HashMap::new();
142//! query.insert("fieldName".to_string(), "example_value".to_string());
143//!
144//! let sort_fields = vec!["fieldName".to_string()];
145//! let ascending = true;
146//!
147//! let search_results = filemaker.search::<serde_json::Value>(vec![query], sort_fields, ascending).await?;
148//! println!("Search Results: {:?}", search_results);
149//! ```
150//!
151//! ### Updating Records
152//!
153//! Update a record by its ID:
154//!
155//! ```rust
156//! use serde_json::Value;
157//!
158//! let record_id = 123;
159//! let mut field_data = HashMap::new();
160//! field_data.insert("fieldName".to_string(), Value::String("new_value".to_string()));
161//!
162//! let update_result = filemaker.update_record(record_id, field_data).await?;
163//! println!("Update Result: {:?}", update_result);
164//! ```
165//!
166//! ### Deleting Records
167//!
168//! Delete a record by its ID:
169//!
170//! ```rust
171//! let record_id = 123;
172//! filemaker.delete_record(record_id).await?;
173//! println!("Record deleted successfully.");
174//! ```
175//!
176//! ### Fetching Available Layouts
177//!
178//! Retrieve a list of layouts in the specified database:
179//!
180//! ```rust
181//! let layouts = Filemaker::get_layouts("your_username", "your_password", "your_database").await?;
182//! println!("Available Layouts: {:?}", layouts);
183//! ```
184//!
185//! ### Fetching Databases
186//!
187//! Retrieve the list of databases accessible with your credentials:
188//!
189//! ```rust
190//! let databases = Filemaker::get_databases("your_username", "your_password").await?;
191//! println!("Databases: {:?}", databases);
192//! ```
193//!
194//! ### Clearing the Database
195//!
196//! Delete all records from the current database and table:
197//!
198//! ```rust
199//! filemaker.clear_database().await?;
200//! println!("All records cleared successfully.");
201//! ```
202//!
203//! ## Environment Variables
204//!
205//! The library uses the `FM_URL` environment variable to specify the base URL of the FileMaker server. You need to set this variable before using the library:
206//!
207//! ```rust
208//! std::env::set_var("FM_URL", "https://fm.example.com/fmi/data/vLatest");
209//! ```
210//!
211//! Replace `"https://fm.example.com/fmi/data/vLatest"` with the actual URL of your FileMaker server.
212//!
213//! ## Examples
214//!
215//! This library comes with example implementations usable as references:
216//!
217//! 1. **Fetch List of Databases**: [`get_databases`](examples/get_databases.rs)
218//! 2. **Fetch Layouts from a Database**: [`filemaker_layout_fetcher`](examples/filemaker_layout_fetcher.rs)
219//! 3. **Retrieve Records**: [`main_filemaker`](examples/main_filemaker.rs)
220//! 4. **Add Single Record**: [`filemaker_single_record_adder`](examples/filemaker_single_record_adder.rs)
221//! 5. **Add Multiple Records**: [`filemaker_multiple_record_adder`](examples/filemaker_multiple_record_adder.rs)
222//! 6. **Update Database Records**: [`filemaker_record_updater`](examples/filemaker_record_updater.rs)
223//! 7. **Delete Database Records**: [`filemaker_record_deleter`](examples/filemaker_record_deleter.rs)
224//! 8. **Find Records Based on Query**: [`filemaker_search_results_output`](examples/filemaker_search_results_output.rs)
225//!
226//! ## Logging
227//!
228//! The library uses the [`log`](https://docs.rs/log/) crate for logging. To capture and display logs, set up a logging framework such as [`env_logger`](https://docs.rs/env_logger/). Example:
229//!
230//! ```rust
231//! use env_logger;
232//!
233//! fn main() {
234//!   env_logger::init();
235//! }
236//! ```
237//!
238//! ## License
239//!
240//! This library is licensed under the terms of the license detailed in the [`LICENSE`](LICENSE) file.
241//!
242//! ---
243//!
244//! For more information, please refer to the [repository documentation](https://github.com/Drew-Chase/filemaker-lib). Contributions are welcome!
245
246
247use anyhow::Result;
248use base64::Engine;
249use log::*;
250use reqwest::{Client, Method};
251use serde_json::{json, Value};
252use std::collections::HashMap;
253use std::sync::Arc;
254use tokio::sync::Mutex;
255
256/// Represents a connection to a Filemaker database with authentication and query capabilities.
257///
258/// This struct manages the connection details and authentication token needed
259/// to interact with a Filemaker database through its Data API.
260#[derive(Clone)]
261pub struct Filemaker {
262    // Name of the database to connect to
263    database: String,
264    // Authentication token stored in thread-safe container that can be updated
265    // Option is used since the token might not be available initially
266    token: Arc<Mutex<Option<String>>>,
267    // Name of the table/layout to operate on
268    table: String,
269    // HTTP client for making API requests
270    client: Client,
271}
272impl Filemaker {
273    /// Creates a new `Filemaker` instance.
274    ///
275    /// Initializes a connection to a FileMaker database with the provided credentials.
276    /// This function performs authentication and sets up the HTTP client with appropriate configuration.
277    ///
278    /// # Arguments
279    /// * `username` - The username for FileMaker authentication
280    /// * `password` - The password for FileMaker authentication
281    /// * `database` - The name of the FileMaker database to connect to
282    /// * `table` - The name of the table/layout to operate on
283    ///
284    /// # Returns
285    /// * `Result<Self>` - A new Filemaker instance or an error
286    pub async fn new(username: &str, password: &str, database: &str, table: &str) -> Result<Self> {
287        // URL-encode database and table names to handle spaces and special characters
288        let encoded_database = Self::encode_parameter(database);
289        let encoded_table = Self::encode_parameter(table);
290
291        // Create an HTTP client that accepts invalid SSL certificates (for development)
292        let client = Client::builder()
293            .danger_accept_invalid_certs(true) // Disable SSL verification
294            .build()
295            .map_err(|e| {
296                error!("Failed to build client: {}", e);
297                anyhow::anyhow!(e)
298            })?;
299
300        // Authenticate with FileMaker and obtain a session token
301        let token = Self::get_session_token(&client, database, username, password).await?;
302        info!("Filemaker instance created successfully");
303
304        // Return the initialized Filemaker instance
305        Ok(Self {
306            database: encoded_database,
307            table: encoded_table,
308            token: Arc::new(Mutex::new(Some(token))), // Wrap token in thread-safe container
309            client,
310        })
311    }
312
313    /// Gets a session token from the FileMaker Data API.
314    ///
315    /// Performs authentication against the FileMaker Data API and retrieves a session token
316    /// that can be used for subsequent API requests.
317    ///
318    /// # Arguments
319    /// * `client` - The HTTP client to use for the request
320    /// * `database` - The name of the FileMaker database to authenticate against
321    /// * `username` - The username for FileMaker authentication
322    /// * `password` - The password for FileMaker authentication
323    ///
324    /// # Returns
325    /// * `Result<String>` - The session token or an error
326    async fn get_session_token(
327        client: &Client,
328        database: &str,
329        username: &str,
330        password: &str,
331    ) -> Result<String> {
332        // URL-encode the database name to handle spaces and special characters
333        let database = Self::encode_parameter(database);
334
335        // Construct the URL for the sessions endpoint
336        let url = format!(
337            "{}/databases/{}/sessions",
338            std::env::var("FM_URL").unwrap_or_default().as_str(),
339            database
340        );
341
342        // Create a Base64-encoded Basic authentication header
343        let auth_header = format!(
344            "Basic {}",
345            base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", username, password))
346        );
347
348        debug!("Requesting session token from URL: {}", url);
349
350        // Send the authentication request to FileMaker
351        let response = client
352            .post(&url)
353            .header("Authorization", auth_header)
354            .header("Content-Type", "application/json")
355            .body("{}") // Empty JSON body for session creation
356            .send()
357            .await
358            .map_err(|e| {
359                error!("Failed to send request for session token: {}", e);
360                anyhow::anyhow!(e)
361            })?;
362
363        // Parse the JSON response
364        let json: Value = response.json().await.map_err(|e| {
365            error!("Failed to parse session token response: {}", e);
366            anyhow::anyhow!(e)
367        })?;
368
369        // Extract the token from the response JSON structure
370        if let Some(token) = json
371            .get("response")
372            .and_then(|r| r.get("token"))
373            .and_then(|t| t.as_str())
374        {
375            info!("Session token retrieved successfully");
376            Ok(token.to_string())
377        } else {
378            error!(
379                "Failed to get token from FileMaker API response: {:?}",
380                json
381            );
382            Err(anyhow::anyhow!("Failed to get token from FileMaker API"))
383        }
384    }
385
386    /// Sends an authenticated HTTP request to the FileMaker Data API.
387    ///
388    /// This method handles adding the authentication token to requests and processing
389    /// the response from the FileMaker Data API.
390    ///
391    /// # Arguments
392    /// * `url` - The endpoint URL to send the request to
393    /// * `method` - The HTTP method to use (GET, POST, etc.)
394    /// * `body` - Optional JSON body to include with the request
395    ///
396    /// # Returns
397    /// * `Result<Value>` - The parsed JSON response or an error
398    async fn authenticated_request(
399        &self,
400        url: &str,
401        method: Method,
402        body: Option<Value>,
403    ) -> Result<Value> {
404        // Retrieve the session token from the shared state
405        let token = self.token.lock().await.clone();
406        if token.is_none() {
407            error!("No session token found");
408            return Err(anyhow::anyhow!("No session token found"));
409        }
410
411        // Create Bearer authentication header with the token
412        let auth_header = format!("Bearer {}", token.unwrap());
413
414        // Start building the request with appropriate headers
415        let mut request = self
416            .client
417            .request(method, url)
418            .header("Authorization", auth_header)
419            .header("Content-Type", "application/json");
420
421        // Add the JSON body to the request if provided
422        if let Some(body_content) = body {
423            let json_body = serde_json::to_string(&body_content).map_err(|e| {
424                error!("Failed to serialize request body: {}", e);
425                anyhow::anyhow!(e)
426            })?;
427            debug!("Request body: {}", json_body);
428            request = request.body(json_body);
429        }
430
431        debug!("Sending authenticated request to URL: {}", url);
432
433        // Send the request and handle any network errors
434        let response = request.send().await.map_err(|e| {
435            error!("Failed to send authenticated request: {}", e);
436            anyhow::anyhow!(e)
437        })?;
438
439        // Parse the response JSON and handle parsing errors
440        let json: Value = response.json().await.map_err(|e| {
441            error!("Failed to parse authenticated request response: {}", e);
442            anyhow::anyhow!(e)
443        })?;
444
445        info!("Authenticated request to {} completed successfully", url);
446        Ok(json)
447    }
448
449    /// Retrieves a specified range of records from the database.
450    ///
451    /// # Arguments
452    /// * `start` - The starting position (offset) for record retrieval
453    /// * `limit` - The maximum number of records to retrieve
454    ///
455    /// # Returns
456    /// * `Result<Vec<Value>>` - A vector of record objects on success, or an error
457    pub async fn get_records<T>(&self, start: T, limit: T) -> Result<Vec<Value>>
458    where
459        T: Sized + Clone + std::fmt::Display + std::str::FromStr + TryFrom<usize>,
460    {
461        // Construct the URL for the FileMaker Data API records endpoint
462        let url = format!(
463            "{}/databases/{}/layouts/{}/records?_offset={}&_limit={}",
464            std::env::var("FM_URL").unwrap_or_default().as_str(),
465            self.database,
466            self.table,
467            start,
468            limit
469        );
470        debug!("Fetching records from URL: {}", url);
471
472        // Send authenticated request to the API endpoint
473        let response = self.authenticated_request(&url, Method::GET, None).await?;
474
475        // Extract the records data from the response if available
476        if let Some(data) = response.get("response").and_then(|r| r.get("data")) {
477            info!("Successfully retrieved records from database");
478            Ok(data.as_array().unwrap_or(&vec![]).clone())
479        } else {
480            // Log and return error if the expected data structure is not found
481            error!("Failed to retrieve records from response: {:?}", response);
482            Err(anyhow::anyhow!("Failed to retrieve records"))
483        }
484    }
485
486    /// Retrieves all records from the database in a single query.
487    ///
488    /// This method first determines the total record count and then
489    /// fetches all records in a single request.
490    ///
491    /// # Returns
492    /// * `Result<Vec<Value>>` - A vector containing all records on success, or an error
493    pub async fn get_all_records(&self) -> Result<Vec<Value>> {
494        // First get the total number of records in the database
495        let total_count = self.get_number_of_records().await?;
496        debug!("Total records to fetch: {}", total_count);
497
498        // Retrieve all records in a single request
499        self.get_records(1, total_count).await
500    }
501
502    /// Retrieves the total number of records in the database table.
503    ///
504    /// # Returns
505    /// * `Result<u64>` - The total record count on success, or an error
506    pub async fn get_number_of_records(&self) -> Result<u64> {
507        // Construct the URL for the FileMaker Data API records endpoint
508        let url = format!(
509            "{}/databases/{}/layouts/{}/records",
510            std::env::var("FM_URL").unwrap_or_default().as_str(),
511            self.database,
512            self.table
513        );
514        debug!("Fetching total number of records from URL: {}", url);
515
516        // Send authenticated request to the API endpoint
517        let response = self.authenticated_request(&url, Method::GET, None).await?;
518
519        // Extract the total record count from the response if available
520        if let Some(total_count) = response
521            .get("response")
522            .and_then(|r| r.get("dataInfo"))
523            .and_then(|d| d.get("totalRecordCount"))
524            .and_then(|c| c.as_u64())
525        {
526            info!("Total record count retrieved successfully: {}", total_count);
527            Ok(total_count)
528        } else {
529            // Log and return error if the expected data structure is not found
530            error!(
531                "Failed to retrieve total record count from response: {:?}",
532                response
533            );
534            Err(anyhow::anyhow!("Failed to retrieve total record count"))
535        }
536    }
537
538    /// Searches the database for records matching specified criteria.
539    ///
540    /// # Arguments
541    /// * `query` - Vector of field-value pairs to search for
542    /// * `sort` - Vector of field names to sort by
543    /// * `ascending` - Whether to sort in ascending (true) or descending (false) order
544    ///
545    /// # Returns
546    /// * `Result<Vec<T>>` - A vector of matching records as the specified type on success, or an error
547    pub async fn search<T>(
548        &self,
549        query: Vec<HashMap<String, String>>,
550        sort: Vec<String>,
551        ascending: bool,
552    ) -> Result<Vec<T>>
553        where
554            T: serde::de::DeserializeOwned + Default,
555    {
556        // Construct the URL for the FileMaker Data API find endpoint
557        let url = format!(
558            "{}/databases/{}/layouts/{}/_find",
559            std::env::var("FM_URL").unwrap_or_default().as_str(),
560            self.database,
561            self.table
562        );
563
564        // Determine sort order based on ascending parameter
565        let sort_order = if ascending { "ascend" } else { "descend" };
566
567        // Transform the sort fields into the format expected by FileMaker API
568        let sort_map: Vec<_> = sort
569            .into_iter()
570            .map(|s| {
571                let mut map = HashMap::new();
572                map.insert("fieldName".to_string(), s);
573                map.insert("sortOrder".to_string(), sort_order.to_string());
574                map
575            })
576            .collect();
577
578        // Construct the request body with query and sort parameters
579        let body: HashMap<String, Value> = HashMap::from([
580            ("query".to_string(), serde_json::to_value(query)?),
581            ("sort".to_string(), serde_json::to_value(sort_map)?),
582        ]);
583        debug!("Executing search query with URL: {}. Body: {:?}", url, body);
584
585        // Send authenticated POST request to the API endpoint
586        let response = self
587            .authenticated_request(&url, Method::POST, Some(serde_json::to_value(body)?))
588            .await?;
589
590        // Extract the search results and deserialize into the specified type
591        if let Some(data) = response.get("response").and_then(|r| r.get("data")) {
592            let deserialized: Vec<T> = serde_json::from_value(data.clone()).map_err(|e| {
593                error!("Failed to deserialize search results: {}", e);
594                anyhow::anyhow!(e)
595            })?;
596            info!("Search query executed successfully");
597            Ok(deserialized)
598        } else {
599            // Log and return error if the expected data structure is not found
600            error!(
601            "Failed to retrieve search results from response: {:?}",
602            response
603        );
604            Err(anyhow::anyhow!("Failed to retrieve search results"))
605        }
606    }
607
608    /// Adds a record to the database.
609    ///
610    /// # Parameters
611    /// - `field_data`: A `HashMap` representing the field data for the new record.
612    ///
613    /// # Returns
614    /// A `Result` containing the added record as a `Value` on success, or an error.
615    pub async fn add_record(
616        &self,
617        field_data: HashMap<String, Value>,
618    ) -> Result<HashMap<String, Value>> {
619        // Define the URL for the FileMaker Data API endpoint
620        let url = format!(
621            "{}/databases/{}/layouts/{}/records",
622            std::env::var("FM_URL").unwrap_or_default().as_str(),
623            self.database,
624            self.table
625        );
626
627        // Prepare the request body
628        let field_data_map: serde_json::Map<String, Value> = field_data.into_iter().collect();
629        let body = HashMap::from([("fieldData".to_string(), Value::Object(field_data_map))]);
630
631        debug!("Adding a new record. URL: {}. Body: {:?}", url, body);
632
633        // Make the API call
634        let response = self
635            .authenticated_request(&url, Method::POST, Some(serde_json::to_value(body)?))
636            .await?;
637
638        if let Some(record_id) = response
639            .get("response")
640            .and_then(|r| r.get("recordId"))
641            .and_then(|id| id.as_str())
642        {
643            if let Ok(record_id) = record_id.parse::<u64>() {
644                debug!("Record added successfully. Record ID: {}", record_id);
645                let added_record = self.get_record_by_id(record_id).await?;
646                Ok(HashMap::from([
647                    ("success".to_string(), Value::Bool(true)),
648                    ("result".to_string(), added_record),
649                ]))
650            } else {
651                error!("Failed to parse record id {} - {:?}", record_id, response);
652                Ok(HashMap::from([
653                    ("success".to_string(), Value::Bool(false)),
654                    ("result".to_string(), response),
655                ]))
656            }
657        } else {
658            error!("Failed to add the record: {:?}", response);
659            Ok(HashMap::from([
660                ("success".to_string(), Value::Bool(false)),
661                ("result".to_string(), response),
662            ]))
663        }
664    }
665
666    /// Updates a record in the database using the FileMaker Data API.
667    ///
668    /// # Arguments
669    /// * `id` - The unique identifier of the record to update
670    /// * `field_data` - A hashmap containing the field names and their new values
671    ///
672    /// # Returns
673    /// * `Result<Value>` - The server response as a JSON value or an error
674    ///
675    /// # Type Parameters
676    /// * `T` - A type that can be used as a record identifier and meets various trait requirements
677    pub async fn update_record<T>(&self, id: T, field_data: HashMap<String, Value>) -> Result<Value>
678    where
679        T: Sized + Clone + std::fmt::Display + std::str::FromStr + TryFrom<usize>,
680    {
681        // Construct the API endpoint URL for updating a specific record
682        let url = format!(
683            "{}/databases/{}/layouts/{}/records/{}",
684            std::env::var("FM_URL").unwrap_or_default().as_str(),
685            self.database,
686            self.table,
687            id
688        );
689
690        // Convert the field data hashmap to the format expected by FileMaker Data API
691        let field_data_map: serde_json::Map<String, Value> = field_data.into_iter().collect();
692        // Create the request body with fieldData property
693        let body = HashMap::from([("fieldData".to_string(), Value::Object(field_data_map))]);
694
695        debug!("Updating record ID: {}. URL: {}. Body: {:?}", id, url, body);
696
697        // Send the PATCH request to update the record
698        let response = self
699            .authenticated_request(&url, Method::PATCH, Some(serde_json::to_value(body)?))
700            .await?;
701
702        info!("Record ID: {} updated successfully", id);
703        Ok(response)
704    }
705
706    /// Retrieves the list of databases accessible to the specified user.
707    ///
708    /// # Arguments
709    /// * `username` - The FileMaker username for authentication
710    /// * `password` - The FileMaker password for authentication
711    ///
712    /// # Returns
713    /// * `Result<Vec<String>>` - A list of accessible database names or an error
714    pub async fn get_databases(username: &str, password: &str) -> Result<Vec<String>> {
715        // Construct the API endpoint URL for retrieving databases
716        let url = format!(
717            "{}/databases",
718            std::env::var("FM_URL").unwrap_or_default().as_str()
719        );
720
721        // Create Base64 encoded Basic auth header from username and password
722        let auth_header = format!(
723            "Basic {}",
724            base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", username, password))
725        );
726
727        debug!("Fetching list of databases from URL: {}", url);
728
729        // Initialize HTTP client
730        let client = Client::new();
731
732        // Send request to get list of databases with authentication
733        let response = client
734            .get(&url)
735            .header("Authorization", auth_header)
736            .header("Content-Type", "application/json")
737            .send()
738            .await
739            .map_err(|e| {
740                error!("Failed to send request for databases: {}", e);
741                anyhow::anyhow!(e)
742            })?
743            .json::<Value>()
744            .await
745            .map_err(|e| {
746                error!("Failed to parse database list response: {}", e);
747                anyhow::anyhow!(e)
748            })?;
749
750        // Extract database names from the response JSON
751        if let Some(databases) = response
752            .get("response")
753            .and_then(|r| r.get("databases"))
754            .and_then(|d| d.as_array())
755        {
756            // Extract the name field from each database object
757            let database_names = databases
758                .iter()
759                .filter_map(|db| {
760                    db.get("name")
761                        .and_then(|n| n.as_str())
762                        .map(|s| s.to_string())
763                })
764                .collect();
765
766            info!("Database list retrieved successfully");
767            Ok(database_names)
768        } else {
769            // Handle case where response doesn't contain expected data structure
770            error!("Failed to retrieve databases from response: {:?}", response);
771            Err(anyhow::anyhow!("Failed to retrieve databases"))
772        }
773    }
774
775    /// Retrieves the list of layouts for the specified database using the provided credentials.
776    ///
777    /// # Arguments
778    /// * `username` - The FileMaker username for authentication
779    /// * `password` - The FileMaker password for authentication
780    /// * `database` - The name of the database to get layouts from
781    ///
782    /// # Returns
783    /// * `Result<Vec<String>>` - A list of layout names or an error
784    pub async fn get_layouts(
785        username: &str,
786        password: &str,
787        database: &str,
788    ) -> Result<Vec<String>> {
789        // URL encode the database name and construct the API endpoint URL
790        let encoded_database = Self::encode_parameter(database);
791        let url = format!(
792            "{}/databases/{}/layouts",
793            std::env::var("FM_URL").unwrap_or_default().as_str(),
794            encoded_database
795        );
796
797        debug!("Fetching layouts from URL: {}", url);
798
799        // Create HTTP client and get session token for authentication
800        let client = Client::new();
801        let token = Self::get_session_token(&client, database, username, password)
802            .await
803            .map_err(|e| {
804                error!("Failed to get session token for layouts: {}", e);
805                anyhow::anyhow!(e)
806            })?;
807
808        // Create Bearer auth header from the session token
809        let auth_header = format!("Bearer {}", token);
810
811        // Send request to get list of layouts with token authentication
812        let response = client
813            .get(&url)
814            .header("Authorization", auth_header)
815            .header("Content-Type", "application/json")
816            .send()
817            .await
818            .map_err(|e| {
819                error!("Failed to send request to retrieve layouts: {}", e);
820                anyhow::anyhow!(e)
821            })?
822            .json::<Value>()
823            .await
824            .map_err(|e| {
825                error!("Failed to parse response for layouts: {}", e);
826                anyhow::anyhow!(e)
827            })?;
828
829        // Extract layout names from the response JSON
830        if let Some(layouts) = response
831            .get("response")
832            .and_then(|r| r.get("layouts"))
833            .and_then(|l| l.as_array())
834        {
835            // Extract the name field from each layout object
836            let layout_names = layouts
837                .iter()
838                .filter_map(|layout| {
839                    layout
840                        .get("name")
841                        .and_then(|n| n.as_str())
842                        .map(|s| s.to_string())
843                })
844                .collect();
845
846            info!("Successfully retrieved layouts");
847            Ok(layout_names)
848        } else {
849            // Handle case where response doesn't contain expected data structure
850            error!("Failed to retrieve layouts from response: {:?}", response);
851            Err(anyhow::anyhow!("Failed to retrieve layouts"))
852        }
853    }
854
855    /// Gets a record from the database by its ID.
856    ///
857    /// # Arguments
858    /// * `id` - The ID of the record to get.
859    ///
860    /// # Returns
861    /// A JSON object representing the record.
862    pub async fn get_record_by_id<T>(&self, id: T) -> Result<Value>
863    where
864        T: Sized + Clone + std::fmt::Display + std::str::FromStr + TryFrom<usize>,
865    {
866        let url = format!(
867            "{}/databases/{}/layouts/{}/records/{}",
868            std::env::var("FM_URL").unwrap_or_default().as_str(),
869            self.database,
870            self.table,
871            id
872        );
873
874        debug!("Fetching record with ID: {} from URL: {}", id, url);
875
876        let response = self
877            .authenticated_request(&url, Method::GET, None)
878            .await
879            .map_err(|e| {
880                error!("Failed to get record ID {}: {}", id, e);
881                anyhow::anyhow!(e)
882            })?;
883
884        if let Some(data) = response.get("response").and_then(|r| r.get("data")) {
885            if let Some(record) = data.as_array().and_then(|arr| arr.first()) {
886                info!("Record ID {} retrieved successfully", id);
887                Ok(record.clone())
888            } else {
889                error!("No record found for ID {}", id);
890                Err(anyhow::anyhow!("No record found"))
891            }
892        } else {
893            error!("Failed to get record from response: {:?}", response);
894            Err(anyhow::anyhow!("Failed to get record"))
895        }
896    }
897
898    /// Deletes a record from the database by its ID.
899    ///
900    /// # Arguments
901    /// * `id` - The ID of the record to delete.
902    ///
903    /// # Returns
904    /// A result indicating the deletion was successful or an error message.
905    pub async fn delete_record<T>(&self, id: T) -> Result<Value>
906    where
907        T: Sized + Clone + std::fmt::Display + std::str::FromStr + TryFrom<usize>,
908    {
909        let url = format!(
910            "{}/databases/{}/layouts/{}/records/{}",
911            std::env::var("FM_URL").unwrap_or_default().as_str(),
912            self.database,
913            self.table,
914            id
915        );
916
917        debug!("Deleting record with ID: {} at URL: {}", id, url);
918
919        let response = self
920            .authenticated_request(&url, Method::DELETE, None)
921            .await
922            .map_err(|e| {
923                error!("Failed to delete record ID {}: {}", id, e);
924                anyhow::anyhow!(e)
925            })?;
926
927        if response.is_object() {
928            info!("Record ID {} deleted successfully", id);
929            Ok(json!({"success": true}))
930        } else {
931            error!("Failed to delete record ID {}", id);
932            Err(anyhow::anyhow!("Failed to delete record"))
933        }
934    }
935
936    /// Deletes the specified database.
937    ///
938    /// # Arguments
939    /// * `database` - The name of the database to delete.
940    /// * `username` - The username for authentication.
941    /// * `password` - The password for authentication.
942    pub async fn delete_database(database: &str, username: &str, password: &str) -> Result<()> {
943        let encoded_database = Self::encode_parameter(database);
944        let url = format!(
945            "{}/databases/{}",
946            std::env::var("FM_URL").unwrap_or_default().as_str(),
947            encoded_database
948        );
949
950        debug!("Deleting database: {}", database);
951
952        let client = Client::new();
953        let token = Self::get_session_token(&client, database, username, password)
954            .await
955            .map_err(|e| {
956                error!("Failed to get session token for database deletion: {}", e);
957                anyhow::anyhow!(e)
958            })?;
959        let auth_header = format!("Bearer {}", token);
960
961        client
962            .delete(&url)
963            .header("Authorization", auth_header)
964            .header("Content-Type", "application/json")
965            .send()
966            .await
967            .map_err(|e| {
968                error!("Failed to delete database {}: {}", database, e);
969                anyhow::anyhow!(e)
970            })?;
971
972        info!("Database {} deleted successfully", database);
973        Ok(())
974    }
975
976    /// Deletes all records from the current database.
977    ///
978    /// This function retrieves and systematically removes all records from the database.
979    /// It first checks if there are any records to delete, then proceeds with deletion
980    /// if records exist.
981    ///
982    /// # Returns
983    /// * `Result<()>` - Ok(()) if all records were successfully deleted, or an error
984    ///
985    /// # Errors
986    /// * Returns error if unable to retrieve records
987    /// * Returns error if record ID parsing fails
988    /// * Returns error if record deletion fails
989    pub async fn clear_database(&self) -> Result<()> {
990        debug!("Clearing all records from the database");
991        // Get the total count of records in the database
992        let number_of_records = self.get_number_of_records().await?;
993
994        // Check if there are any records to delete
995        if number_of_records == 0 {
996            warn!("No records found in the database. Nothing to clear");
997            return Ok(());
998        }
999
1000        // Retrieve all records that need to be deleted
1001        // The number_of_records value is used as limit to fetch all records at once
1002        let records = self.get_records(1, number_of_records).await.map_err(|e| {
1003            error!("Failed to retrieve records for clearing database: {}", e);
1004            anyhow::anyhow!(e)
1005        })?;
1006
1007        // Iterate through each record and delete it individually
1008        for record in records {
1009            // Extract the record ID from the record data
1010            if let Some(id) = record.get("recordId").and_then(|id| id.as_str()) {
1011                // The record ID is usually marked as a string even though it's a u64,
1012                // so we need to parse it to the correct type
1013                if let Ok(id) = id.parse::<u64>() {
1014                    debug!("Deleting record ID: {}", id);
1015                    // Attempt to delete the record and handle any errors
1016                    if let Err(e) = self.delete_record(id).await {
1017                        error!("Failed to delete record ID {}: {}", id, e);
1018                        return Err(anyhow::anyhow!(e));
1019                    }
1020                } else {
1021                    // Handle case where ID exists but cannot be parsed as u64
1022                    error!("Failed to parse record ID {} as u64", id);
1023                    return Err(anyhow::anyhow!("Failed to parse record ID as u64"));
1024                }
1025            } else {
1026                // Handle case where record doesn't contain an ID field
1027                error!("Record ID not found in record: {:?}", record);
1028                return Err(anyhow::anyhow!(
1029                    "Record ID not found in record: {:?}",
1030                    record
1031                ));
1032            }
1033        }
1034
1035        info!("All records cleared from the database");
1036        Ok(())
1037    }
1038    /// Returns the names of fields in the given record excluding the ones starting with 'g_' (global fields)
1039    ///
1040    /// # Arguments
1041    /// * `record` - An example record with 'fieldData' element containing field names as keys.
1042    ///
1043    /// # Returns
1044    /// An array of field names.
1045    pub fn get_row_names_by_example(record: &Value) -> Vec<String> {
1046        let mut fields = Vec::new();
1047        if let Some(field_data) = record.get("fieldData").and_then(|fd| fd.as_object()) {
1048            for field in field_data.keys() {
1049                if !field.starts_with("g_") {
1050                    fields.push(field.clone());
1051                }
1052            }
1053        }
1054        info!("Extracted row names: {:?}", fields);
1055        fields
1056    }
1057
1058    /// Gets the field names for the first record in the database.
1059    ///
1060    /// This function retrieves a single record from the database and extracts
1061    /// field names from it. If no records exist, an empty vector is returned.
1062    ///
1063    /// # Returns
1064    /// * `Result<Vec<String>>` - A vector of field names on success, or an error
1065    pub async fn get_row_names(&self) -> Result<Vec<String>> {
1066        debug!("Attempting to fetch field names for the first record");
1067
1068        // Fetch just the first record to use as a template
1069        let records = self.get_records(1, 1).await?;
1070
1071        if let Some(first_record) = records.first() {
1072            info!("Successfully fetched field names for the first record");
1073            // Extract field names from the first record using the helper method
1074            return Ok(Self::get_row_names_by_example(first_record));
1075        }
1076
1077        // Handle the case where no records exist in the database
1078        warn!("No records found while fetching field names");
1079        Ok(vec![])
1080    }
1081
1082    /// Searches the database for records matching the specified query.
1083    ///
1084    /// # Arguments
1085    /// * `fields` - The query fields.
1086    /// * `sort` - The sort order.
1087    /// * `ascending` - Whether to sort in ascending order.
1088    ///
1089    /// # Returns
1090    /// A vector of matching records.
1091    pub async fn advanced_search(
1092        &self,
1093        fields: HashMap<String, Value>,
1094        sort: Vec<String>,
1095        ascending: bool,
1096    ) -> Result<Vec<Value>> {
1097        let url = format!(
1098            "{}/databases/{}/layouts/{}/_find",
1099            std::env::var("FM_URL").unwrap_or_default().as_str(),
1100            self.database,
1101            self.table
1102        );
1103
1104        debug!(
1105            "Preparing advanced search with fields: {:?}, sort: {:?}, ascending: {}",
1106            fields, sort, ascending
1107        );
1108
1109        let mut content = serde_json::Map::new();
1110        content.insert(
1111            "query".to_string(),
1112            Value::Array(fields.into_iter().map(|(k, v)| json!({ k: v })).collect()),
1113        );
1114
1115        if !sort.is_empty() {
1116            let sort_array: Vec<Value> = sort
1117                .into_iter()
1118                .map(|s| {
1119                    json!({
1120                        "fieldName": s,
1121                        "sortOrder": if ascending { "ascend" } else { "descend" }
1122                    })
1123                })
1124                .collect();
1125            content.insert("sort".to_string(), Value::Array(sort_array));
1126        }
1127
1128        debug!(
1129            "Sending authenticated request to URL: {} with content: {:?}",
1130            url, content
1131        );
1132
1133        let response = self
1134            .authenticated_request(&url, Method::POST, Some(Value::Object(content)))
1135            .await?;
1136
1137        if let Some(data) = response
1138            .get("response")
1139            .and_then(|r| r.get("data"))
1140            .and_then(|d| d.as_array())
1141        {
1142            info!(
1143                "Advanced search completed successfully, retrieved {} records",
1144                data.len()
1145            );
1146            Ok(data.clone())
1147        } else {
1148            error!("Failed to retrieve advanced search results: {:?}", response);
1149            Err(anyhow::anyhow!(
1150                "Failed to retrieve advanced search results"
1151            ))
1152        }
1153    }
1154
1155    /// Encodes a parameter by replacing spaces with `%20`.
1156    ///
1157    /// This function takes a string parameter and replaces all spaces with URL-encoded
1158    /// representation (%20), which is useful for preparing strings to be included in URLs.
1159    ///
1160    /// # Arguments
1161    ///
1162    /// * `parameter` - The string to be encoded
1163    ///
1164    /// # Returns
1165    ///
1166    /// A new String with all spaces replaced by %20
1167    fn encode_parameter(parameter: &str) -> String {
1168        // Replace all spaces with %20 URL encoding
1169        let encoded = parameter.replace(" ", "%20");
1170
1171        // Log the encoding operation at debug level
1172        debug!("Encoded parameter '{}' to '{}'", parameter, encoded);
1173
1174        // Return the encoded string
1175        encoded
1176    }
1177}