Skip to content
Closed

bad pr #1531

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions module/move/gspread/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ default-run = "main"
name = "main"
path = "src/bin/main.rs"

[[bin]]
name = "test"
path = "src/bin/test.rs"


[features]
with_online = []
default = [ "enabled" ]
Expand Down
160 changes: 137 additions & 23 deletions module/move/gspread/src/actions/gspread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,35 @@ mod private
use once_cell::sync::Lazy;
use std::collections::HashMap;

use crate::gcore::client::InsertDataOption;
use crate::*;
use gcore::Secret;
use gcore::error::
{
Error,
Result
use gcore::methods::batch_update::BatchUpdateResponse;
use gcore::methods::values::
{
BatchClearValuesRequest,
BatchClearValuesResponse,
BatchUpdateValuesRequest,
BatchUpdateValuesResponse,
UpdateValuesResponse,
ValuesClearResponse
};
use gcore::types::
{
DimensionRange,
InsertDataOption,
SheetProperties,
ValueInputOption,
ValueRenderOption
};
use gcore::client::
use gcore::
{
Client,
DeleteDimensionRequest,
Dimension,
ValueRange,
ValueInputOption,
ValueRenderOption,
UpdateValuesResponse,
// ValuesAppendResponse,
BatchUpdateValuesRequest,
BatchUpdateValuesResponse,
BatchClearValuesRequest,
BatchClearValuesResponse,
SheetProperties,
ValuesClearResponse
Error,
Result,
ValueRange
};
use gcore::Secret;

static REGEX_ROW_INDEX : Lazy< Regex > = Lazy::new( || {
Regex::new( r"^([A-Za-z]+)(\d+)$" ).unwrap()
Expand Down Expand Up @@ -663,6 +668,57 @@ mod private

}

/// # delete_rows
///
/// Deletes selected range of rows. It starts from the first one.
///
/// ## Returns:
/// - `Result< Response >`
/// On success, returns a list of rows, where each row is a `Vec< serde_json::Value >`.
///
/// ## Errors:
/// - `Error::ApiError`:
/// Occurs if the Google Sheets API returns an error,
/// such as an invalid spreadsheet ID, insufficient permissions,
/// or any issues during the request/response cycle.
pub async fn delete_rows< S : Secret >
(
client : &Client< '_, S >,
spreadsheet_id : &str,
sheet_id : &str,
range : RowRange
) -> Result< BatchUpdateResponse >
{
let ( start_index, end_index ) = match range
{
RowRange::All => ( Some( 1 ), None ),
RowRange::Range { row_start, row_end } => ( Some( row_start ), Some( row_end ) )
};

let dimension_range = DimensionRange
{
sheet_id : sheet_id.to_string(),
dimension : Dimension::Row,
start_index : start_index,
end_index : end_index
};

let request = DeleteDimensionRequest
{
range : dimension_range
};

match client
.batch_update( spreadsheet_id )
.delete_dimension( request )
.doit()
.await
{
Ok( response ) => Ok( response ),
Err( error ) => Err( Error::ApiError( error.to_string() ) )
}
}



/// # `get_header`
Expand Down Expand Up @@ -763,7 +819,7 @@ mod private
}
}

/// # `get_rows`
/// # `get_all_rows`
///
/// Retrieves all rows (excluding the header) from a specific sheet.
///
Expand All @@ -782,14 +838,70 @@ mod private
/// - `Error::ApiError`:
/// Occurs if the Google Sheets API returns an error, such as an invalid spreadsheet ID
/// or insufficient permissions.
pub async fn get_rows< S : Secret >
pub async fn get_all_rows< S : Secret >
(
client : &Client< '_, S >,
spreadsheet_id : &str,
sheet_name : &str,
) -> Result< Vec< Vec< serde_json::Value > > >
{
let range = format!( "{}!A2:ZZZ", sheet_name );
get_rows( client, spreadsheet_id, sheet_name, RowRange::All ).await
}

/// # `RowRange`
///
/// Enum sprecifies range of rows to retrieve from a sheet.
///
/// ## `Variants`:
/// - `All`:
/// All rows but not header.
/// - `Range`:
/// Specified range of rows.
pub enum RowRange
{
/// All rows but header (the first row in a sheet)
All,
/// The first and the last rows to retrieve. It will include header in response only in case you set `row_start` = 0.
Range
{
row_start : usize,
row_end : usize
}
}

/// # `get_rows`
///
/// Retrieves specified range of rows from a sheet.
///
/// ## Parameters:
/// - `client`:
/// A reference to the `Client` client configured for the Google Sheets API.
/// - `spreadsheet_id`:
/// A `&str` representing the unique identifier of the spreadsheet.
/// - `sheet_name`:
/// A `&str` specifying the name of the sheet whose rows are to be retrieved.
/// - `range`:
/// A `RowRange` variant.
/// ## Returns:
/// - `Result< Vec< Vec< serde_json::Value > > >`
///
/// ## Errors:
/// - `Error::ApiError`:
/// Occurs if the Google Sheets API returns an error, such as an invalid spreadsheet ID
/// or insufficient permissions.
pub async fn get_rows< S : Secret >
(
client : &Client< '_, S >,
spreadsheet_id : &str,
sheet_name : &str,
range : RowRange
)-> Result< Vec< Vec< serde_json::Value > > >
{
let range = match range
{
RowRange::All => format!( "{}!A2:ZZZ", sheet_name ),
RowRange::Range { row_start, row_end } => format!( "{}!A{}:ZZZ{}", sheet_name, row_start + 1, row_end + 1 )
};

match client
.spreadsheet()
Expand All @@ -808,7 +920,6 @@ mod private
}
Err( error ) => Err( error )
}

}

