vtiger_client/client.rs
1use csv::{Writer, WriterBuilder};
2use futures::stream::{self, StreamExt};
3use indexmap::IndexMap;
4use reqwest::{self, Response};
5use std::collections::HashMap;
6use std::{fs::File, io::Write};
7use tokio::sync::mpsc;
8
9use crate::types::{ExportFormat, VtigerQueryResponse, VtigerResponse};
10/// The base endpoint path for the Vtiger REST API.
11///
12/// This path is appended to the Vtiger instance URL to form the complete
13/// API endpoint. All REST API operations use this base path.
14///
15/// # Example
16///
17/// With a Vtiger instance at `https://example.vtiger.com/`, the full
18/// API URL would be: `https://example.vtiger.com/restapi/v1/vtiger/default`
19const LINK_ENDPOINT: &str = "restapi/v1/vtiger/default";
20
21/// Client for interacting with the Vtiger REST API.
22///
23/// This struct provides a high-level interface for making authenticated requests
24/// to a Vtiger CRM instance. It handles authentication, request formatting, and
25/// response parsing automatically.
26///
27/// # Examples
28///
29/// ```no_run
30///
31/// # #[tokio::main]
32/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
33///
34/// use vtiger_client::Vtiger;
35///
36/// let vtiger = Vtiger::new(
37/// "https://your-instance.vtiger.com",
38/// "your_username",
39/// "your_access_key"
40/// );
41///
42/// // Query records
43/// let response = vtiger.query("SELECT * FROM Leads LIMIT 10").await?;
44/// Ok(())
45/// }
46/// ```
47///
48/// # Authentication
49///
50/// Authentication uses the Vtiger username and access key. The access key can be
51/// found in your Vtiger user preferences under "My Preferences" > "Security".
52#[derive(Debug)]
53pub struct Vtiger {
54 /// The base URL of the Vtiger instance
55 url: String,
56 /// Username for API authentication
57 username: String,
58 /// Access key for API authentication (found in user preferences)
59 access_key: String,
60 /// HTTP client for making requests
61 client: reqwest::Client,
62}
63
64impl Vtiger {
65 /// Creates a new Vtiger API client.
66 ///
67 /// # Arguments
68 ///
69 /// * `url` - The base URL of your Vtiger instance (e.g., `https://your-instance.vtiger.com`)
70 /// * `username` - Your Vtiger username
71 /// * `access_key` - Your Vtiger access key (found in My Preferences > Security)
72 ///
73 /// # Examples
74 ///
75 /// ```no_run
76 /// use vtiger_client::Vtiger;
77 ///
78 /// let vtiger = Vtiger::new(
79 /// "https://demo.vtiger.com",
80 /// "admin",
81 /// "your_access_key_here"
82 /// );
83 /// ```
84 pub fn new(url: &str, username: &str, access_key: &str) -> Self {
85 Vtiger {
86 url: url.to_string(),
87 username: username.to_string(),
88 access_key: access_key.to_string(),
89 client: reqwest::Client::new(),
90 }
91 }
92
93 /// Performs an authenticated GET request to the Vtiger API.
94 ///
95 /// This is an internal method that handles authentication and common headers
96 /// for all GET operations. The URL is constructed by combining the base URL,
97 /// the API endpoint path, and the provided endpoint.
98 ///
99 /// # Arguments
100 ///
101 /// * `endpoint` - The specific API endpoint path (e.g., "/query")
102 /// * `query` - Query parameters as key-value pairs
103 ///
104 /// # Returns
105 ///
106 /// Returns a `Result` containing the HTTP response or a request error.
107 async fn get(
108 &self,
109 endpoint: &str,
110 query: &[(&str, &str)],
111 ) -> Result<Response, reqwest::Error> {
112 let url = format!("{}{}{}", self.url, LINK_ENDPOINT, endpoint);
113 let mut request = self.client.get(&url);
114 if !query.is_empty() {
115 request = request.query(query);
116 }
117 request
118 .basic_auth(&self.username, Some(&self.access_key))
119 .header("Content-Type", "application/json")
120 .header("Accept", "application/json")
121 .send()
122 .await
123 }
124
125 /// Performs an authenticated POST request to the Vtiger API.
126 ///
127 /// This is an internal method that handles authentication and common headers
128 /// for all POST operations. The URL is constructed by combining the base URL,
129 /// the API endpoint path, and the provided endpoint.
130 ///
131 /// # Arguments
132 ///
133 /// * `endpoint` - The specific API endpoint path (e.g., "/create")
134 /// * `query` - Query parameters as key-value pairs
135 ///
136 /// # Returns
137 ///
138 /// Returns a `Result` containing the HTTP response or a request error.
139 async fn post(
140 &self,
141 endpoint: &str,
142 query: &[(&str, &str)],
143 ) -> Result<Response, reqwest::Error> {
144 let url = format!("{}{}{}", self.url, LINK_ENDPOINT, endpoint);
145 let mut request = self.client.post(&url);
146 if !query.is_empty() {
147 request = request.query(query);
148 }
149 request
150 .basic_auth(&self.username, Some(&self.access_key))
151 .header("Content-Type", "application/json")
152 .header("Accept", "application/json")
153 .send()
154 .await
155 }
156
157 /// Retrieves information about the currently authenticated user.
158 ///
159 /// This method calls the `/me` endpoint to get details about the user account
160 /// associated with the provided credentials. It's useful for verifying authentication
161 /// and retrieving user-specific information.
162 ///
163 /// # Returns
164 ///
165 /// Returns a `Result` containing a [`VtigerResponse`] with user information on success,
166 /// or a `reqwest::Error` if the request fails.
167 ///
168 /// # Examples
169 ///
170 /// ```no_run
171 /// use vtiger_client::Vtiger;
172 ///
173 /// #[tokio::main]
174 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
175 /// let vtiger = Vtiger::new(
176 /// "https://demo.vtiger.com",
177 /// "admin",
178 /// "your_access_key",
179 /// );
180 ///
181 /// let user_info = vtiger.me().await?;
182 /// if user_info.success {
183 /// println!("Authenticated as: {:?}", user_info.result);
184 /// } else {
185 /// eprintln!("Authentication failed: {:?}", user_info.error);
186 /// }
187 /// Ok(())
188 /// }
189 /// ```
190 ///
191 /// # Errors
192 ///
193 /// This method will return an error if:
194 /// - The network request fails
195 /// - The response cannot be parsed as JSON
196 /// - The server returns an invalid response format
197 pub async fn me(&self) -> Result<VtigerResponse, reqwest::Error> {
198 let response = self.get("/me", &[]).await?;
199 let vtiger_response = response.json::<VtigerResponse>().await?;
200 Ok(vtiger_response)
201 }
202
203 /// List the available modules and their information
204 ///
205 /// This endpoint returns a list of all of the available modules (like Contacts, Leads, Accounts)
206 /// available in your vtiger instance. You can optionally filter modules by the types of fields
207 /// they contain.
208 ///
209 /// #Arguments
210 ///
211 /// * `query`: An optional query string to filter the modules by. Common parameters:
212 /// - `("fieldTypeList", "null") or &[]- Return all available modules
213 /// - `("fieldTypeList", "picklist")- Return modules with picklist fields
214 /// - `("fieldTypeList", "grid")- Return modules with grid fields
215 ///
216 /// # Returns
217 ///
218 /// A `VtigerResponse` containing module information. The `result` typically includes:
219 /// - `types`: Array of module names
220 /// - `information`: Object with detailed info about each module
221 ///
222 /// # Errors
223 ///
224 /// Returns `reqwest::Error` for network issues or authentication failures.
225 /// Check the response's `success` field and `error` field for API-level errors.
226 ///
227 /// # Examples
228 ///
229 /// ```no_run
230 /// # use vtiger_client::Vtiger;
231 /// # #[tokio::main]
232 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
233 /// let vtiger = Vtiger::new("https://demo.vtiger.com/", "admin", "access_key");
234 ///
235 /// // Get all available modules
236 /// let all_modules = vtiger.list_types(&[("fieldTypeList", "null")]).await?;
237 ///
238 /// // Get modules with picklist fields only
239 /// let picklist_modules = vtiger.list_types(&[("fieldTypeList[]", "picklist")]).await?;
240 ///
241 /// // Get all modules (no filtering)
242 /// let modules = vtiger.list_types(&[]).await?;
243 ///
244 /// if all_modules.success {
245 /// println!("Available modules: {:#?}", all_modules.result);
246 /// }
247 /// # Ok(())
248 /// # }
249 /// ```
250 pub async fn list_types(
251 &self,
252 query: &[(&str, &str)],
253 ) -> Result<VtigerResponse, reqwest::Error> {
254 let response = self.get("/listtypes", query).await?;
255 let vtiger_response = response.json::<VtigerResponse>().await?;
256 Ok(vtiger_response)
257 }
258 /// List the fields of a module.
259 ///
260 /// This endpoint returns a list of fields, their types, labels, default values, and other metadata of a module.
261 ///
262 /// #Arguments
263 ///
264 /// - `module_name`: The name of the module to describe.
265 ///
266 /// #Errors
267 ///
268 /// Returns `reqwest::Error` for network issues or authentication failures.
269 /// Check the response's `success` field and `error` field for API-level errors.
270 ///
271 /// #Examples
272 ///
273 /// ```no_run
274 /// # use vtiger_client::Vtiger;
275 /// # #[tokio::main]
276 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
277 /// let vtiger = Vtiger::new("https://demo.vtiger.com/", "admin", "access_key");
278 ///
279 /// // Describe the Accounts module
280 /// let accounts_description = vtiger.describe("Accounts").await?;
281 ///
282 /// if accounts_description.success {
283 /// println!("Fields of Accounts module: {:#?}", accounts_description.result);
284 /// }
285 /// # Ok(())
286 /// # }
287 /// ```
288 pub async fn describe(&self, module_name: &str) -> Result<VtigerResponse, reqwest::Error> {
289 let response = self
290 .get(&format!("/describe"), &[("elementType", module_name)])
291 .await?;
292 let vtiger_response = response.json::<VtigerResponse>().await?;
293 Ok(vtiger_response)
294 }
295
296 /// Export records from a module to multiple file formats.
297 ///
298 /// This method performs a high-performance, concurrent export of records from a Vtiger module.
299 /// It automatically handles batching, concurrency, and multiple output formats simultaneously.
300 /// Be wary of rate limits and potential API throttling.
301 ///
302 /// # Process Overview
303 ///
304 /// 1. **Count Phase**: Determines record counts for each filter
305 /// 2. **Batch Phase**: Creates work items based on batch size
306 /// 3. **Concurrent Export**: Runs multiple queries in parallel
307 /// 4. **File Writing**: Writes to multiple formats simultaneously
308 ///
309 /// # Arguments
310 ///
311 /// * `module` - The Vtiger module name (e.g., "Leads", "Contacts", "Accounts")
312 /// * `query_filter` - Optional filter as (column_name, filter_values). Uses LIKE queries with '-' suffix
313 /// * `batch_size` - Number of records per batch (recommended: 100-200)
314 /// * `concurrency` - Number of concurrent requests (recommended: 2-5)
315 /// * `format` - Vector of output formats to generate simultaneously
316 ///
317 /// # Output Files
318 ///
319 /// * **JSON**: `output.json` - Single JSON array with all records
320 /// * **JSON Lines**: `output.jsonl` - One JSON object per line
321 /// * **CSV**: `output.csv` - Traditional CSV with headers
322 ///
323 /// # Performance Notes
324 ///
325 /// * Vtiger's query API has an implicit limit of ~100 records per query
326 /// * Batch sizes of 200 may work depending on module and account tier
327 /// * Higher concurrency may hit API rate limits
328 /// * Multiple formats are written simultaneously for efficiency
329 ///
330 /// # Examples
331 ///
332 /// ```no_run
333 /// use vtiger_client::{Vtiger, ExportFormat};
334 ///
335 /// #[tokio::main]
336 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
337 /// let vtiger = Vtiger::new("https://demo.vtiger.com", "admin", "key");
338 ///
339 /// // Export all leads
340 /// vtiger.export(
341 /// "Leads",
342 /// None,
343 /// 200,
344 /// 3,
345 /// vec![ExportFormat::Json, ExportFormat::CSV]
346 /// ).await?;
347 ///
348 /// // Export leads with specific locations
349 /// let locations = vec!["Los Angeles".to_string(), "Seattle".to_string()];
350 /// vtiger.export(
351 /// "Leads",
352 /// Some(("Location", locations)),
353 /// 200,
354 /// 3,
355 /// vec![ExportFormat::JsonLines]
356 /// ).await?;
357 ///
358 /// Ok(())
359 /// }
360 /// ```
361 ///
362 /// # Errors
363 ///
364 /// Returns an error if:
365 /// * Network requests fail
366 /// * File creation fails
367 /// * JSON serialization fails
368 /// * Invalid module name or query syntax
369 pub async fn export(
370 &self,
371 module: &str,
372 query_filter: Option<(&str, Vec<String>)>,
373 batch_size: usize,
374 concurrency: usize,
375 format: Vec<ExportFormat>,
376 ) -> Result<(), Box<dyn std::error::Error>> {
377 let (column, query_filters) = match query_filter {
378 Some((column, filters)) => (column, filters),
379 None => ("", vec![]),
380 };
381
382 let query_filter_counts: Vec<(String, i32)> = stream::iter(query_filters)
383 .map(|query_filter| async move {
384 let query = format!(
385 "SELECT count(*) from {} WHERE {} LIKE '{}-%';",
386 module, column, query_filter
387 );
388
389 let count = match self.query(&query).await {
390 Ok(result) => match result.result {
391 Some(records) => {
392 // Extract the count value directly without chaining references
393 if let Some(first_record) = records.get(0) {
394 if let Some(count_val) = first_record.get("count") {
395 if let Some(count_str) = count_val.as_str() {
396 count_str.parse::<i32>().unwrap_or(0)
397 } else {
398 0
399 }
400 } else {
401 0
402 }
403 } else {
404 0
405 }
406 }
407 None => 0,
408 },
409 Err(_) => 0,
410 };
411 if count != 0 {
412 println!("Received {} records for {}", count, query_filter);
413 }
414 (query_filter, count)
415 })
416 .buffer_unordered(concurrency)
417 .collect()
418 .await;
419
420 let work_items = query_filter_counts
421 .into_iter()
422 .flat_map(|(query_filter, count)| {
423 (0..count)
424 .step_by(batch_size.clone())
425 .map(|offset| (query_filter.clone(), offset, batch_size))
426 .collect::<Vec<_>>()
427 })
428 .collect::<Vec<_>>();
429 let (record_sender, mut record_receiver) =
430 mpsc::unbounded_channel::<IndexMap<String, serde_json::Value>>();
431
432 let writer_task = tokio::spawn(async move {
433 let mut file_json_lines: Option<File> = None;
434 let mut file_json: Option<File> = None;
435 let mut file_csv: Option<Writer<File>> = None;
436 if format.contains(&ExportFormat::JsonLines) {
437 file_json_lines = Some(File::create("output.jsonl").unwrap());
438 }
439 if format.contains(&ExportFormat::Json) {
440 file_json = Some(File::create("output.json").unwrap());
441 file_json
442 .as_mut()
443 .unwrap()
444 .write_all(b"[")
445 .expect("Could not write JSON array start");
446 }
447 if format.contains(&ExportFormat::CSV) {
448 file_csv = Some(
449 WriterBuilder::new()
450 .quote(b'"')
451 .quote_style(csv::QuoteStyle::Always)
452 .escape(b'\\')
453 .terminator(csv::Terminator::CRLF)
454 .from_path("output.csv")
455 .expect("CSV file creation failed"),
456 );
457 }
458 let mut count = 0;
459
460 while let Some(record) = record_receiver.recv().await {
461 if let Some(ref mut file) = file_json_lines {
462 writeln!(file, "{}", serde_json::to_string(&record).unwrap()).unwrap();
463 }
464 if let Some(ref mut file) = file_json {
465 if count != 0 {
466 write!(file, ",\n").unwrap();
467 }
468 writeln!(file, "{}", serde_json::to_string_pretty(&record).unwrap()).unwrap();
469 }
470 if let Some(ref mut file) = file_csv {
471 if count == 0 {
472 let header: Vec<&str> = record.keys().map(|k| k.as_str()).collect();
473 file.write_record(header)
474 .expect("Could not write CSV header record!");
475 }
476 let values: Vec<String> = record
477 .values()
478 .map(|v| match v {
479 serde_json::Value::String(s) => s
480 .replace('\n', "\\n")
481 .replace('\r', "\\r")
482 .replace('\t', "\\t"),
483 serde_json::Value::Number(s) => s.to_string(),
484 serde_json::Value::Bool(b) => b.to_string(),
485 serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
486 serde_json::to_string(v).unwrap_or_else(|_| String::new())
487 }
488 _ => "".to_string(),
489 })
490 .collect();
491 file.write_record(values)
492 .expect("Could not write CSV values record@");
493 }
494 count += 1;
495 if count % 10000 == 0 {
496 println!("Processed {} records", count);
497 }
498 }
499 println!("Finished writing {} total records", count);
500
501 if let Some(mut file) = file_json_lines {
502 file.flush().unwrap();
503 }
504
505 if let Some(mut file) = file_json {
506 write!(file, "\n]").unwrap(); // Close the JSON array
507 file.flush().unwrap();
508 }
509
510 if let Some(mut file) = file_csv {
511 file.flush().unwrap();
512 }
513
514 println!("All files flushed and closed");
515 });
516
517 stream::iter(work_items)
518 .map(|(query_filter, offset, batch_size)| {
519 let sender = record_sender.clone();
520 async move {
521 let query = format!(
522 "SELECT * FROM {} WHERE {} LIKE '{}%' LIMIT {}, {};",
523 module, column, query_filter, offset, batch_size
524 );
525 println!("Executing query: {}", query);
526
527 if let Ok(result) = self.query(&query).await {
528 if let Some(records) = result.result {
529 let record_count = records.len();
530 for record in records {
531 if let Err(_) = sender.send(record) {
532 eprintln!("Failed to send record, writer may have stopped");
533 break;
534 }
535 }
536 println!(
537 "Sent {} records from {} offset {}",
538 record_count, query_filter, offset
539 );
540 }
541 }
542 Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
543 }
544 })
545 .buffer_unordered(concurrency)
546 .collect::<Vec<_>>()
547 .await;
548
549 drop(record_sender);
550
551 writer_task.await.unwrap();
552
553 Ok(())
554 }
555
556 /// Create a new record in the specified module.
557 ///
558 /// This method creates a single record in Vtiger by sending field data
559 /// to the `/create` endpoint. The fields are automatically serialized
560 /// to JSON format as required by the Vtiger API.
561 ///
562 /// # Arguments
563 ///
564 /// * `module_name` - The name of the module to create the record in
565 /// * `fields` - Array of field name/value pairs to set on the new record
566 ///
567 /// # Returns
568 ///
569 /// Returns a [`VtigerResponse`] containing the created record's ID and data
570 /// on success, or the error details on failure.
571 ///
572 /// # Examples
573 ///
574 /// ```no_run
575 /// use vtiger_client::Vtiger;
576 ///
577 /// #[tokio::main]
578 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
579 /// let vtiger = Vtiger::new("https://demo.vtiger.com", "admin", "key");
580 ///
581 /// // Create a new lead
582 /// let response = vtiger.create(
583 /// "Leads",
584 /// &[
585 /// ("lastname", "Smith"),
586 /// ("firstname", "John"),
587 /// ("email", "john.smith@example.com"),
588 /// ("company", "Acme Corp"),
589 /// ]
590 /// ).await?;
591 ///
592 /// if response.success {
593 /// println!("Created record: {:?}", response.result);
594 /// } else {
595 /// eprintln!("Creation failed: {:?}", response.error);
596 /// }
597 ///
598 /// Ok(())
599 /// }
600 /// ```
601 ///
602 /// # Errors
603 ///
604 /// This method will return an error if:
605 /// * The network request fails
606 /// * The response cannot be parsed as JSON
607 /// * Invalid module name or field names are provided
608 /// * Required fields are missing (check API response for details)
609 pub async fn create(
610 &self,
611 module_name: &str,
612 fields: &[(&str, &str)],
613 ) -> Result<VtigerResponse, reqwest::Error> {
614 let fields_map: HashMap<&str, &str> = fields.iter().cloned().collect();
615 let element_json = serde_json::to_string(&fields_map)
616 .expect("Failed to serialize string IndexMap to JSON");
617
618 let response = self
619 .post(
620 "/create",
621 &[("elementType", module_name), ("element", &element_json)],
622 )
623 .await?;
624 let vtiger_response = response.json::<VtigerResponse>().await?;
625 Ok(vtiger_response)
626 }
627
628 /// Retrieve a single record by its ID.
629 ///
630 /// This method fetches a complete record from Vtiger using its unique ID.
631 /// The ID should be in Vtiger's format (e.g., "12x34" where 12 is the
632 /// module ID and 34 is the record ID).
633 ///
634 /// # Arguments
635 ///
636 /// * `record_id` - The Vtiger record ID (format: "ModuleIDxRecordID")
637 ///
638 /// # Returns
639 ///
640 /// Returns a [`VtigerResponse`] containing the record data on success,
641 /// or error details on failure.
642 ///
643 /// # Examples
644 ///
645 /// ```no_run
646 /// use vtiger_client::Vtiger;
647 ///
648 /// #[tokio::main]
649 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
650 /// let vtiger = Vtiger::new("https://demo.vtiger.com", "admin", "key");
651 ///
652 /// // Retrieve a specific lead record
653 /// let response = vtiger.retrieve("12x34").await?;
654 ///
655 /// if response.success {
656 /// if let Some(record) = response.result {
657 /// println!("Record data: {:#?}", record);
658 /// // Access specific fields
659 /// if let Some(name) = record.get("lastname") {
660 /// println!("Last name: {}", name);
661 /// }
662 /// }
663 /// } else {
664 /// eprintln!("Retrieval failed: {:?}", response.error);
665 /// }
666 ///
667 /// Ok(())
668 /// }
669 /// ```
670 ///
671 /// # Record ID Format
672 ///
673 /// Vtiger record IDs follow the format "ModuleIDxRecordID":
674 /// * `12x34` - Module 12, Record 34
675 /// * `4x567` - Module 4, Record 567
676 ///
677 /// You can typically get these IDs from:
678 /// * Previous create/query operations
679 /// * The Vtiger web interface URL
680 /// * Other API responses
681 ///
682 /// # Errors
683 ///
684 /// This method will return an error if:
685 /// * The network request fails
686 /// * The response cannot be parsed as JSON
687 /// * The record ID format is invalid
688 /// * The record doesn't exist or you don't have permission to view it
689 pub async fn retrieve(&self, record_id: &str) -> Result<VtigerResponse, reqwest::Error> {
690 let response = self
691 .get(&format!("/retrieve"), &[("id", record_id)])
692 .await?;
693 let vtiger_response = response.json::<VtigerResponse>().await?;
694 Ok(vtiger_response)
695 }
696
697 /// Execute a SQL-like query against Vtiger data.
698 ///
699 /// This method allows you to query Vtiger records using a SQL-like syntax.
700 /// It returns multiple records and is the primary method for searching
701 /// and filtering data in Vtiger.
702 ///
703 /// # Arguments
704 ///
705 /// * `query` - SQL-like query string using Vtiger's query syntax
706 ///
707 /// # Returns
708 ///
709 /// Returns a [`VtigerQueryResponse`] containing an array of matching records
710 /// on success, or error details on failure.
711 ///
712 /// # Query Syntax
713 ///
714 /// Vtiger supports a subset of SQL:
715 /// * `SELECT * FROM ModuleName`
716 /// * `SELECT field1, field2 FROM ModuleName`
717 /// * `WHERE` conditions with `=`, `!=`, `LIKE`, `IN`
718 /// * `ORDER BY` for sorting
719 /// * `LIMIT` for pagination (recommended: ≤200 records)
720 ///
721 /// # Examples
722 ///
723 /// ```no_run
724 /// use vtiger_client::Vtiger;
725 ///
726 /// #[tokio::main]
727 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
728 /// let vtiger = Vtiger::new("https://demo.vtiger.com", "admin", "key");
729 ///
730 /// // Basic query
731 /// let response = vtiger.query("SELECT * FROM Leads LIMIT 10").await?;
732 ///
733 /// // Query with conditions
734 /// let response = vtiger.query(
735 /// "SELECT firstname, lastname, email FROM Leads WHERE email != ''"
736 /// ).await?;
737 ///
738 /// // Query with LIKE operator
739 /// let response = vtiger.query(
740 /// "SELECT * FROM Leads WHERE lastname LIKE 'Smith%'"
741 /// ).await?;
742 ///
743 /// // Query with ordering
744 /// let response = vtiger.query(
745 /// "SELECT * FROM Leads ORDER BY createdtime DESC LIMIT 50"
746 /// ).await?;
747 ///
748 /// if response.success {
749 /// if let Some(records) = response.result {
750 /// println!("Found {} records", records.len());
751 /// for record in records {
752 /// println!("Record: {:#?}", record);
753 /// }
754 /// }
755 /// } else {
756 /// eprintln!("Query failed: {:?}", response.error);
757 /// }
758 ///
759 /// Ok(())
760 /// }
761 /// ```
762 ///
763 /// # Performance Considerations
764 ///
765 /// * **Limit results**: Always use `LIMIT` to avoid timeouts
766 /// * **Batch large queries**: Use pagination for large datasets
767 /// * **Index usage**: Filter on indexed fields when possible
768 /// * **Concurrent queries**: Use multiple queries for better performance
769 ///
770 /// # Common Query Patterns
771 ///
772 /// ```sql
773 /// -- Get recent records
774 /// SELECT * FROM Leads ORDER BY createdtime DESC LIMIT 100
775 ///
776 /// -- Filter by custom field
777 /// SELECT * FROM Leads WHERE location LIKE 'Los Angeles%'
778 ///
779 /// -- Count records
780 /// SELECT count(*) FROM Leads WHERE leadstatus = 'Hot'
781 ///
782 /// -- Multiple conditions
783 /// SELECT * FROM Leads WHERE email != '' AND leadstatus IN ('Hot', 'Warm')
784 /// ```
785 ///
786 /// # Errors
787 ///
788 /// This method will return an error if:
789 /// * The network request fails
790 /// * The response cannot be parsed as JSON
791 /// * Invalid SQL syntax is used
792 /// * Referenced fields or modules don't exist
793 /// * Query exceeds time or result limits
794 pub async fn query(&self, query: &str) -> Result<VtigerQueryResponse, reqwest::Error> {
795 let response = self.get(&format!("/query"), &[("query", query)]).await?;
796 let vtiger_response = response.json::<VtigerQueryResponse>().await?;
797 Ok(vtiger_response)
798 }
799
800 /// Update a record in the database
801 ///
802 /// This function takes a single record that must include an ID and all
803 /// required fields on the module in order to successfulyy update the record.
804 /// It's recommended to use the revise function instead of this one.
805 ///
806 /// # Arguments
807 ///
808 /// * `fields` - A vector of tuples containing the field name and value to update.
809 ///
810 /// # Returns
811 ///
812 /// Returns a [`VtigerResponse`] containing a message indicating success or failure,
813 /// and the result if successful.
814 ///
815 /// # Examples
816 ///
817 /// ```no_run
818 /// use vtiger_client::Vtiger;
819 ///
820 /// #[tokio::main]
821 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
822 /// let vtiger = Vtiger::new("https://demo.vtiger.com", "admin", "key");
823 ///
824 /// // Query with conditions
825 /// let update_fields = vec![
826 /// ("id", "2x12345"),
827 /// ("first_name", "John"),
828 /// ("last_name", "Smith"),
829 /// ("email", "smith@example.com"),
830 /// ("phone", "604-555-1212"),
831 /// ("lane", "123 Main St"),
832 /// ("city", "Los Angeles"),
833 /// ("state", "CA"),
834 /// ("postal_code", "12345"),
835 /// ];
836 /// let response = vtiger.update(&update_fields).await?;
837 ///
838 /// println!("Updated record: {:?}", response);
839 /// Ok(())
840 /// }
841 /// ```
842 pub async fn update(
843 &self,
844 fields: &Vec<(&str, &str)>,
845 ) -> Result<VtigerResponse, reqwest::Error> {
846 let map: HashMap<_, _> = fields.iter().cloned().collect();
847 let fields_json = serde_json::to_string(&map).unwrap();
848
849 let response = self
850 .post(&format!("/update"), &[("element", &fields_json)])
851 .await?;
852 let vtiger_response = response.json::<VtigerResponse>().await?;
853 Ok(vtiger_response)
854 }
855
856 /// Update a record in the database
857 ///
858 /// This function takes a single record that must include an ID and at least
859 /// one field to update.
860 ///
861 /// # Arguments
862 ///
863 /// * `fields` - A vector of tuples containing the field name and value to update.
864 ///
865 /// # Returns
866 ///
867 /// Returns a [`VtigerResponse`] containing a message indicating success or failure,
868 /// and the result if successful.
869 ///
870 /// # Examples
871 ///
872 /// ```no_run
873 /// use vtiger_client::Vtiger;
874 ///
875 /// #[tokio::main]
876 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
877 /// let vtiger = Vtiger::new("https://demo.vtiger.com", "admin", "key");
878 ///
879 /// // Query with conditions
880 /// let update_fields = vec![
881 /// ("id", "2x12345"),
882 /// ("phone", "604-555-1212"),
883 /// ];
884 /// let response = vtiger.revise(&update_fields).await?;
885 ///
886 /// println!("Updated record: {:?}", response);
887 /// Ok(())
888 /// }
889 /// ```
890 pub async fn revise(
891 &self,
892 fields: &Vec<(&str, &str)>,
893 ) -> Result<VtigerResponse, reqwest::Error> {
894 let map: HashMap<_, _> = fields.iter().cloned().collect();
895 let fields_json = serde_json::to_string(&map).unwrap();
896
897 let response = self
898 .post(&format!("/revise"), &[("element", &fields_json)])
899 .await?;
900 let vtiger_response = response.json::<VtigerResponse>().await?;
901 Ok(vtiger_response)
902 }
903}