Skip to content

Commit 288bbee

Browse files
author
Vsevolod
committed
working delete_rows
1 parent 370421c commit 288bbee

File tree

19 files changed

+177
-136
lines changed

19 files changed

+177
-136
lines changed

module/move/gspread/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ default-run = "main"
1717
name = "main"
1818
path = "src/bin/main.rs"
1919

20+
[[bin]]
21+
name = "test"
22+
path = "src/bin/test.rs"
23+
24+
2025
[features]
2126
with_online = []
2227
default = [ "enabled" ]

module/move/gspread/src/actions/gspread.rs

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,34 @@ mod private
1111
use once_cell::sync::Lazy;
1212
use std::collections::HashMap;
1313

14-
use crate::{gcore::{methods::values::{BatchClearValuesRequest, BatchClearValuesResponse, BatchUpdateValuesRequest, BatchUpdateValuesResponse, UpdateValuesResponse, ValuesClearResponse}, types::{DimensionRange, InsertDataOption, SheetProperties, ValueInputOption, ValueRenderOption}, Client, DeleteDimensionRequest, Dimension, Error, Result, ValueRange}, *};
14+
use crate::*;
15+
use gcore::methods::batch_update::BatchUpdateResponse;
16+
use gcore::methods::values::
17+
{
18+
BatchClearValuesRequest,
19+
BatchClearValuesResponse,
20+
BatchUpdateValuesRequest,
21+
BatchUpdateValuesResponse,
22+
UpdateValuesResponse,
23+
ValuesClearResponse
24+
};
25+
use gcore::types::
26+
{
27+
DimensionRange,
28+
InsertDataOption,
29+
SheetProperties,
30+
ValueInputOption,
31+
ValueRenderOption
32+
};
33+
use gcore::
34+
{
35+
Client,
36+
DeleteDimensionRequest,
37+
Dimension,
38+
Error,
39+
Result,
40+
ValueRange
41+
};
1542
use gcore::Secret;
1643

1744
static REGEX_ROW_INDEX : Lazy< Regex > = Lazy::new( || {
@@ -641,17 +668,30 @@ mod private
641668

642669
}
643670

671+
/// # delete_rows
672+
///
673+
/// Deletes selected range of rows. It starts from the first one.
674+
///
675+
/// ## Returns:
676+
/// - `Result< Response >`
677+
/// On success, returns a list of rows, where each row is a `Vec< serde_json::Value >`.
678+
///
679+
/// ## Errors:
680+
/// - `Error::ApiError`:
681+
/// Occurs if the Google Sheets API returns an error,
682+
/// such as an invalid spreadsheet ID, insufficient permissions,
683+
/// or any issues during the request/response cycle.
644684
pub async fn delete_rows< S : Secret >
645685
(
646686
client : &Client< '_, S >,
647687
spreadsheet_id : &str,
648688
sheet_id : &str,
649689
range : RowRange
650-
) -> Result<()>
690+
) -> Result< BatchUpdateResponse >
651691
{
652-
let (start_index, end_index) = match range
692+
let ( start_index, end_index ) = match range
653693
{
654-
RowRange::All => ( None, None ),
694+
RowRange::All => ( Some( 1 ), None ),
655695
RowRange::Range { row_start, row_end } => ( Some( row_start ), Some( row_end ) )
656696
};
657697

@@ -669,12 +709,12 @@ mod private
669709
};
670710

671711
match client
672-
.sheet()
673-
.delete_dimension( spreadsheet_id, request )
712+
.batch_update( spreadsheet_id )
713+
.delete_dimension( request )
674714
.doit()
675715
.await
676716
{
677-
Ok( _ ) => Ok( () ),
717+
Ok( response ) => Ok( response ),
678718
Err( error ) => Err( Error::ApiError( error.to_string() ) )
679719
}
680720
}
@@ -1177,6 +1217,7 @@ crate::mod_interface!
11771217
clear,
11781218
clear_by_custom_row_key,
11791219
copy_to,
1180-
RowRange
1220+
RowRange,
1221+
delete_rows
11811222
};
11821223
}
Lines changed: 9 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use std::error::Error;
21
use dotenv::dotenv;
2+
use gspread::actions::gspread::{delete_rows, RowRange};
33
use gspread::*;
44
use gcore::ApplicationSecret;
55
use gcore::client::
@@ -8,14 +8,8 @@ use gcore::client::
88
Client
99
};
1010