/// # `get_cell`
Expand Down Expand Up @@ -1096,6 +1207,7 @@ crate::mod_interface!
get_cell,
get_row,
get_rows,
get_all_rows,
update_row,
get_header,
append_row,
Expand All @@ -1104,6 +1216,8 @@ crate::mod_interface!
get_column,
clear,
clear_by_custom_row_key,
copy_to
copy_to,
RowRange,
delete_rows
};
}
9 changes: 6 additions & 3 deletions module/move/gspread/src/actions/gspread_rows_get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
mod private
{
use crate::*;
use actions::gspread::get_rows;
use actions::gspread::get_all_rows;
use gcore::Secret;
use gcore::error::Result;
use gcore::client::Client;
Expand All @@ -20,9 +20,12 @@ mod private
sheet_name : &str
) -> Result< Vec< Vec < serde_json::Value > > >
{
match get_rows( client, spreadsheet_id, sheet_name ).await
match get_all_rows( client, spreadsheet_id, sheet_name ).await
{
Ok( rows ) => Ok( rows ),
Ok( rows ) => {
println!("Got {} rows", rows.len());
Ok( rows )
},
Err( error ) => Err( error )
}
}
Expand Down
87 changes: 9 additions & 78 deletions module/move/gspread/src/bin/test.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::error::Error;
use dotenv::dotenv;
use gspread::actions::gspread::{delete_rows, RowRange};
use gspread::*;
use gcore::ApplicationSecret;
use gcore::client::
Expand All @@ -8,14 +8,8 @@ use gcore::client::
Client
};

use std::collections::HashMap;
use serde_json::json;
use rand::Rng;
use rand::rngs::OsRng;


#[ tokio::main ]
async fn main() -> Result< (), Box< dyn Error > >
async fn main()
{
dotenv().ok();

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

let spreadsheet_ids = vec![
"172krpHTo_BI8Bwm9-9aGc5Bt9tm6P3nbiwkveVbO81k",
];
let tables = vec!["t1"];
let mut row_key_val = generate_truly_random_key_val(5000, 100);

for &spreadsheet_id in &spreadsheet_ids {
for i in 0..5 {
for &sheet_name in &tables {
row_key_val.insert("A".to_string(), json!(i));
_ = gspread::actions::gspread::append_row(&client, spreadsheet_id, sheet_name, &row_key_val).await;
}
}
}

Ok( () )
}


fn generate_truly_random_key_val(n: usize, str_len: usize) -> HashMap<String, serde_json::Value> {
let all_cols = generate_all_columns();
let total = all_cols.len();

let mut rng = OsRng;
let mut indices: Vec<usize> = (0..total).collect();
let spreadsheet_id = "15_AKiE2nWUYopNpSLsE_G1tBsiZRNoSfdU8VIuostLc";
let sheet_id = "0";
let range = RowRange::All;

for i in 0..total {
let j = i + (rng.gen_range(0..(total - i)));
indices.swap(i, j);
}

let chosen_indices = &indices[0..n.min(total)];

let mut result = HashMap::new();
for &idx in chosen_indices {
let col = &all_cols[idx];
let val = random_string(&mut rng, str_len);
result.insert(col.clone(), json!(val));
}
result
}

fn random_string(rng: &mut OsRng, length: usize) -> String {
let charset = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
(0..length)
.map(|_| {
let idx = rng.gen_range(0..charset.len());
charset[idx] as char
})
.collect()
}

fn generate_all_columns() -> Vec<String> {
let mut columns = Vec::new();
for c1 in b'A'..=b'Z' {
columns.push((c1 as char).to_string());
}
for c1 in b'A'..=b'Z' {
for c2 in b'A'..=b'Z' {
columns.push(format!("{}{}", c1 as char, c2 as char));
}
}
for c1 in b'A'..=b'Z' {
for c2 in b'A'..=b'Z' {
for c3 in b'A'..=b'Z' {
columns.push(format!("{}{}{}", c1 as char, c2 as char, c3 as char));
}
}
match delete_rows( &client, spreadsheet_id, sheet_id, range ).await
{
Ok( _ ) => println!("Row was deleted"),
Err( error ) => eprintln!( "{error}" )
}
columns
}
2 changes: 2 additions & 0 deletions module/move/gspread/src/gcore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ crate::mod_interface!
layer client;
layer error;
layer secret;
layer types;
layer methods;
}
Loading
Loading