11-
use std::collections::HashMap;
12-
use serde_json::json;
13-
use rand::Rng;
14-
use rand::rngs::OsRng;
15-
16-
1711
#[ tokio::main ]
18-
async fn main() -> Result< (), Box< dyn Error > >
12+
async fn main()
1913
{
2014
dotenv().ok();
2115

@@ -27,76 +21,13 @@ async fn main() -> Result< (), Box< dyn Error > >
2721
.auth( auth )
2822
.form();
2923

30-
let spreadsheet_ids = vec![
31-
"172krpHTo_BI8Bwm9-9aGc5Bt9tm6P3nbiwkveVbO81k",
32-
];
33-
let tables = vec!["t1"];
34-
let mut row_key_val = generate_truly_random_key_val(5000, 100);
35-
36-
for &spreadsheet_id in &spreadsheet_ids {
37-
for i in 0..5 {
38-
for &sheet_name in &tables {
39-
row_key_val.insert("A".to_string(), json!(i));
40-
_ = gspread::actions::gspread::append_row(&client, spreadsheet_id, sheet_name, &row_key_val).await;
41-
}
42-
}
43-
}
44-
45-
Ok( () )
46-
}
47-
48-
49-
fn generate_truly_random_key_val(n: usize, str_len: usize) -> HashMap<String, serde_json::Value> {
50-
let all_cols = generate_all_columns();
51-
let total = all_cols.len();
52-
53-
let mut rng = OsRng;
54-
let mut indices: Vec<usize> = (0..total).collect();
24+
let spreadsheet_id = "15_AKiE2nWUYopNpSLsE_G1tBsiZRNoSfdU8VIuostLc";
25+
let sheet_id = "0";
26+
let range = RowRange::All;
5527

56-
for i in 0..total {
57-
let j = i + (rng.gen_range(0..(total - i)));
58-
indices.swap(i, j);
59-
}
60-
61-
let chosen_indices = &indices[0..n.min(total)];
62-
63-
let mut result = HashMap::new();
64-
for &idx in chosen_indices {
65-
let col = &all_cols[idx];
66-
let val = random_string(&mut rng, str_len);
67-
result.insert(col.clone(), json!(val));
68-
}
69-
result
70-
}
71-
72-
fn random_string(rng: &mut OsRng, length: usize) -> String {
73-
let charset = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
74-
abcdefghijklmnopqrstuvwxyz\
75-
0123456789";
76-
(0..length)
77-
.map(|_| {
78-
let idx = rng.gen_range(0..charset.len());
79-
charset[idx] as char
80-
})
81-
.collect()
82-
}
83-
84-
fn generate_all_columns() -> Vec<String> {
85-
let mut columns = Vec::new();
86-
for c1 in b'A'..=b'Z' {
87-
columns.push((c1 as char).to_string());
88-
}
89-
for c1 in b'A'..=b'Z' {
90-
for c2 in b'A'..=b'Z' {
91-
columns.push(format!("{}{}", c1 as char, c2 as char));
92-
}
93-
}
94-
for c1 in b'A'..=b'Z' {
95-
for c2 in b'A'..=b'Z' {
96-
for c3 in b'A'..=b'Z' {
97-
columns.push(format!("{}{}{}", c1 as char, c2 as char, c3 as char));
98-
}
99-
}
28+
match delete_rows( &client, spreadsheet_id, sheet_id, range ).await
29+
{
30+
Ok( _ ) => println!("Row was deleted"),
31+
Err( error ) => eprintln!( "{error}" )
10032
}
101-
columns
10233
}

module/move/gspread/src/gcore/methods/batch_update.rs

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,29 @@ mod private
2525
self
2626
}
2727

28-
pub async fn doit( &self ) -> Result< Response >
28+
pub fn include_spreadsheet_in_response( mut self ) -> SpreadSheetBatchUpdate< 'a, 'b, S >
29+
{
30+
self.include_spreadsheet_in_response = true;
31+
self
32+
}
33+
34+
pub fn response_ranges
35+
(
36+
mut self,
37+
ranges : Vec< String >
38+
) -> SpreadSheetBatchUpdate< 'a, 'b, S >
39+
{
40+
self.response_ranges = ranges;
41+
self
42+
}
43+
44+
pub fn response_include_grid_data( mut self ) -> SpreadSheetBatchUpdate< 'a, 'b, S >
45+
{
46+
self.response_include_grid_data = true;
47+
self
48+
}
49+
50+
pub async fn doit( &self ) -> Result< BatchUpdateResponse >
2951
{
3052
let endpoint = format!
3153
(
@@ -86,7 +108,7 @@ mod private
86108
return Err( Error::ApiError( response_text ) );
87109
}
88110

89-
let response_parsed = response.json::< Response >()
111+
let response_parsed = response.json::< BatchUpdateResponse >()
90112
.await
91113
.map_err( | err | Error::ParseError( err.to_string() ) )?;
92114

@@ -103,7 +125,7 @@ mod private
103125
#[ serde( rename = "includeSpreadsheetInResponse" ) ]
104126
include_spreadsheet_in_response : bool,
105127
/// Limits the ranges included in the response spreadsheet. Meaningful only if includeSpreadsheetInResponse is 'true'.
106-
#[ serde( rename = "resoponseRanges" ) ]
128+
#[ serde( rename = "responseRanges" ) ]
107129
response_ranges : Vec< String >,
108130
/// True if grid data should be returned. Meaningful only if includeSpreadsheetInResponse is 'true'. This parameter is ignored if a field mask was set in the request.
109131
#[ serde( rename = "responseIncludeGridData" ) ]
@@ -114,17 +136,18 @@ mod private
114136
pub struct BatchUpdateResponse
115137
{
116138
#[ serde( rename = "spreadsheetId" ) ]
117-
spreadsheet_id : Option< String >,
118-
replies : Option< Vec< Response > >,
139+
pub spreadsheet_id : Option< String >,
140+
pub replies : Option< Vec< Response > >,
119141
#[ serde( rename = "updatedSpreadsheet" ) ]
120-
updated_spreadsheet : Option< Spreadsheet >
142+
pub updated_spreadsheet : Option< Spreadsheet >
121143
}
122144
}
123145

124146
crate::mod_interface!
125147
{
126148
own use
127149
{
128-
SpreadSheetBatchUpdate
150+
SpreadSheetBatchUpdate,
151+
BatchUpdateResponse
129152
};
130153
}

module/move/gspread/src/gcore/methods/sheet.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,11 @@ mod private
1010
use gcore::
1111
{
1212
Client,
13-
Response,
1413
Secret,
1514
Error,
1615
Result
1716
};
18-
use gcore::types::
19-
{
20-
DeleteDimensionRequest,
21-
SheetProperties
22-
};
17+
use gcore::types::SheetProperties;
2318

2419
/// # SpreadSheetMethod
2520
///

module/move/gspread/src/gcore/types.rs

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ mod private
373373
}
374374

375375
/// Additional properties of a [DATA_SOURCE](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#SheetType) sheet.
376-
#[ derive( Debug, Serialize, Deserialize ) ]
376+
#[ derive( Debug, Serialize, Deserialize, Clone ) ]
377377
pub struct DataSourceSheetProperties
378378
{
379379
/// ID of the [DataSource](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#DataSource) the sheet is connected to.
@@ -434,13 +434,6 @@ mod private
434434
pub data_source_sheet_properties : Option< DataSourceSheetProperties >
435435
}
436436

437-
#[ derive( Debug ) ]
438-
pub struct Range
439-
{
440-
start_index : usize,
441-
end_index : usize
442-
}
443-
444437
/// A range along a single dimension on a sheet. All indexes are zero-based. Indexes are half open: the start index is inclusive and the end index is exclusive. Missing indexes indicate the range is unbounded on that side.
445438
#[ derive( Debug, Serialize, Deserialize, Clone ) ]
446439
pub struct DimensionRange
@@ -482,9 +475,11 @@ mod private
482475
}
483476

484477
#[ derive( Debug, Serialize, Deserialize ) ]
478+
#[ serde( untagged ) ]
485479
pub enum Response
486480
{
487-
DeleteDimensionGroupResponse,
481+
#[ serde( rename = "deleteDimensionGroup" ) ]
482+
DeleteDimensionGroup( DeleteDimensionGroupResponse ),
488483
}
489484

490485
#[ derive( Debug, ser::Serialize, ser::Deserialize, Clone ) ]
@@ -3974,7 +3969,7 @@ mod private
39743969
enbled : Option< bool >,
39753970
/// The scope of the refresh. Must be ALL_DATA_SOURCES.
39763971
#[ serde( rename = "refreshScope" ) ]
3977-
refreshScope : Option< DataSourceRefreshScope >,
3972+
refresh_scope : Option< DataSourceRefreshScope >,
39783973
/// Output only. The time interval of the next run.
39793974
#[ serde( rename = "nextRun" ) ]
39803975
next_run : Option< Interval >,

module/move/gspread/tests/mock/append_row.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//! Tests for `append_row` function.
33
//!
44
5-
use gspread::gcore::client::BatchUpdateValuesResponse;
5+
use gspread::gcore::methods::values::BatchUpdateValuesResponse;
66
use httpmock::prelude::*;
77
use serde_json::json;
88
use std::collections::HashMap;

module/move/gspread/tests/mock/clear.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,12 @@
22
//! Tests for `clear` function.
33
//!
44
5+
use gspread::gcore::methods::values::ValuesClearResponse;
56
use httpmock::prelude::*;
67
use gspread::*;
78
use actions::gspread::clear;
89
use gcore::ApplicationSecret;
9-
use gcore::client::
10-
{
11-
Client,
12-
ValuesClearResponse
13-
};
10+
use gcore::Client;
1411

1512

1613
/// # What

0 commit comments

Comments
 (0)