google_datastore1_beta3/
api.rs

1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16    /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17    CloudPlatform,
18
19    /// View and manage your Google Cloud Datastore data
20    Full,
21}
22
23impl AsRef<str> for Scope {
24    fn as_ref(&self) -> &str {
25        match *self {
26            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
27            Scope::Full => "https://www.googleapis.com/auth/datastore",
28        }
29    }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34    fn default() -> Scope {
35        Scope::Full
36    }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all Datastore related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_datastore1_beta3 as datastore1_beta3;
53/// use datastore1_beta3::api::RunQueryRequest;
54/// use datastore1_beta3::{Result, Error};
55/// # async fn dox() {
56/// use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace  `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
67///     .with_native_roots()
68///     .unwrap()
69///     .https_only()
70///     .enable_http2()
71///     .build();
72///
73/// let executor = hyper_util::rt::TokioExecutor::new();
74/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
75///     secret,
76///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
77///     yup_oauth2::client::CustomHyperClientBuilder::from(
78///         hyper_util::client::legacy::Client::builder(executor).build(connector),
79///     ),
80/// ).build().await.unwrap();
81///
82/// let client = hyper_util::client::legacy::Client::builder(
83///     hyper_util::rt::TokioExecutor::new()
84/// )
85/// .build(
86///     hyper_rustls::HttpsConnectorBuilder::new()
87///         .with_native_roots()
88///         .unwrap()
89///         .https_or_http()
90///         .enable_http2()
91///         .build()
92/// );
93/// let mut hub = Datastore::new(client, auth);
94/// // As the method needs a request, you would usually fill it with the desired information
95/// // into the respective structure. Some of the parts shown here might not be applicable !
96/// // Values shown here are possibly random and not representative !
97/// let mut req = RunQueryRequest::default();
98///
99/// // You can configure optional parameters by calling the respective setters at will, and
100/// // execute the final call using `doit()`.
101/// // Values shown here are possibly random and not representative !
102/// let result = hub.projects().run_query(req, "projectId")
103///              .doit().await;
104///
105/// match result {
106///     Err(e) => match e {
107///         // The Error enum provides details about what exactly happened.
108///         // You can also just use its `Debug`, `Display` or `Error` traits
109///          Error::HttpError(_)
110///         |Error::Io(_)
111///         |Error::MissingAPIKey
112///         |Error::MissingToken(_)
113///         |Error::Cancelled
114///         |Error::UploadSizeLimitExceeded(_, _)
115///         |Error::Failure(_)
116///         |Error::BadRequest(_)
117///         |Error::FieldClash(_)
118///         |Error::JsonDecodeError(_, _) => println!("{}", e),
119///     },
120///     Ok(res) => println!("Success: {:?}", res),
121/// }
122/// # }
123/// ```
124#[derive(Clone)]
125pub struct Datastore<C> {
126    pub client: common::Client<C>,
127    pub auth: Box<dyn common::GetToken>,
128    _user_agent: String,
129    _base_url: String,
130    _root_url: String,
131}
132
133impl<C> common::Hub for Datastore<C> {}
134
135impl<'a, C> Datastore<C> {
136    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Datastore<C> {
137        Datastore {
138            client,
139            auth: Box::new(auth),
140            _user_agent: "google-api-rust-client/7.0.0".to_string(),
141            _base_url: "https://datastore.googleapis.com/".to_string(),
142            _root_url: "https://datastore.googleapis.com/".to_string(),
143        }
144    }
145
146    pub fn projects(&'a self) -> ProjectMethods<'a, C> {
147        ProjectMethods { hub: self }
148    }
149
150    /// Set the user-agent header field to use in all requests to the server.
151    /// It defaults to `google-api-rust-client/7.0.0`.
152    ///
153    /// Returns the previously set user-agent.
154    pub fn user_agent(&mut self, agent_name: String) -> String {
155        std::mem::replace(&mut self._user_agent, agent_name)
156    }
157
158    /// Set the base url to use in all requests to the server.
159    /// It defaults to `https://datastore.googleapis.com/`.
160    ///
161    /// Returns the previously set base url.
162    pub fn base_url(&mut self, new_base_url: String) -> String {
163        std::mem::replace(&mut self._base_url, new_base_url)
164    }
165
166    /// Set the root url to use in all requests to the server.
167    /// It defaults to `https://datastore.googleapis.com/`.
168    ///
169    /// Returns the previously set root url.
170    pub fn root_url(&mut self, new_root_url: String) -> String {
171        std::mem::replace(&mut self._root_url, new_root_url)
172    }
173}
174
175// ############
176// SCHEMAS ###
177// ##########
178/// Defines an aggregation that produces a single result.
179///
180/// This type is not used in any activity, and only used as *part* of another schema.
181///
182#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
183#[serde_with::serde_as]
184#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
185pub struct Aggregation {
186    /// Optional. Optional name of the property to store the result of the aggregation. If not provided, Datastore will pick a default name following the format `property_`. For example: ``` AGGREGATE COUNT_UP_TO(1) AS count_up_to_1, COUNT_UP_TO(2), COUNT_UP_TO(3) AS count_up_to_3, COUNT(*) OVER ( ... ); ``` becomes: ``` AGGREGATE COUNT_UP_TO(1) AS count_up_to_1, COUNT_UP_TO(2) AS property_1, COUNT_UP_TO(3) AS count_up_to_3, COUNT(*) AS property_2 OVER ( ... ); ``` Requires: * Must be unique across all aggregation aliases. * Conform to entity property name limitations.
187    pub alias: Option<String>,
188    /// Average aggregator.
189    pub avg: Option<Avg>,
190    /// Count aggregator.
191    pub count: Option<Count>,
192    /// Sum aggregator.
193    pub sum: Option<Sum>,
194}
195
196impl common::Part for Aggregation {}
197
198/// Datastore query for running an aggregation over a Query.
199///
200/// This type is not used in any activity, and only used as *part* of another schema.
201///
202#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
203#[serde_with::serde_as]
204#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
205pub struct AggregationQuery {
206    /// Optional. Series of aggregations to apply over the results of the `nested_query`. Requires: * A minimum of one and maximum of five aggregations per query.
207    pub aggregations: Option<Vec<Aggregation>>,
208    /// Nested query for aggregation
209    #[serde(rename = "nestedQuery")]
210    pub nested_query: Option<Query>,
211}
212
213impl common::Part for AggregationQuery {}
214
215/// The result of a single bucket from a Datastore aggregation query. The keys of `aggregate_properties` are the same for all results in an aggregation query, unlike entity queries which can have different fields present for each result.
216///
217/// This type is not used in any activity, and only used as *part* of another schema.
218///
219#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
220#[serde_with::serde_as]
221#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
222pub struct AggregationResult {
223    /// The result of the aggregation functions, ex: `COUNT(*) AS total_entities`. The key is the alias assigned to the aggregation function on input and the size of this map equals the number of aggregation functions in the query.
224    #[serde(rename = "aggregateProperties")]
225    pub aggregate_properties: Option<HashMap<String, Value>>,
226}
227
228impl common::Part for AggregationResult {}
229
230/// A batch of aggregation results produced by an aggregation query.
231///
232/// This type is not used in any activity, and only used as *part* of another schema.
233///
234#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
235#[serde_with::serde_as]
236#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
237pub struct AggregationResultBatch {
238    /// The aggregation results for this batch.
239    #[serde(rename = "aggregationResults")]
240    pub aggregation_results: Option<Vec<AggregationResult>>,
241    /// The state of the query after the current batch. Only COUNT(*) aggregations are supported in the initial launch. Therefore, expected result type is limited to `NO_MORE_RESULTS`.
242    #[serde(rename = "moreResults")]
243    pub more_results: Option<String>,
244    /// Read timestamp this batch was returned from. In a single transaction, subsequent query result batches for the same query can have a greater timestamp. Each batch's read timestamp is valid for all preceding batches.
245    #[serde(rename = "readTime")]
246    pub read_time: Option<chrono::DateTime<chrono::offset::Utc>>,
247}
248
249impl common::Part for AggregationResultBatch {}
250
251/// The request for Datastore.AllocateIds.
252///
253/// # Activities
254///
255/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
256/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
257///
258/// * [allocate ids projects](ProjectAllocateIdCall) (request)
259#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
260#[serde_with::serde_as]
261#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
262pub struct AllocateIdsRequest {
263    /// Required. A list of keys with incomplete key paths for which to allocate IDs. No key may be reserved/read-only.
264    pub keys: Option<Vec<Key>>,
265}
266
267impl common::RequestValue for AllocateIdsRequest {}
268
269/// The response for Datastore.AllocateIds.
270///
271/// # Activities
272///
273/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
274/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
275///
276/// * [allocate ids projects](ProjectAllocateIdCall) (response)
277#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
278#[serde_with::serde_as]
279#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
280pub struct AllocateIdsResponse {
281    /// The keys specified in the request (in the same order), each with its key path completed with a newly allocated ID.
282    pub keys: Option<Vec<Key>>,
283}
284
285impl common::ResponseResult for AllocateIdsResponse {}
286
287/// An array value.
288///
289/// This type is not used in any activity, and only used as *part* of another schema.
290///
291#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
292#[serde_with::serde_as]
293#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
294pub struct ArrayValue {
295    /// Values in the array. The order of values in an array is preserved as long as all values have identical settings for 'exclude_from_indexes'.
296    pub values: Option<Vec<Value>>,
297}
298
299impl common::Part for ArrayValue {}
300
301/// Average of the values of the requested property. * Only numeric values will be aggregated. All non-numeric values including `NULL` are skipped. * If the aggregated values contain `NaN`, returns `NaN`. Infinity math follows IEEE-754 standards. * If the aggregated value set is empty, returns `NULL`. * Always returns the result as a double.
302///
303/// This type is not used in any activity, and only used as *part* of another schema.
304///
305#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
306#[serde_with::serde_as]
307#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
308pub struct Avg {
309    /// The property to aggregate on.
310    pub property: Option<PropertyReference>,
311}
312
313impl common::Part for Avg {}
314
315/// The request for Datastore.BeginTransaction.
316///
317/// # Activities
318///
319/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
320/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
321///
322/// * [begin transaction projects](ProjectBeginTransactionCall) (request)
323#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
324#[serde_with::serde_as]
325#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
326pub struct BeginTransactionRequest {
327    /// Options for a new transaction.
328    #[serde(rename = "transactionOptions")]
329    pub transaction_options: Option<TransactionOptions>,
330}
331
332impl common::RequestValue for BeginTransactionRequest {}
333
334/// The response for Datastore.BeginTransaction.
335///
336/// # Activities
337///
338/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
339/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
340///
341/// * [begin transaction projects](ProjectBeginTransactionCall) (response)
342#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
343#[serde_with::serde_as]
344#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
345pub struct BeginTransactionResponse {
346    /// The transaction identifier (always present).
347    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
348    pub transaction: Option<Vec<u8>>,
349}
350
351impl common::ResponseResult for BeginTransactionResponse {}
352
353/// The request for Datastore.Commit.
354///
355/// # Activities
356///
357/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
358/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
359///
360/// * [commit projects](ProjectCommitCall) (request)
361#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
362#[serde_with::serde_as]
363#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
364pub struct CommitRequest {
365    /// The type of commit to perform. Defaults to `TRANSACTIONAL`.
366    pub mode: Option<String>,
367    /// The mutations to perform. When mode is `TRANSACTIONAL`, mutations affecting a single entity are applied in order. The following sequences of mutations affecting a single entity are not permitted in a single `Commit` request: - `insert` followed by `insert` - `update` followed by `insert` - `upsert` followed by `insert` - `delete` followed by `update` When mode is `NON_TRANSACTIONAL`, no two mutations may affect a single entity.
368    pub mutations: Option<Vec<Mutation>>,
369    /// The identifier of the transaction associated with the commit. A transaction identifier is returned by a call to Datastore.BeginTransaction.
370    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
371    pub transaction: Option<Vec<u8>>,
372}
373
374impl common::RequestValue for CommitRequest {}
375
376/// The response for Datastore.Commit.
377///
378/// # Activities
379///
380/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
381/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
382///
383/// * [commit projects](ProjectCommitCall) (response)
384#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
385#[serde_with::serde_as]
386#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
387pub struct CommitResponse {
388    /// The transaction commit timestamp. Not set for non-transactional commits.
389    #[serde(rename = "commitTime")]
390    pub commit_time: Option<chrono::DateTime<chrono::offset::Utc>>,
391    /// The number of index entries updated during the commit, or zero if none were updated.
392    #[serde(rename = "indexUpdates")]
393    pub index_updates: Option<i32>,
394    /// The result of performing the mutations. The i-th mutation result corresponds to the i-th mutation in the request.
395    #[serde(rename = "mutationResults")]
396    pub mutation_results: Option<Vec<MutationResult>>,
397}
398
399impl common::ResponseResult for CommitResponse {}
400
401/// A filter that merges multiple other filters using the given operator.
402///
403/// This type is not used in any activity, and only used as *part* of another schema.
404///
405#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
406#[serde_with::serde_as]
407#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
408pub struct CompositeFilter {
409    /// The list of filters to combine. Requires: * At least one filter is present.
410    pub filters: Option<Vec<Filter>>,
411    /// The operator for combining multiple filters.
412    pub op: Option<String>,
413}
414
415impl common::Part for CompositeFilter {}
416
417/// Count of entities that match the query. The `COUNT(*)` aggregation function operates on the entire entity so it does not require a field reference.
418///
419/// This type is not used in any activity, and only used as *part* of another schema.
420///
421#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
422#[serde_with::serde_as]
423#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
424pub struct Count {
425    /// Optional. Optional constraint on the maximum number of entities to count. This provides a way to set an upper bound on the number of entities to scan, limiting latency, and cost. Unspecified is interpreted as no bound. If a zero value is provided, a count result of zero should always be expected. High-Level Example: ``` AGGREGATE COUNT_UP_TO(1000) OVER ( SELECT * FROM k ); ``` Requires: * Must be non-negative when present.
426    #[serde(rename = "upTo")]
427    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
428    pub up_to: Option<i64>,
429}
430
431impl common::Part for Count {}
432
433/// A Datastore data object. Must not exceed 1 MiB - 4 bytes.
434///
435/// This type is not used in any activity, and only used as *part* of another schema.
436///
437#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
438#[serde_with::serde_as]
439#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
440pub struct Entity {
441    /// The entity's key. An entity must have a key, unless otherwise documented (for example, an entity in `Value.entity_value` may have no key). An entity's kind is its key path's last element's kind, or null if it has no key.
442    pub key: Option<Key>,
443    /// The entity's properties. The map's keys are property names. A property name matching regex `__.*__` is reserved. A reserved property name is forbidden in certain documented contexts. The map keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be empty.
444    pub properties: Option<HashMap<String, Value>>,
445}
446
447impl common::Part for Entity {}
448
449/// The result of fetching an entity from Datastore.
450///
451/// This type is not used in any activity, and only used as *part* of another schema.
452///
453#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
454#[serde_with::serde_as]
455#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
456pub struct EntityResult {
457    /// The time at which the entity was created. This field is set for `FULL` entity results. If this entity is missing, this field will not be set.
458    #[serde(rename = "createTime")]
459    pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
460    /// A cursor that points to the position after the result entity. Set only when the `EntityResult` is part of a `QueryResultBatch` message.
461    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
462    pub cursor: Option<Vec<u8>>,
463    /// The resulting entity.
464    pub entity: Option<Entity>,
465    /// The time at which the entity was last changed. This field is set for `FULL` entity results. If this entity is missing, this field will not be set.
466    #[serde(rename = "updateTime")]
467    pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
468    /// The version of the entity, a strictly positive number that monotonically increases with changes to the entity. This field is set for `FULL` entity results. For missing entities in `LookupResponse`, this is the version of the snapshot that was used to look up the entity, and it is always set except for eventually consistent reads.
469    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
470    pub version: Option<i64>,
471}
472
473impl common::Part for EntityResult {}
474
475/// Execution statistics for the query.
476///
477/// This type is not used in any activity, and only used as *part* of another schema.
478///
479#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
480#[serde_with::serde_as]
481#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
482pub struct ExecutionStats {
483    /// Debugging statistics from the execution of the query. Note that the debugging stats are subject to change as Firestore evolves. It could include: { "indexes_entries_scanned": "1000", "documents_scanned": "20", "billing_details" : { "documents_billable": "20", "index_entries_billable": "1000", "min_query_cost": "0" } }
484    #[serde(rename = "debugStats")]
485    pub debug_stats: Option<HashMap<String, serde_json::Value>>,
486    /// Total time to execute the query in the backend.
487    #[serde(rename = "executionDuration")]
488    #[serde_as(as = "Option<common::serde::duration::Wrapper>")]
489    pub execution_duration: Option<chrono::Duration>,
490    /// Total billable read operations.
491    #[serde(rename = "readOperations")]
492    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
493    pub read_operations: Option<i64>,
494    /// Total number of results returned, including documents, projections, aggregation results, keys.
495    #[serde(rename = "resultsReturned")]
496    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
497    pub results_returned: Option<i64>,
498}
499
500impl common::Part for ExecutionStats {}
501
502/// Explain metrics for the query.
503///
504/// This type is not used in any activity, and only used as *part* of another schema.
505///
506#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
507#[serde_with::serde_as]
508#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
509pub struct ExplainMetrics {
510    /// Aggregated stats from the execution of the query. Only present when ExplainOptions.analyze is set to true.
511    #[serde(rename = "executionStats")]
512    pub execution_stats: Option<ExecutionStats>,
513    /// Planning phase information for the query.
514    #[serde(rename = "planSummary")]
515    pub plan_summary: Option<PlanSummary>,
516}
517
518impl common::Part for ExplainMetrics {}
519
520/// Explain options for the query.
521///
522/// This type is not used in any activity, and only used as *part* of another schema.
523///
524#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
525#[serde_with::serde_as]
526#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
527pub struct ExplainOptions {
528    /// Optional. Whether to execute this query. When false (the default), the query will be planned, returning only metrics from the planning stages. When true, the query will be planned and executed, returning the full query results along with both planning and execution stage metrics.
529    pub analyze: Option<bool>,
530}
531
532impl common::Part for ExplainOptions {}
533
534/// A holder for any type of filter.
535///
536/// This type is not used in any activity, and only used as *part* of another schema.
537///
538#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
539#[serde_with::serde_as]
540#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
541pub struct Filter {
542    /// A composite filter.
543    #[serde(rename = "compositeFilter")]
544    pub composite_filter: Option<CompositeFilter>,
545    /// A filter on a property.
546    #[serde(rename = "propertyFilter")]
547    pub property_filter: Option<PropertyFilter>,
548}
549
550impl common::Part for Filter {}
551
552/// Nearest Neighbors search config. The ordering provided by FindNearest supersedes the order_by stage. If multiple documents have the same vector distance, the returned document order is not guaranteed to be stable between queries.
553///
554/// This type is not used in any activity, and only used as *part* of another schema.
555///
556#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
557#[serde_with::serde_as]
558#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
559pub struct FindNearest {
560    /// Required. The Distance Measure to use, required.
561    #[serde(rename = "distanceMeasure")]
562    pub distance_measure: Option<String>,
563    /// Optional. Optional name of the field to output the result of the vector distance calculation. Must conform to entity property limitations.
564    #[serde(rename = "distanceResultProperty")]
565    pub distance_result_property: Option<String>,
566    /// Optional. Option to specify a threshold for which no less similar documents will be returned. The behavior of the specified `distance_measure` will affect the meaning of the distance threshold. Since DOT_PRODUCT distances increase when the vectors are more similar, the comparison is inverted. * For EUCLIDEAN, COSINE: WHERE distance <= distance_threshold * For DOT_PRODUCT: WHERE distance >= distance_threshold
567    #[serde(rename = "distanceThreshold")]
568    pub distance_threshold: Option<f64>,
569    /// Required. The number of nearest neighbors to return. Must be a positive integer of no more than 100.
570    pub limit: Option<i32>,
571    /// Required. The query vector that we are searching on. Must be a vector of no more than 2048 dimensions.
572    #[serde(rename = "queryVector")]
573    pub query_vector: Option<Value>,
574    /// Required. An indexed vector property to search upon. Only documents which contain vectors whose dimensionality match the query_vector can be returned.
575    #[serde(rename = "vectorProperty")]
576    pub vector_property: Option<PropertyReference>,
577}
578
579impl common::Part for FindNearest {}
580
581/// A [GQL query](https://cloud.google.com/datastore/docs/apis/gql/gql_reference).
582///
583/// This type is not used in any activity, and only used as *part* of another schema.
584///
585#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
586#[serde_with::serde_as]
587#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
588pub struct GqlQuery {
589    /// When false, the query string must not contain any literals and instead must bind all values. For example, `SELECT * FROM Kind WHERE a = 'string literal'` is not allowed, while `SELECT * FROM Kind WHERE a = @value` is.
590    #[serde(rename = "allowLiterals")]
591    pub allow_literals: Option<bool>,
592    /// For each non-reserved named binding site in the query string, there must be a named parameter with that name, but not necessarily the inverse. Key must match regex `A-Za-z_$*`, must not match regex `__.*__`, and must not be `""`.
593    #[serde(rename = "namedBindings")]
594    pub named_bindings: Option<HashMap<String, GqlQueryParameter>>,
595    /// Numbered binding site @1 references the first numbered parameter, effectively using 1-based indexing, rather than the usual 0. For each binding site numbered i in `query_string`, there must be an i-th numbered parameter. The inverse must also be true.
596    #[serde(rename = "positionalBindings")]
597    pub positional_bindings: Option<Vec<GqlQueryParameter>>,
598    /// A string of the format described [here](https://cloud.google.com/datastore/docs/apis/gql/gql_reference).
599    #[serde(rename = "queryString")]
600    pub query_string: Option<String>,
601}
602
603impl common::Part for GqlQuery {}
604
605/// A binding parameter for a GQL query.
606///
607/// This type is not used in any activity, and only used as *part* of another schema.
608///
609#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
610#[serde_with::serde_as]
611#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
612pub struct GqlQueryParameter {
613    /// A query cursor. Query cursors are returned in query result batches.
614    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
615    pub cursor: Option<Vec<u8>>,
616    /// A value parameter.
617    pub value: Option<Value>,
618}
619
620impl common::Part for GqlQueryParameter {}
621
622/// A unique identifier for an entity. If a key's partition ID or any of its path kinds or names are reserved/read-only, the key is reserved/read-only. A reserved/read-only key is forbidden in certain documented contexts.
623///
624/// This type is not used in any activity, and only used as *part* of another schema.
625///
626#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
627#[serde_with::serde_as]
628#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
629pub struct Key {
630    /// Entities are partitioned into subsets, currently identified by a project ID and namespace ID. Queries are scoped to a single partition.
631    #[serde(rename = "partitionId")]
632    pub partition_id: Option<PartitionId>,
633    /// The entity path. An entity path consists of one or more elements composed of a kind and a string or numerical identifier, which identify entities. The first element identifies a _root entity_, the second element identifies a _child_ of the root entity, the third element identifies a child of the second entity, and so forth. The entities identified by all prefixes of the path are called the element's _ancestors_. An entity path is always fully complete: *all* of the entity's ancestors are required to be in the path along with the entity identifier itself. The only exception is that in some documented cases, the identifier in the last path element (for the entity) itself may be omitted. For example, the last path element of the key of `Mutation.insert` may have no identifier. A path can never be empty, and a path can have at most 100 elements.
634    pub path: Option<Vec<PathElement>>,
635}
636
637impl common::Part for Key {}
638
639/// A representation of a kind.
640///
641/// This type is not used in any activity, and only used as *part* of another schema.
642///
643#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
644#[serde_with::serde_as]
645#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
646pub struct KindExpression {
647    /// The name of the kind.
648    pub name: Option<String>,
649}
650
651impl common::Part for KindExpression {}
652
653/// An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard. Values must be within normalized ranges.
654///
655/// This type is not used in any activity, and only used as *part* of another schema.
656///
657#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
658#[serde_with::serde_as]
659#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
660pub struct LatLng {
661    /// The latitude in degrees. It must be in the range [-90.0, +90.0].
662    pub latitude: Option<f64>,
663    /// The longitude in degrees. It must be in the range [-180.0, +180.0].
664    pub longitude: Option<f64>,
665}
666
667impl common::Part for LatLng {}
668
669/// The request for Datastore.Lookup.
670///
671/// # Activities
672///
673/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
674/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
675///
676/// * [lookup projects](ProjectLookupCall) (request)
677#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
678#[serde_with::serde_as]
679#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
680pub struct LookupRequest {
681    /// Required. Keys of entities to look up.
682    pub keys: Option<Vec<Key>>,
683    /// The properties to return. Defaults to returning all properties. If this field is set and an entity has a property not referenced in the mask, it will be absent from LookupResponse.found.entity.properties. The entity's key is always returned.
684    #[serde(rename = "propertyMask")]
685    pub property_mask: Option<PropertyMask>,
686    /// The options for this lookup request.
687    #[serde(rename = "readOptions")]
688    pub read_options: Option<ReadOptions>,
689}
690
691impl common::RequestValue for LookupRequest {}
692
693/// The response for Datastore.Lookup.
694///
695/// # Activities
696///
697/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
698/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
699///
700/// * [lookup projects](ProjectLookupCall) (response)
701#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
702#[serde_with::serde_as]
703#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
704pub struct LookupResponse {
705    /// A list of keys that were not looked up due to resource constraints. The order of results in this field is undefined and has no relation to the order of the keys in the input.
706    pub deferred: Option<Vec<Key>>,
707    /// Entities found as `ResultType.FULL` entities. The order of results in this field is undefined and has no relation to the order of the keys in the input.
708    pub found: Option<Vec<EntityResult>>,
709    /// Entities not found as `ResultType.KEY_ONLY` entities. The order of results in this field is undefined and has no relation to the order of the keys in the input.
710    pub missing: Option<Vec<EntityResult>>,
711    /// The time at which these entities were read or found missing.
712    #[serde(rename = "readTime")]
713    pub read_time: Option<chrono::DateTime<chrono::offset::Utc>>,
714}
715
716impl common::ResponseResult for LookupResponse {}
717
718/// A mutation to apply to an entity.
719///
720/// This type is not used in any activity, and only used as *part* of another schema.
721///
722#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
723#[serde_with::serde_as]
724#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
725pub struct Mutation {
726    /// The version of the entity that this mutation is being applied to. If this does not match the current version on the server, the mutation conflicts.
727    #[serde(rename = "baseVersion")]
728    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
729    pub base_version: Option<i64>,
730    /// The strategy to use when a conflict is detected. Defaults to `SERVER_VALUE`. If this is set, then `conflict_detection_strategy` must also be set.
731    #[serde(rename = "conflictResolutionStrategy")]
732    pub conflict_resolution_strategy: Option<String>,
733    /// The key of the entity to delete. The entity may or may not already exist. Must have a complete key path and must not be reserved/read-only.
734    pub delete: Option<Key>,
735    /// The entity to insert. The entity must not already exist. The entity key's final path element may be incomplete.
736    pub insert: Option<Entity>,
737    /// The properties to write in this mutation. None of the properties in the mask may have a reserved name, except for `__key__`. This field is ignored for `delete`. If the entity already exists, only properties referenced in the mask are updated, others are left untouched. Properties referenced in the mask but not in the entity are deleted.
738    #[serde(rename = "propertyMask")]
739    pub property_mask: Option<PropertyMask>,
740    /// Optional. The transforms to perform on the entity. This field can be set only when the operation is `insert`, `update`, or `upsert`. If present, the transforms are be applied to the entity regardless of the property mask, in order, after the operation.
741    #[serde(rename = "propertyTransforms")]
742    pub property_transforms: Option<Vec<PropertyTransform>>,
743    /// The entity to update. The entity must already exist. Must have a complete key path.
744    pub update: Option<Entity>,
745    /// The update time of the entity that this mutation is being applied to. If this does not match the current update time on the server, the mutation conflicts.
746    #[serde(rename = "updateTime")]
747    pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
748    /// The entity to upsert. The entity may or may not already exist. The entity key's final path element may be incomplete.
749    pub upsert: Option<Entity>,
750}
751
752impl common::Part for Mutation {}
753
754/// The result of applying a mutation.
755///
756/// This type is not used in any activity, and only used as *part* of another schema.
757///
758#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
759#[serde_with::serde_as]
760#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
761pub struct MutationResult {
762    /// Whether a conflict was detected for this mutation. Always false when a conflict detection strategy field is not set in the mutation.
763    #[serde(rename = "conflictDetected")]
764    pub conflict_detected: Option<bool>,
765    /// The create time of the entity. This field will not be set after a 'delete'.
766    #[serde(rename = "createTime")]
767    pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
768    /// The automatically allocated key. Set only when the mutation allocated a key.
769    pub key: Option<Key>,
770    /// The results of applying each PropertyTransform, in the same order of the request.
771    #[serde(rename = "transformResults")]
772    pub transform_results: Option<Vec<Value>>,
773    /// The update time of the entity on the server after processing the mutation. If the mutation doesn't change anything on the server, then the timestamp will be the update timestamp of the current entity. This field will not be set after a 'delete'.
774    #[serde(rename = "updateTime")]
775    pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
776    /// The version of the entity on the server after processing the mutation. If the mutation doesn't change anything on the server, then the version will be the version of the current entity or, if no entity is present, a version that is strictly greater than the version of any previous entity and less than the version of any possible future entity.
777    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
778    pub version: Option<i64>,
779}
780
781impl common::Part for MutationResult {}
782
783/// A partition ID identifies a grouping of entities. The grouping is always by project and namespace, however the namespace ID may be empty. A partition ID contains several dimensions: project ID and namespace ID. Partition dimensions: - May be `""`. - Must be valid UTF-8 bytes. - Must have values that match regex `[A-Za-z\d\.\-_]{1,100}` If the value of any dimension matches regex `__.*__`, the partition is reserved/read-only. A reserved/read-only partition ID is forbidden in certain documented contexts. Foreign partition IDs (in which the project ID does not match the context project ID ) are discouraged. Reads and writes of foreign partition IDs may fail if the project is not in an active state.
784///
785/// This type is not used in any activity, and only used as *part* of another schema.
786///
787#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
788#[serde_with::serde_as]
789#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
790pub struct PartitionId {
791    /// If not empty, the ID of the namespace to which the entities belong.
792    #[serde(rename = "namespaceId")]
793    pub namespace_id: Option<String>,
794    /// The ID of the project to which the entities belong.
795    #[serde(rename = "projectId")]
796    pub project_id: Option<String>,
797}
798
799impl common::Part for PartitionId {}
800
801/// A (kind, ID/name) pair used to construct a key path. If either name or ID is set, the element is complete. If neither is set, the element is incomplete.
802///
803/// This type is not used in any activity, and only used as *part* of another schema.
804///
805#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
806#[serde_with::serde_as]
807#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
808pub struct PathElement {
809    /// The auto-allocated ID of the entity. Never equal to zero. Values less than zero are discouraged and may not be supported in the future.
810    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
811    pub id: Option<i64>,
812    /// The kind of the entity. A kind matching regex `__.*__` is reserved/read-only. A kind must not contain more than 1500 bytes when UTF-8 encoded. Cannot be `""`. Must be valid UTF-8 bytes. Legacy values that are not valid UTF-8 are encoded as `__bytes__` where `` is the base-64 encoding of the bytes.
813    pub kind: Option<String>,
814    /// The name of the entity. A name matching regex `__.*__` is reserved/read-only. A name must not be more than 1500 bytes when UTF-8 encoded. Cannot be `""`. Must be valid UTF-8 bytes. Legacy values that are not valid UTF-8 are encoded as `__bytes__` where `` is the base-64 encoding of the bytes.
815    pub name: Option<String>,
816}
817
818impl common::Part for PathElement {}
819
820/// Planning phase information for the query.
821///
822/// This type is not used in any activity, and only used as *part* of another schema.
823///
824#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
825#[serde_with::serde_as]
826#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
827pub struct PlanSummary {
828    /// The indexes selected for the query. For example: [ {"query_scope": "Collection", "properties": "(foo ASC, __name__ ASC)"}, {"query_scope": "Collection", "properties": "(bar ASC, __name__ ASC)"} ]
829    #[serde(rename = "indexesUsed")]
830    pub indexes_used: Option<Vec<HashMap<String, serde_json::Value>>>,
831}
832
833impl common::Part for PlanSummary {}
834
835/// A representation of a property in a projection.
836///
837/// This type is not used in any activity, and only used as *part* of another schema.
838///
839#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
840#[serde_with::serde_as]
841#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
842pub struct Projection {
843    /// The property to project.
844    pub property: Option<PropertyReference>,
845}
846
847impl common::Part for Projection {}
848
849/// A filter on a specific property.
850///
851/// This type is not used in any activity, and only used as *part* of another schema.
852///
853#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
854#[serde_with::serde_as]
855#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
856pub struct PropertyFilter {
857    /// The operator to filter by.
858    pub op: Option<String>,
859    /// The property to filter by.
860    pub property: Option<PropertyReference>,
861    /// The value to compare the property to.
862    pub value: Option<Value>,
863}
864
865impl common::Part for PropertyFilter {}
866
867/// The set of arbitrarily nested property paths used to restrict an operation to only a subset of properties in an entity.
868///
869/// This type is not used in any activity, and only used as *part* of another schema.
870///
871#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
872#[serde_with::serde_as]
873#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
874pub struct PropertyMask {
875    /// The paths to the properties covered by this mask. A path is a list of property names separated by dots (`.`), for example `foo.bar` means the property `bar` inside the entity property `foo` inside the entity associated with this path. If a property name contains a dot `.` or a backslash `\`, then that name must be escaped. A path must not be empty, and may not reference a value inside an array value.
876    pub paths: Option<Vec<String>>,
877}
878
879impl common::Part for PropertyMask {}
880
881/// The desired order for a specific property.
882///
883/// This type is not used in any activity, and only used as *part* of another schema.
884///
885#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
886#[serde_with::serde_as]
887#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
888pub struct PropertyOrder {
889    /// The direction to order by. Defaults to `ASCENDING`.
890    pub direction: Option<String>,
891    /// The property to order by.
892    pub property: Option<PropertyReference>,
893}
894
895impl common::Part for PropertyOrder {}
896
897/// A reference to a property relative to the kind expressions.
898///
899/// This type is not used in any activity, and only used as *part* of another schema.
900///
901#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
902#[serde_with::serde_as]
903#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
904pub struct PropertyReference {
905    /// A reference to a property. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to entity property name limitations.
906    pub name: Option<String>,
907}
908
909impl common::Part for PropertyReference {}
910
911/// A transformation of an entity property.
912///
913/// This type is not used in any activity, and only used as *part* of another schema.
914///
915#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
916#[serde_with::serde_as]
917#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
918pub struct PropertyTransform {
919    /// Appends the given elements in order if they are not already present in the current property value. If the property is not an array, or if the property does not yet exist, it is first set to the empty array. Equivalent numbers of different types (e.g. 3L and 3.0) are considered equal when checking if a value is missing. NaN is equal to NaN, and the null value is equal to the null value. If the input contains multiple equivalent values, only the first will be considered. The corresponding transform result will be the null value.
920    #[serde(rename = "appendMissingElements")]
921    pub append_missing_elements: Option<ArrayValue>,
922    /// Adds the given value to the property's current value. This must be an integer or a double value. If the property is not an integer or double, or if the property does not yet exist, the transformation will set the property to the given value. If either of the given value or the current property value are doubles, both values will be interpreted as doubles. Double arithmetic and representation of double values follows IEEE 754 semantics. If there is positive/negative integer overflow, the property is resolved to the largest magnitude positive/negative integer.
923    pub increment: Option<Value>,
924    /// Sets the property to the maximum of its current value and the given value. This must be an integer or a double value. If the property is not an integer or double, or if the property does not yet exist, the transformation will set the property to the given value. If a maximum operation is applied where the property and the input value are of mixed types (that is - one is an integer and one is a double) the property takes on the type of the larger operand. If the operands are equivalent (e.g. 3 and 3.0), the property does not change. 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and zero input value is always the stored value. The maximum of any numeric value x and NaN is NaN.
925    pub maximum: Option<Value>,
926    /// Sets the property to the minimum of its current value and the given value. This must be an integer or a double value. If the property is not an integer or double, or if the property does not yet exist, the transformation will set the property to the input value. If a minimum operation is applied where the property and the input value are of mixed types (that is - one is an integer and one is a double) the property takes on the type of the smaller operand. If the operands are equivalent (e.g. 3 and 3.0), the property does not change. 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and zero input value is always the stored value. The minimum of any numeric value x and NaN is NaN.
927    pub minimum: Option<Value>,
928    /// Optional. The name of the property. Property paths (a list of property names separated by dots (`.`)) may be used to refer to properties inside entity values. For example `foo.bar` means the property `bar` inside the entity property `foo`. If a property name contains a dot `.` or a backlslash `\`, then that name must be escaped.
929    pub property: Option<String>,
930    /// Removes all of the given elements from the array in the property. If the property is not an array, or if the property does not yet exist, it is set to the empty array. Equivalent numbers of different types (e.g. 3L and 3.0) are considered equal when deciding whether an element should be removed. NaN is equal to NaN, and the null value is equal to the null value. This will remove all equivalent values if there are duplicates. The corresponding transform result will be the null value.
931    #[serde(rename = "removeAllFromArray")]
932    pub remove_all_from_array: Option<ArrayValue>,
933    /// Sets the property to the given server value.
934    #[serde(rename = "setToServerValue")]
935    pub set_to_server_value: Option<String>,
936}
937
938impl common::Part for PropertyTransform {}
939
940/// A query for entities. The query stages are executed in the following order: 1. kind 2. filter 3. projection 4. order + start_cursor + end_cursor 5. offset 6. limit 7. find_nearest
941///
942/// This type is not used in any activity, and only used as *part* of another schema.
943///
944#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
945#[serde_with::serde_as]
946#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
947pub struct Query {
948    /// The properties to make distinct. The query results will contain the first result for each distinct combination of values for the given properties (if empty, all results are returned). Requires: * If `order` is specified, the set of distinct on properties must appear before the non-distinct on properties in `order`.
949    #[serde(rename = "distinctOn")]
950    pub distinct_on: Option<Vec<PropertyReference>>,
951    /// An ending point for the query results. Query cursors are returned in query result batches and [can only be used to limit the same query](https://cloud.google.com/datastore/docs/concepts/queries#cursors_limits_and_offsets).
952    #[serde(rename = "endCursor")]
953    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
954    pub end_cursor: Option<Vec<u8>>,
955    /// The filter to apply.
956    pub filter: Option<Filter>,
957    /// Optional. A potential Nearest Neighbors Search. Applies after all other filters and ordering. Finds the closest vector embeddings to the given query vector.
958    #[serde(rename = "findNearest")]
959    pub find_nearest: Option<FindNearest>,
960    /// The kinds to query (if empty, returns entities of all kinds). Currently at most 1 kind may be specified.
961    pub kind: Option<Vec<KindExpression>>,
962    /// The maximum number of results to return. Applies after all other constraints. Optional. Unspecified is interpreted as no limit. Must be >= 0 if specified.
963    pub limit: Option<i32>,
964    /// The number of results to skip. Applies before limit, but after all other constraints. Optional. Must be >= 0 if specified.
965    pub offset: Option<i32>,
966    /// The order to apply to the query results (if empty, order is unspecified).
967    pub order: Option<Vec<PropertyOrder>>,
968    /// The projection to return. Defaults to returning all properties.
969    pub projection: Option<Vec<Projection>>,
970    /// A starting point for the query results. Query cursors are returned in query result batches and [can only be used to continue the same query](https://cloud.google.com/datastore/docs/concepts/queries#cursors_limits_and_offsets).
971    #[serde(rename = "startCursor")]
972    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
973    pub start_cursor: Option<Vec<u8>>,
974}
975
976impl common::Part for Query {}
977
978/// A batch of results produced by a query.
979///
980/// This type is not used in any activity, and only used as *part* of another schema.
981///
982#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
983#[serde_with::serde_as]
984#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
985pub struct QueryResultBatch {
986    /// A cursor that points to the position after the last result in the batch.
987    #[serde(rename = "endCursor")]
988    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
989    pub end_cursor: Option<Vec<u8>>,
990    /// The result type for every entity in `entity_results`.
991    #[serde(rename = "entityResultType")]
992    pub entity_result_type: Option<String>,
993    /// The results for this batch.
994    #[serde(rename = "entityResults")]
995    pub entity_results: Option<Vec<EntityResult>>,
996    /// The state of the query after the current batch.
997    #[serde(rename = "moreResults")]
998    pub more_results: Option<String>,
999    /// Read timestamp this batch was returned from. This applies to the range of results from the query's `start_cursor` (or the beginning of the query if no cursor was given) to this batch's `end_cursor` (not the query's `end_cursor`). In a single transaction, subsequent query result batches for the same query can have a greater timestamp. Each batch's read timestamp is valid for all preceding batches. This value will not be set for eventually consistent queries in Cloud Datastore.
1000    #[serde(rename = "readTime")]
1001    pub read_time: Option<chrono::DateTime<chrono::offset::Utc>>,
1002    /// A cursor that points to the position after the last skipped result. Will be set when `skipped_results` != 0.
1003    #[serde(rename = "skippedCursor")]
1004    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
1005    pub skipped_cursor: Option<Vec<u8>>,
1006    /// The number of results skipped, typically because of an offset.
1007    #[serde(rename = "skippedResults")]
1008    pub skipped_results: Option<i32>,
1009    /// The version number of the snapshot this batch was returned from. This applies to the range of results from the query's `start_cursor` (or the beginning of the query if no cursor was given) to this batch's `end_cursor` (not the query's `end_cursor`). In a single transaction, subsequent query result batches for the same query can have a greater snapshot version number. Each batch's snapshot version is valid for all preceding batches. The value will be zero for eventually consistent queries.
1010    #[serde(rename = "snapshotVersion")]
1011    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1012    pub snapshot_version: Option<i64>,
1013}
1014
1015impl common::Part for QueryResultBatch {}
1016
1017/// Options specific to read-only transactions.
1018///
1019/// This type is not used in any activity, and only used as *part* of another schema.
1020///
1021#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1022#[serde_with::serde_as]
1023#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1024pub struct ReadOnly {
1025    /// Reads entities at the given time. This must be a microsecond precision timestamp within the past one hour, or if Point-in-Time Recovery is enabled, can additionally be a whole minute timestamp within the past 7 days.
1026    #[serde(rename = "readTime")]
1027    pub read_time: Option<chrono::DateTime<chrono::offset::Utc>>,
1028}
1029
1030impl common::Part for ReadOnly {}
1031
1032/// The options shared by read requests.
1033///
1034/// This type is not used in any activity, and only used as *part* of another schema.
1035///
1036#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1037#[serde_with::serde_as]
1038#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1039pub struct ReadOptions {
1040    /// The non-transactional read consistency to use.
1041    #[serde(rename = "readConsistency")]
1042    pub read_consistency: Option<String>,
1043    /// Reads entities as they were at the given time. This value is only supported for Cloud Firestore in Datastore mode. This must be a microsecond precision timestamp within the past one hour, or if Point-in-Time Recovery is enabled, can additionally be a whole minute timestamp within the past 7 days.
1044    #[serde(rename = "readTime")]
1045    pub read_time: Option<chrono::DateTime<chrono::offset::Utc>>,
1046    /// The identifier of the transaction in which to read. A transaction identifier is returned by a call to Datastore.BeginTransaction.
1047    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
1048    pub transaction: Option<Vec<u8>>,
1049}
1050
1051impl common::Part for ReadOptions {}
1052
1053/// Options specific to read / write transactions.
1054///
1055/// This type is not used in any activity, and only used as *part* of another schema.
1056///
1057#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1058#[serde_with::serde_as]
1059#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1060pub struct ReadWrite {
1061    /// The transaction identifier of the transaction being retried.
1062    #[serde(rename = "previousTransaction")]
1063    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
1064    pub previous_transaction: Option<Vec<u8>>,
1065}
1066
1067impl common::Part for ReadWrite {}
1068
1069/// The request for Datastore.ReserveIds.
1070///
1071/// # Activities
1072///
1073/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1074/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1075///
1076/// * [reserve ids projects](ProjectReserveIdCall) (request)
1077#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1078#[serde_with::serde_as]
1079#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1080pub struct ReserveIdsRequest {
1081    /// The ID of the database against which to make the request. '(default)' is not allowed; please use empty string '' to refer the default database.
1082    #[serde(rename = "databaseId")]
1083    pub database_id: Option<String>,
1084    /// Required. A list of keys with complete key paths whose numeric IDs should not be auto-allocated.
1085    pub keys: Option<Vec<Key>>,
1086}
1087
1088impl common::RequestValue for ReserveIdsRequest {}
1089
1090/// The response for Datastore.ReserveIds.
1091///
1092/// # Activities
1093///
1094/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1095/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1096///
1097/// * [reserve ids projects](ProjectReserveIdCall) (response)
1098#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1099#[serde_with::serde_as]
1100#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1101pub struct ReserveIdsResponse {
1102    _never_set: Option<bool>,
1103}
1104
1105impl common::ResponseResult for ReserveIdsResponse {}
1106
1107/// The request for Datastore.Rollback.
1108///
1109/// # Activities
1110///
1111/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1112/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1113///
1114/// * [rollback projects](ProjectRollbackCall) (request)
1115#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1116#[serde_with::serde_as]
1117#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1118pub struct RollbackRequest {
1119    /// Required. The transaction identifier, returned by a call to Datastore.BeginTransaction.
1120    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
1121    pub transaction: Option<Vec<u8>>,
1122}
1123
1124impl common::RequestValue for RollbackRequest {}
1125
1126/// The response for Datastore.Rollback. (an empty message).
1127///
1128/// # Activities
1129///
1130/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1131/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1132///
1133/// * [rollback projects](ProjectRollbackCall) (response)
1134#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1135#[serde_with::serde_as]
1136#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1137pub struct RollbackResponse {
1138    _never_set: Option<bool>,
1139}
1140
1141impl common::ResponseResult for RollbackResponse {}
1142
1143/// The request for Datastore.RunAggregationQuery.
1144///
1145/// # Activities
1146///
1147/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1148/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1149///
1150/// * [run aggregation query projects](ProjectRunAggregationQueryCall) (request)
1151#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1152#[serde_with::serde_as]
1153#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1154pub struct RunAggregationQueryRequest {
1155    /// The query to run.
1156    #[serde(rename = "aggregationQuery")]
1157    pub aggregation_query: Option<AggregationQuery>,
1158    /// Optional. Explain options for the query. If set, additional query statistics will be returned. If not, only query results will be returned.
1159    #[serde(rename = "explainOptions")]
1160    pub explain_options: Option<ExplainOptions>,
1161    /// The GQL query to run. This query must be an aggregation query.
1162    #[serde(rename = "gqlQuery")]
1163    pub gql_query: Option<GqlQuery>,
1164    /// Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID.
1165    #[serde(rename = "partitionId")]
1166    pub partition_id: Option<PartitionId>,
1167    /// The options for this query.
1168    #[serde(rename = "readOptions")]
1169    pub read_options: Option<ReadOptions>,
1170}
1171
1172impl common::RequestValue for RunAggregationQueryRequest {}
1173
1174/// The response for Datastore.RunAggregationQuery.
1175///
1176/// # Activities
1177///
1178/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1179/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1180///
1181/// * [run aggregation query projects](ProjectRunAggregationQueryCall) (response)
1182#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1183#[serde_with::serde_as]
1184#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1185pub struct RunAggregationQueryResponse {
1186    /// A batch of aggregation results. Always present.
1187    pub batch: Option<AggregationResultBatch>,
1188    /// Query explain metrics. This is only present when the RunAggregationQueryRequest.explain_options is provided, and it is sent only once with the last response in the stream.
1189    #[serde(rename = "explainMetrics")]
1190    pub explain_metrics: Option<ExplainMetrics>,
1191    /// The parsed form of the `GqlQuery` from the request, if it was set.
1192    pub query: Option<AggregationQuery>,
1193}
1194
1195impl common::ResponseResult for RunAggregationQueryResponse {}
1196
1197/// The request for Datastore.RunQuery.
1198///
1199/// # Activities
1200///
1201/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1202/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1203///
1204/// * [run query projects](ProjectRunQueryCall) (request)
1205#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1206#[serde_with::serde_as]
1207#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1208pub struct RunQueryRequest {
1209    /// Optional. Explain options for the query. If set, additional query statistics will be returned. If not, only query results will be returned.
1210    #[serde(rename = "explainOptions")]
1211    pub explain_options: Option<ExplainOptions>,
1212    /// The GQL query to run. This query must be a non-aggregation query.
1213    #[serde(rename = "gqlQuery")]
1214    pub gql_query: Option<GqlQuery>,
1215    /// Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID.
1216    #[serde(rename = "partitionId")]
1217    pub partition_id: Option<PartitionId>,
1218    /// The properties to return. This field must not be set for a projection query. See LookupRequest.property_mask.
1219    #[serde(rename = "propertyMask")]
1220    pub property_mask: Option<PropertyMask>,
1221    /// The query to run.
1222    pub query: Option<Query>,
1223    /// The options for this query.
1224    #[serde(rename = "readOptions")]
1225    pub read_options: Option<ReadOptions>,
1226}
1227
1228impl common::RequestValue for RunQueryRequest {}
1229
1230/// The response for Datastore.RunQuery.
1231///
1232/// # Activities
1233///
1234/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1235/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1236///
1237/// * [run query projects](ProjectRunQueryCall) (response)
1238#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1239#[serde_with::serde_as]
1240#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1241pub struct RunQueryResponse {
1242    /// A batch of query results. This is always present unless running a query under explain-only mode: RunQueryRequest.explain_options was provided and ExplainOptions.analyze was set to false.
1243    pub batch: Option<QueryResultBatch>,
1244    /// Query explain metrics. This is only present when the RunQueryRequest.explain_options is provided, and it is sent only once with the last response in the stream.
1245    #[serde(rename = "explainMetrics")]
1246    pub explain_metrics: Option<ExplainMetrics>,
1247    /// The parsed form of the `GqlQuery` from the request, if it was set.
1248    pub query: Option<Query>,
1249}
1250
1251impl common::ResponseResult for RunQueryResponse {}
1252
1253/// Sum of the values of the requested property. * Only numeric values will be aggregated. All non-numeric values including `NULL` are skipped. * If the aggregated values contain `NaN`, returns `NaN`. Infinity math follows IEEE-754 standards. * If the aggregated value set is empty, returns 0. * Returns a 64-bit integer if all aggregated numbers are integers and the sum result does not overflow. Otherwise, the result is returned as a double. Note that even if all the aggregated values are integers, the result is returned as a double if it cannot fit within a 64-bit signed integer. When this occurs, the returned value will lose precision. * When underflow occurs, floating-point aggregation is non-deterministic. This means that running the same query repeatedly without any changes to the underlying values could produce slightly different results each time. In those cases, values should be stored as integers over floating-point numbers.
1254///
1255/// This type is not used in any activity, and only used as *part* of another schema.
1256///
1257#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1258#[serde_with::serde_as]
1259#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1260pub struct Sum {
1261    /// The property to aggregate on.
1262    pub property: Option<PropertyReference>,
1263}
1264
1265impl common::Part for Sum {}
1266
1267/// Options for beginning a new transaction. Transactions can be created explicitly with calls to Datastore.BeginTransaction or implicitly by setting ReadOptions.new_transaction in read requests.
1268///
1269/// This type is not used in any activity, and only used as *part* of another schema.
1270///
1271#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1272#[serde_with::serde_as]
1273#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1274pub struct TransactionOptions {
1275    /// The transaction should only allow reads.
1276    #[serde(rename = "readOnly")]
1277    pub read_only: Option<ReadOnly>,
1278    /// The transaction should allow both reads and writes.
1279    #[serde(rename = "readWrite")]
1280    pub read_write: Option<ReadWrite>,
1281}
1282
1283impl common::Part for TransactionOptions {}
1284
1285/// A message that can hold any of the supported value types and associated metadata.
1286///
1287/// This type is not used in any activity, and only used as *part* of another schema.
1288///
1289#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1290#[serde_with::serde_as]
1291#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1292pub struct Value {
1293    /// An array value. Cannot contain another array value. A `Value` instance that sets field `array_value` must not set fields `meaning` or `exclude_from_indexes`.
1294    #[serde(rename = "arrayValue")]
1295    pub array_value: Option<ArrayValue>,
1296    /// A blob value. May have at most 1,000,000 bytes. When `exclude_from_indexes` is false, may have at most 1500 bytes. In JSON requests, must be base64-encoded.
1297    #[serde(rename = "blobValue")]
1298    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
1299    pub blob_value: Option<Vec<u8>>,
1300    /// A boolean value.
1301    #[serde(rename = "booleanValue")]
1302    pub boolean_value: Option<bool>,
1303    /// A double value.
1304    #[serde(rename = "doubleValue")]
1305    pub double_value: Option<f64>,
1306    /// An entity value. - May have no key. - May have a key with an incomplete key path. - May have a reserved/read-only key.
1307    #[serde(rename = "entityValue")]
1308    pub entity_value: Option<Entity>,
1309    /// If the value should be excluded from all indexes including those defined explicitly.
1310    #[serde(rename = "excludeFromIndexes")]
1311    pub exclude_from_indexes: Option<bool>,
1312    /// A geo point value representing a point on the surface of Earth.
1313    #[serde(rename = "geoPointValue")]
1314    pub geo_point_value: Option<LatLng>,
1315    /// An integer value.
1316    #[serde(rename = "integerValue")]
1317    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1318    pub integer_value: Option<i64>,
1319    /// A key value.
1320    #[serde(rename = "keyValue")]
1321    pub key_value: Option<Key>,
1322    /// The `meaning` field should only be populated for backwards compatibility.
1323    pub meaning: Option<i32>,
1324    /// A null value.
1325    #[serde(rename = "nullValue")]
1326    pub null_value: Option<String>,
1327    /// A UTF-8 encoded string value. When `exclude_from_indexes` is false (it is indexed) , may have at most 1500 bytes. Otherwise, may be set to at most 1,000,000 bytes.
1328    #[serde(rename = "stringValue")]
1329    pub string_value: Option<String>,
1330    /// A timestamp value. When stored in the Datastore, precise only to microseconds; any additional precision is rounded down.
1331    #[serde(rename = "timestampValue")]
1332    pub timestamp_value: Option<chrono::DateTime<chrono::offset::Utc>>,
1333}
1334
1335impl common::Part for Value {}
1336
1337// ###################
1338// MethodBuilders ###
1339// #################
1340
1341/// A builder providing access to all methods supported on *project* resources.
1342/// It is not used directly, but through the [`Datastore`] hub.
1343///
1344/// # Example
1345///
1346/// Instantiate a resource builder
1347///
1348/// ```test_harness,no_run
1349/// extern crate hyper;
1350/// extern crate hyper_rustls;
1351/// extern crate google_datastore1_beta3 as datastore1_beta3;
1352///
1353/// # async fn dox() {
1354/// use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1355///
1356/// let secret: yup_oauth2::ApplicationSecret = Default::default();
1357/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
1358///     .with_native_roots()
1359///     .unwrap()
1360///     .https_only()
1361///     .enable_http2()
1362///     .build();
1363///
1364/// let executor = hyper_util::rt::TokioExecutor::new();
1365/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1366///     secret,
1367///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1368///     yup_oauth2::client::CustomHyperClientBuilder::from(
1369///         hyper_util::client::legacy::Client::builder(executor).build(connector),
1370///     ),
1371/// ).build().await.unwrap();
1372///
1373/// let client = hyper_util::client::legacy::Client::builder(
1374///     hyper_util::rt::TokioExecutor::new()
1375/// )
1376/// .build(
1377///     hyper_rustls::HttpsConnectorBuilder::new()
1378///         .with_native_roots()
1379///         .unwrap()
1380///         .https_or_http()
1381///         .enable_http2()
1382///         .build()
1383/// );
1384/// let mut hub = Datastore::new(client, auth);
1385/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
1386/// // like `allocate_ids(...)`, `begin_transaction(...)`, `commit(...)`, `lookup(...)`, `reserve_ids(...)`, `rollback(...)`, `run_aggregation_query(...)` and `run_query(...)`
1387/// // to build up your call.
1388/// let rb = hub.projects();
1389/// # }
1390/// ```
1391pub struct ProjectMethods<'a, C>
1392where
1393    C: 'a,
1394{
1395    hub: &'a Datastore<C>,
1396}
1397
1398impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
1399
1400impl<'a, C> ProjectMethods<'a, C> {
1401    /// Create a builder to help you perform the following task:
1402    ///
1403    /// Allocates IDs for the given keys, which is useful for referencing an entity before it is inserted.
1404    ///
1405    /// # Arguments
1406    ///
1407    /// * `request` - No description provided.
1408    /// * `projectId` - Required. The ID of the project against which to make the request.
1409    pub fn allocate_ids(
1410        &self,
1411        request: AllocateIdsRequest,
1412        project_id: &str,
1413    ) -> ProjectAllocateIdCall<'a, C> {
1414        ProjectAllocateIdCall {
1415            hub: self.hub,
1416            _request: request,
1417            _project_id: project_id.to_string(),
1418            _delegate: Default::default(),
1419            _additional_params: Default::default(),
1420            _scopes: Default::default(),
1421        }
1422    }
1423
1424    /// Create a builder to help you perform the following task:
1425    ///
1426    /// Begins a new transaction.
1427    ///
1428    /// # Arguments
1429    ///
1430    /// * `request` - No description provided.
1431    /// * `projectId` - Required. The ID of the project against which to make the request.
1432    pub fn begin_transaction(
1433        &self,
1434        request: BeginTransactionRequest,
1435        project_id: &str,
1436    ) -> ProjectBeginTransactionCall<'a, C> {
1437        ProjectBeginTransactionCall {
1438            hub: self.hub,
1439            _request: request,
1440            _project_id: project_id.to_string(),
1441            _delegate: Default::default(),
1442            _additional_params: Default::default(),
1443            _scopes: Default::default(),
1444        }
1445    }
1446
1447    /// Create a builder to help you perform the following task:
1448    ///
1449    /// Commits a transaction, optionally creating, deleting or modifying some entities.
1450    ///
1451    /// # Arguments
1452    ///
1453    /// * `request` - No description provided.
1454    /// * `projectId` - Required. The ID of the project against which to make the request.
1455    pub fn commit(&self, request: CommitRequest, project_id: &str) -> ProjectCommitCall<'a, C> {
1456        ProjectCommitCall {
1457            hub: self.hub,
1458            _request: request,
1459            _project_id: project_id.to_string(),
1460            _delegate: Default::default(),
1461            _additional_params: Default::default(),
1462            _scopes: Default::default(),
1463        }
1464    }
1465
1466    /// Create a builder to help you perform the following task:
1467    ///
1468    /// Looks up entities by key.
1469    ///
1470    /// # Arguments
1471    ///
1472    /// * `request` - No description provided.
1473    /// * `projectId` - Required. The ID of the project against which to make the request.
1474    pub fn lookup(&self, request: LookupRequest, project_id: &str) -> ProjectLookupCall<'a, C> {
1475        ProjectLookupCall {
1476            hub: self.hub,
1477            _request: request,
1478            _project_id: project_id.to_string(),
1479            _delegate: Default::default(),
1480            _additional_params: Default::default(),
1481            _scopes: Default::default(),
1482        }
1483    }
1484
1485    /// Create a builder to help you perform the following task:
1486    ///
1487    /// Prevents the supplied keys' IDs from being auto-allocated by Cloud Datastore.
1488    ///
1489    /// # Arguments
1490    ///
1491    /// * `request` - No description provided.
1492    /// * `projectId` - Required. The ID of the project against which to make the request.
1493    pub fn reserve_ids(
1494        &self,
1495        request: ReserveIdsRequest,
1496        project_id: &str,
1497    ) -> ProjectReserveIdCall<'a, C> {
1498        ProjectReserveIdCall {
1499            hub: self.hub,
1500            _request: request,
1501            _project_id: project_id.to_string(),
1502            _delegate: Default::default(),
1503            _additional_params: Default::default(),
1504            _scopes: Default::default(),
1505        }
1506    }
1507
1508    /// Create a builder to help you perform the following task:
1509    ///
1510    /// Rolls back a transaction.
1511    ///
1512    /// # Arguments
1513    ///
1514    /// * `request` - No description provided.
1515    /// * `projectId` - Required. The ID of the project against which to make the request.
1516    pub fn rollback(
1517        &self,
1518        request: RollbackRequest,
1519        project_id: &str,
1520    ) -> ProjectRollbackCall<'a, C> {
1521        ProjectRollbackCall {
1522            hub: self.hub,
1523            _request: request,
1524            _project_id: project_id.to_string(),
1525            _delegate: Default::default(),
1526            _additional_params: Default::default(),
1527            _scopes: Default::default(),
1528        }
1529    }
1530
1531    /// Create a builder to help you perform the following task:
1532    ///
1533    /// Runs an aggregation query.
1534    ///
1535    /// # Arguments
1536    ///
1537    /// * `request` - No description provided.
1538    /// * `projectId` - Required. The ID of the project against which to make the request.
1539    pub fn run_aggregation_query(
1540        &self,
1541        request: RunAggregationQueryRequest,
1542        project_id: &str,
1543    ) -> ProjectRunAggregationQueryCall<'a, C> {
1544        ProjectRunAggregationQueryCall {
1545            hub: self.hub,
1546            _request: request,
1547            _project_id: project_id.to_string(),
1548            _delegate: Default::default(),
1549            _additional_params: Default::default(),
1550            _scopes: Default::default(),
1551        }
1552    }
1553
1554    /// Create a builder to help you perform the following task:
1555    ///
1556    /// Queries for entities.
1557    ///
1558    /// # Arguments
1559    ///
1560    /// * `request` - No description provided.
1561    /// * `projectId` - Required. The ID of the project against which to make the request.
1562    pub fn run_query(
1563        &self,
1564        request: RunQueryRequest,
1565        project_id: &str,
1566    ) -> ProjectRunQueryCall<'a, C> {
1567        ProjectRunQueryCall {
1568            hub: self.hub,
1569            _request: request,
1570            _project_id: project_id.to_string(),
1571            _delegate: Default::default(),
1572            _additional_params: Default::default(),
1573            _scopes: Default::default(),
1574        }
1575    }
1576}
1577
1578// ###################
1579// CallBuilders   ###
1580// #################
1581
1582/// Allocates IDs for the given keys, which is useful for referencing an entity before it is inserted.
1583///
1584/// A builder for the *allocateIds* method supported by a *project* resource.
1585/// It is not used directly, but through a [`ProjectMethods`] instance.
1586///
1587/// # Example
1588///
1589/// Instantiate a resource method builder
1590///
1591/// ```test_harness,no_run
1592/// # extern crate hyper;
1593/// # extern crate hyper_rustls;
1594/// # extern crate google_datastore1_beta3 as datastore1_beta3;
1595/// use datastore1_beta3::api::AllocateIdsRequest;
1596/// # async fn dox() {
1597/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1598///
1599/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1600/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1601/// #     .with_native_roots()
1602/// #     .unwrap()
1603/// #     .https_only()
1604/// #     .enable_http2()
1605/// #     .build();
1606///
1607/// # let executor = hyper_util::rt::TokioExecutor::new();
1608/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1609/// #     secret,
1610/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1611/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1612/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1613/// #     ),
1614/// # ).build().await.unwrap();
1615///
1616/// # let client = hyper_util::client::legacy::Client::builder(
1617/// #     hyper_util::rt::TokioExecutor::new()
1618/// # )
1619/// # .build(
1620/// #     hyper_rustls::HttpsConnectorBuilder::new()
1621/// #         .with_native_roots()
1622/// #         .unwrap()
1623/// #         .https_or_http()
1624/// #         .enable_http2()
1625/// #         .build()
1626/// # );
1627/// # let mut hub = Datastore::new(client, auth);
1628/// // As the method needs a request, you would usually fill it with the desired information
1629/// // into the respective structure. Some of the parts shown here might not be applicable !
1630/// // Values shown here are possibly random and not representative !
1631/// let mut req = AllocateIdsRequest::default();
1632///
1633/// // You can configure optional parameters by calling the respective setters at will, and
1634/// // execute the final call using `doit()`.
1635/// // Values shown here are possibly random and not representative !
1636/// let result = hub.projects().allocate_ids(req, "projectId")
1637///              .doit().await;
1638/// # }
1639/// ```
1640pub struct ProjectAllocateIdCall<'a, C>
1641where
1642    C: 'a,
1643{
1644    hub: &'a Datastore<C>,
1645    _request: AllocateIdsRequest,
1646    _project_id: String,
1647    _delegate: Option<&'a mut dyn common::Delegate>,
1648    _additional_params: HashMap<String, String>,
1649    _scopes: BTreeSet<String>,
1650}
1651
1652impl<'a, C> common::CallBuilder for ProjectAllocateIdCall<'a, C> {}
1653
1654impl<'a, C> ProjectAllocateIdCall<'a, C>
1655where
1656    C: common::Connector,
1657{
1658    /// Perform the operation you have build so far.
1659    pub async fn doit(mut self) -> common::Result<(common::Response, AllocateIdsResponse)> {
1660        use std::borrow::Cow;
1661        use std::io::{Read, Seek};
1662
1663        use common::{url::Params, ToParts};
1664        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1665
1666        let mut dd = common::DefaultDelegate;
1667        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1668        dlg.begin(common::MethodInfo {
1669            id: "datastore.projects.allocateIds",
1670            http_method: hyper::Method::POST,
1671        });
1672
1673        for &field in ["alt", "projectId"].iter() {
1674            if self._additional_params.contains_key(field) {
1675                dlg.finished(false);
1676                return Err(common::Error::FieldClash(field));
1677            }
1678        }
1679
1680        let mut params = Params::with_capacity(4 + self._additional_params.len());
1681        params.push("projectId", self._project_id);
1682
1683        params.extend(self._additional_params.iter());
1684
1685        params.push("alt", "json");
1686        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:allocateIds";
1687        if self._scopes.is_empty() {
1688            self._scopes
1689                .insert(Scope::CloudPlatform.as_ref().to_string());
1690        }
1691
1692        #[allow(clippy::single_element_loop)]
1693        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
1694            url = params.uri_replacement(url, param_name, find_this, false);
1695        }
1696        {
1697            let to_remove = ["projectId"];
1698            params.remove_params(&to_remove);
1699        }
1700
1701        let url = params.parse_with_url(&url);
1702
1703        let mut json_mime_type = mime::APPLICATION_JSON;
1704        let mut request_value_reader = {
1705            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1706            common::remove_json_null_values(&mut value);
1707            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1708            serde_json::to_writer(&mut dst, &value).unwrap();
1709            dst
1710        };
1711        let request_size = request_value_reader
1712            .seek(std::io::SeekFrom::End(0))
1713            .unwrap();
1714        request_value_reader
1715            .seek(std::io::SeekFrom::Start(0))
1716            .unwrap();
1717
1718        loop {
1719            let token = match self
1720                .hub
1721                .auth
1722                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1723                .await
1724            {
1725                Ok(token) => token,
1726                Err(e) => match dlg.token(e) {
1727                    Ok(token) => token,
1728                    Err(e) => {
1729                        dlg.finished(false);
1730                        return Err(common::Error::MissingToken(e));
1731                    }
1732                },
1733            };
1734            request_value_reader
1735                .seek(std::io::SeekFrom::Start(0))
1736                .unwrap();
1737            let mut req_result = {
1738                let client = &self.hub.client;
1739                dlg.pre_request();
1740                let mut req_builder = hyper::Request::builder()
1741                    .method(hyper::Method::POST)
1742                    .uri(url.as_str())
1743                    .header(USER_AGENT, self.hub._user_agent.clone());
1744
1745                if let Some(token) = token.as_ref() {
1746                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1747                }
1748
1749                let request = req_builder
1750                    .header(CONTENT_TYPE, json_mime_type.to_string())
1751                    .header(CONTENT_LENGTH, request_size as u64)
1752                    .body(common::to_body(
1753                        request_value_reader.get_ref().clone().into(),
1754                    ));
1755
1756                client.request(request.unwrap()).await
1757            };
1758
1759            match req_result {
1760                Err(err) => {
1761                    if let common::Retry::After(d) = dlg.http_error(&err) {
1762                        sleep(d).await;
1763                        continue;
1764                    }
1765                    dlg.finished(false);
1766                    return Err(common::Error::HttpError(err));
1767                }
1768                Ok(res) => {
1769                    let (mut parts, body) = res.into_parts();
1770                    let mut body = common::Body::new(body);
1771                    if !parts.status.is_success() {
1772                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1773                        let error = serde_json::from_str(&common::to_string(&bytes));
1774                        let response = common::to_response(parts, bytes.into());
1775
1776                        if let common::Retry::After(d) =
1777                            dlg.http_failure(&response, error.as_ref().ok())
1778                        {
1779                            sleep(d).await;
1780                            continue;
1781                        }
1782
1783                        dlg.finished(false);
1784
1785                        return Err(match error {
1786                            Ok(value) => common::Error::BadRequest(value),
1787                            _ => common::Error::Failure(response),
1788                        });
1789                    }
1790                    let response = {
1791                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1792                        let encoded = common::to_string(&bytes);
1793                        match serde_json::from_str(&encoded) {
1794                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1795                            Err(error) => {
1796                                dlg.response_json_decode_error(&encoded, &error);
1797                                return Err(common::Error::JsonDecodeError(
1798                                    encoded.to_string(),
1799                                    error,
1800                                ));
1801                            }
1802                        }
1803                    };
1804
1805                    dlg.finished(true);
1806                    return Ok(response);
1807                }
1808            }
1809        }
1810    }
1811
1812    ///
1813    /// Sets the *request* property to the given value.
1814    ///
1815    /// Even though the property as already been set when instantiating this call,
1816    /// we provide this method for API completeness.
1817    pub fn request(mut self, new_value: AllocateIdsRequest) -> ProjectAllocateIdCall<'a, C> {
1818        self._request = new_value;
1819        self
1820    }
1821    /// Required. The ID of the project against which to make the request.
1822    ///
1823    /// Sets the *project id* path property to the given value.
1824    ///
1825    /// Even though the property as already been set when instantiating this call,
1826    /// we provide this method for API completeness.
1827    pub fn project_id(mut self, new_value: &str) -> ProjectAllocateIdCall<'a, C> {
1828        self._project_id = new_value.to_string();
1829        self
1830    }
1831    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1832    /// while executing the actual API request.
1833    ///
1834    /// ````text
1835    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1836    /// ````
1837    ///
1838    /// Sets the *delegate* property to the given value.
1839    pub fn delegate(
1840        mut self,
1841        new_value: &'a mut dyn common::Delegate,
1842    ) -> ProjectAllocateIdCall<'a, C> {
1843        self._delegate = Some(new_value);
1844        self
1845    }
1846
1847    /// Set any additional parameter of the query string used in the request.
1848    /// It should be used to set parameters which are not yet available through their own
1849    /// setters.
1850    ///
1851    /// Please note that this method must not be used to set any of the known parameters
1852    /// which have their own setter method. If done anyway, the request will fail.
1853    ///
1854    /// # Additional Parameters
1855    ///
1856    /// * *$.xgafv* (query-string) - V1 error format.
1857    /// * *access_token* (query-string) - OAuth access token.
1858    /// * *alt* (query-string) - Data format for response.
1859    /// * *callback* (query-string) - JSONP
1860    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1861    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1862    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1863    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1864    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1865    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1866    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1867    pub fn param<T>(mut self, name: T, value: T) -> ProjectAllocateIdCall<'a, C>
1868    where
1869        T: AsRef<str>,
1870    {
1871        self._additional_params
1872            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1873        self
1874    }
1875
1876    /// Identifies the authorization scope for the method you are building.
1877    ///
1878    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1879    /// [`Scope::CloudPlatform`].
1880    ///
1881    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1882    /// tokens for more than one scope.
1883    ///
1884    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1885    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1886    /// sufficient, a read-write scope will do as well.
1887    pub fn add_scope<St>(mut self, scope: St) -> ProjectAllocateIdCall<'a, C>
1888    where
1889        St: AsRef<str>,
1890    {
1891        self._scopes.insert(String::from(scope.as_ref()));
1892        self
1893    }
1894    /// Identifies the authorization scope(s) for the method you are building.
1895    ///
1896    /// See [`Self::add_scope()`] for details.
1897    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectAllocateIdCall<'a, C>
1898    where
1899        I: IntoIterator<Item = St>,
1900        St: AsRef<str>,
1901    {
1902        self._scopes
1903            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1904        self
1905    }
1906
1907    /// Removes all scopes, and no default scope will be used either.
1908    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1909    /// for details).
1910    pub fn clear_scopes(mut self) -> ProjectAllocateIdCall<'a, C> {
1911        self._scopes.clear();
1912        self
1913    }
1914}
1915
1916/// Begins a new transaction.
1917///
1918/// A builder for the *beginTransaction* method supported by a *project* resource.
1919/// It is not used directly, but through a [`ProjectMethods`] instance.
1920///
1921/// # Example
1922///
1923/// Instantiate a resource method builder
1924///
1925/// ```test_harness,no_run
1926/// # extern crate hyper;
1927/// # extern crate hyper_rustls;
1928/// # extern crate google_datastore1_beta3 as datastore1_beta3;
1929/// use datastore1_beta3::api::BeginTransactionRequest;
1930/// # async fn dox() {
1931/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1932///
1933/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1934/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1935/// #     .with_native_roots()
1936/// #     .unwrap()
1937/// #     .https_only()
1938/// #     .enable_http2()
1939/// #     .build();
1940///
1941/// # let executor = hyper_util::rt::TokioExecutor::new();
1942/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1943/// #     secret,
1944/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1945/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1946/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1947/// #     ),
1948/// # ).build().await.unwrap();
1949///
1950/// # let client = hyper_util::client::legacy::Client::builder(
1951/// #     hyper_util::rt::TokioExecutor::new()
1952/// # )
1953/// # .build(
1954/// #     hyper_rustls::HttpsConnectorBuilder::new()
1955/// #         .with_native_roots()
1956/// #         .unwrap()
1957/// #         .https_or_http()
1958/// #         .enable_http2()
1959/// #         .build()
1960/// # );
1961/// # let mut hub = Datastore::new(client, auth);
1962/// // As the method needs a request, you would usually fill it with the desired information
1963/// // into the respective structure. Some of the parts shown here might not be applicable !
1964/// // Values shown here are possibly random and not representative !
1965/// let mut req = BeginTransactionRequest::default();
1966///
1967/// // You can configure optional parameters by calling the respective setters at will, and
1968/// // execute the final call using `doit()`.
1969/// // Values shown here are possibly random and not representative !
1970/// let result = hub.projects().begin_transaction(req, "projectId")
1971///              .doit().await;
1972/// # }
1973/// ```
1974pub struct ProjectBeginTransactionCall<'a, C>
1975where
1976    C: 'a,
1977{
1978    hub: &'a Datastore<C>,
1979    _request: BeginTransactionRequest,
1980    _project_id: String,
1981    _delegate: Option<&'a mut dyn common::Delegate>,
1982    _additional_params: HashMap<String, String>,
1983    _scopes: BTreeSet<String>,
1984}
1985
1986impl<'a, C> common::CallBuilder for ProjectBeginTransactionCall<'a, C> {}
1987
1988impl<'a, C> ProjectBeginTransactionCall<'a, C>
1989where
1990    C: common::Connector,
1991{
1992    /// Perform the operation you have build so far.
1993    pub async fn doit(mut self) -> common::Result<(common::Response, BeginTransactionResponse)> {
1994        use std::borrow::Cow;
1995        use std::io::{Read, Seek};
1996
1997        use common::{url::Params, ToParts};
1998        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1999
2000        let mut dd = common::DefaultDelegate;
2001        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2002        dlg.begin(common::MethodInfo {
2003            id: "datastore.projects.beginTransaction",
2004            http_method: hyper::Method::POST,
2005        });
2006
2007        for &field in ["alt", "projectId"].iter() {
2008            if self._additional_params.contains_key(field) {
2009                dlg.finished(false);
2010                return Err(common::Error::FieldClash(field));
2011            }
2012        }
2013
2014        let mut params = Params::with_capacity(4 + self._additional_params.len());
2015        params.push("projectId", self._project_id);
2016
2017        params.extend(self._additional_params.iter());
2018
2019        params.push("alt", "json");
2020        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:beginTransaction";
2021        if self._scopes.is_empty() {
2022            self._scopes
2023                .insert(Scope::CloudPlatform.as_ref().to_string());
2024        }
2025
2026        #[allow(clippy::single_element_loop)]
2027        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
2028            url = params.uri_replacement(url, param_name, find_this, false);
2029        }
2030        {
2031            let to_remove = ["projectId"];
2032            params.remove_params(&to_remove);
2033        }
2034
2035        let url = params.parse_with_url(&url);
2036
2037        let mut json_mime_type = mime::APPLICATION_JSON;
2038        let mut request_value_reader = {
2039            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2040            common::remove_json_null_values(&mut value);
2041            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2042            serde_json::to_writer(&mut dst, &value).unwrap();
2043            dst
2044        };
2045        let request_size = request_value_reader
2046            .seek(std::io::SeekFrom::End(0))
2047            .unwrap();
2048        request_value_reader
2049            .seek(std::io::SeekFrom::Start(0))
2050            .unwrap();
2051
2052        loop {
2053            let token = match self
2054                .hub
2055                .auth
2056                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2057                .await
2058            {
2059                Ok(token) => token,
2060                Err(e) => match dlg.token(e) {
2061                    Ok(token) => token,
2062                    Err(e) => {
2063                        dlg.finished(false);
2064                        return Err(common::Error::MissingToken(e));
2065                    }
2066                },
2067            };
2068            request_value_reader
2069                .seek(std::io::SeekFrom::Start(0))
2070                .unwrap();
2071            let mut req_result = {
2072                let client = &self.hub.client;
2073                dlg.pre_request();
2074                let mut req_builder = hyper::Request::builder()
2075                    .method(hyper::Method::POST)
2076                    .uri(url.as_str())
2077                    .header(USER_AGENT, self.hub._user_agent.clone());
2078
2079                if let Some(token) = token.as_ref() {
2080                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2081                }
2082
2083                let request = req_builder
2084                    .header(CONTENT_TYPE, json_mime_type.to_string())
2085                    .header(CONTENT_LENGTH, request_size as u64)
2086                    .body(common::to_body(
2087                        request_value_reader.get_ref().clone().into(),
2088                    ));
2089
2090                client.request(request.unwrap()).await
2091            };
2092
2093            match req_result {
2094                Err(err) => {
2095                    if let common::Retry::After(d) = dlg.http_error(&err) {
2096                        sleep(d).await;
2097                        continue;
2098                    }
2099                    dlg.finished(false);
2100                    return Err(common::Error::HttpError(err));
2101                }
2102                Ok(res) => {
2103                    let (mut parts, body) = res.into_parts();
2104                    let mut body = common::Body::new(body);
2105                    if !parts.status.is_success() {
2106                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2107                        let error = serde_json::from_str(&common::to_string(&bytes));
2108                        let response = common::to_response(parts, bytes.into());
2109
2110                        if let common::Retry::After(d) =
2111                            dlg.http_failure(&response, error.as_ref().ok())
2112                        {
2113                            sleep(d).await;
2114                            continue;
2115                        }
2116
2117                        dlg.finished(false);
2118
2119                        return Err(match error {
2120                            Ok(value) => common::Error::BadRequest(value),
2121                            _ => common::Error::Failure(response),
2122                        });
2123                    }
2124                    let response = {
2125                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2126                        let encoded = common::to_string(&bytes);
2127                        match serde_json::from_str(&encoded) {
2128                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2129                            Err(error) => {
2130                                dlg.response_json_decode_error(&encoded, &error);
2131                                return Err(common::Error::JsonDecodeError(
2132                                    encoded.to_string(),
2133                                    error,
2134                                ));
2135                            }
2136                        }
2137                    };
2138
2139                    dlg.finished(true);
2140                    return Ok(response);
2141                }
2142            }
2143        }
2144    }
2145
2146    ///
2147    /// Sets the *request* property to the given value.
2148    ///
2149    /// Even though the property as already been set when instantiating this call,
2150    /// we provide this method for API completeness.
2151    pub fn request(
2152        mut self,
2153        new_value: BeginTransactionRequest,
2154    ) -> ProjectBeginTransactionCall<'a, C> {
2155        self._request = new_value;
2156        self
2157    }
2158    /// Required. The ID of the project against which to make the request.
2159    ///
2160    /// Sets the *project id* path property to the given value.
2161    ///
2162    /// Even though the property as already been set when instantiating this call,
2163    /// we provide this method for API completeness.
2164    pub fn project_id(mut self, new_value: &str) -> ProjectBeginTransactionCall<'a, C> {
2165        self._project_id = new_value.to_string();
2166        self
2167    }
2168    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2169    /// while executing the actual API request.
2170    ///
2171    /// ````text
2172    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2173    /// ````
2174    ///
2175    /// Sets the *delegate* property to the given value.
2176    pub fn delegate(
2177        mut self,
2178        new_value: &'a mut dyn common::Delegate,
2179    ) -> ProjectBeginTransactionCall<'a, C> {
2180        self._delegate = Some(new_value);
2181        self
2182    }
2183
2184    /// Set any additional parameter of the query string used in the request.
2185    /// It should be used to set parameters which are not yet available through their own
2186    /// setters.
2187    ///
2188    /// Please note that this method must not be used to set any of the known parameters
2189    /// which have their own setter method. If done anyway, the request will fail.
2190    ///
2191    /// # Additional Parameters
2192    ///
2193    /// * *$.xgafv* (query-string) - V1 error format.
2194    /// * *access_token* (query-string) - OAuth access token.
2195    /// * *alt* (query-string) - Data format for response.
2196    /// * *callback* (query-string) - JSONP
2197    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2198    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2199    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2200    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2201    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2202    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2203    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2204    pub fn param<T>(mut self, name: T, value: T) -> ProjectBeginTransactionCall<'a, C>
2205    where
2206        T: AsRef<str>,
2207    {
2208        self._additional_params
2209            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2210        self
2211    }
2212
2213    /// Identifies the authorization scope for the method you are building.
2214    ///
2215    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2216    /// [`Scope::CloudPlatform`].
2217    ///
2218    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2219    /// tokens for more than one scope.
2220    ///
2221    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2222    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2223    /// sufficient, a read-write scope will do as well.
2224    pub fn add_scope<St>(mut self, scope: St) -> ProjectBeginTransactionCall<'a, C>
2225    where
2226        St: AsRef<str>,
2227    {
2228        self._scopes.insert(String::from(scope.as_ref()));
2229        self
2230    }
2231    /// Identifies the authorization scope(s) for the method you are building.
2232    ///
2233    /// See [`Self::add_scope()`] for details.
2234    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectBeginTransactionCall<'a, C>
2235    where
2236        I: IntoIterator<Item = St>,
2237        St: AsRef<str>,
2238    {
2239        self._scopes
2240            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2241        self
2242    }
2243
2244    /// Removes all scopes, and no default scope will be used either.
2245    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2246    /// for details).
2247    pub fn clear_scopes(mut self) -> ProjectBeginTransactionCall<'a, C> {
2248        self._scopes.clear();
2249        self
2250    }
2251}
2252
2253/// Commits a transaction, optionally creating, deleting or modifying some entities.
2254///
2255/// A builder for the *commit* method supported by a *project* resource.
2256/// It is not used directly, but through a [`ProjectMethods`] instance.
2257///
2258/// # Example
2259///
2260/// Instantiate a resource method builder
2261///
2262/// ```test_harness,no_run
2263/// # extern crate hyper;
2264/// # extern crate hyper_rustls;
2265/// # extern crate google_datastore1_beta3 as datastore1_beta3;
2266/// use datastore1_beta3::api::CommitRequest;
2267/// # async fn dox() {
2268/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2269///
2270/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2271/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2272/// #     .with_native_roots()
2273/// #     .unwrap()
2274/// #     .https_only()
2275/// #     .enable_http2()
2276/// #     .build();
2277///
2278/// # let executor = hyper_util::rt::TokioExecutor::new();
2279/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2280/// #     secret,
2281/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2282/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
2283/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
2284/// #     ),
2285/// # ).build().await.unwrap();
2286///
2287/// # let client = hyper_util::client::legacy::Client::builder(
2288/// #     hyper_util::rt::TokioExecutor::new()
2289/// # )
2290/// # .build(
2291/// #     hyper_rustls::HttpsConnectorBuilder::new()
2292/// #         .with_native_roots()
2293/// #         .unwrap()
2294/// #         .https_or_http()
2295/// #         .enable_http2()
2296/// #         .build()
2297/// # );
2298/// # let mut hub = Datastore::new(client, auth);
2299/// // As the method needs a request, you would usually fill it with the desired information
2300/// // into the respective structure. Some of the parts shown here might not be applicable !
2301/// // Values shown here are possibly random and not representative !
2302/// let mut req = CommitRequest::default();
2303///
2304/// // You can configure optional parameters by calling the respective setters at will, and
2305/// // execute the final call using `doit()`.
2306/// // Values shown here are possibly random and not representative !
2307/// let result = hub.projects().commit(req, "projectId")
2308///              .doit().await;
2309/// # }
2310/// ```
2311pub struct ProjectCommitCall<'a, C>
2312where
2313    C: 'a,
2314{
2315    hub: &'a Datastore<C>,
2316    _request: CommitRequest,
2317    _project_id: String,
2318    _delegate: Option<&'a mut dyn common::Delegate>,
2319    _additional_params: HashMap<String, String>,
2320    _scopes: BTreeSet<String>,
2321}
2322
2323impl<'a, C> common::CallBuilder for ProjectCommitCall<'a, C> {}
2324
2325impl<'a, C> ProjectCommitCall<'a, C>
2326where
2327    C: common::Connector,
2328{
2329    /// Perform the operation you have build so far.
2330    pub async fn doit(mut self) -> common::Result<(common::Response, CommitResponse)> {
2331        use std::borrow::Cow;
2332        use std::io::{Read, Seek};
2333
2334        use common::{url::Params, ToParts};
2335        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2336
2337        let mut dd = common::DefaultDelegate;
2338        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2339        dlg.begin(common::MethodInfo {
2340            id: "datastore.projects.commit",
2341            http_method: hyper::Method::POST,
2342        });
2343
2344        for &field in ["alt", "projectId"].iter() {
2345            if self._additional_params.contains_key(field) {
2346                dlg.finished(false);
2347                return Err(common::Error::FieldClash(field));
2348            }
2349        }
2350
2351        let mut params = Params::with_capacity(4 + self._additional_params.len());
2352        params.push("projectId", self._project_id);
2353
2354        params.extend(self._additional_params.iter());
2355
2356        params.push("alt", "json");
2357        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:commit";
2358        if self._scopes.is_empty() {
2359            self._scopes
2360                .insert(Scope::CloudPlatform.as_ref().to_string());
2361        }
2362
2363        #[allow(clippy::single_element_loop)]
2364        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
2365            url = params.uri_replacement(url, param_name, find_this, false);
2366        }
2367        {
2368            let to_remove = ["projectId"];
2369            params.remove_params(&to_remove);
2370        }
2371
2372        let url = params.parse_with_url(&url);
2373
2374        let mut json_mime_type = mime::APPLICATION_JSON;
2375        let mut request_value_reader = {
2376            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2377            common::remove_json_null_values(&mut value);
2378            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2379            serde_json::to_writer(&mut dst, &value).unwrap();
2380            dst
2381        };
2382        let request_size = request_value_reader
2383            .seek(std::io::SeekFrom::End(0))
2384            .unwrap();
2385        request_value_reader
2386            .seek(std::io::SeekFrom::Start(0))
2387            .unwrap();
2388
2389        loop {
2390            let token = match self
2391                .hub
2392                .auth
2393                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2394                .await
2395            {
2396                Ok(token) => token,
2397                Err(e) => match dlg.token(e) {
2398                    Ok(token) => token,
2399                    Err(e) => {
2400                        dlg.finished(false);
2401                        return Err(common::Error::MissingToken(e));
2402                    }
2403                },
2404            };
2405            request_value_reader
2406                .seek(std::io::SeekFrom::Start(0))
2407                .unwrap();
2408            let mut req_result = {
2409                let client = &self.hub.client;
2410                dlg.pre_request();
2411                let mut req_builder = hyper::Request::builder()
2412                    .method(hyper::Method::POST)
2413                    .uri(url.as_str())
2414                    .header(USER_AGENT, self.hub._user_agent.clone());
2415
2416                if let Some(token) = token.as_ref() {
2417                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2418                }
2419
2420                let request = req_builder
2421                    .header(CONTENT_TYPE, json_mime_type.to_string())
2422                    .header(CONTENT_LENGTH, request_size as u64)
2423                    .body(common::to_body(
2424                        request_value_reader.get_ref().clone().into(),
2425                    ));
2426
2427                client.request(request.unwrap()).await
2428            };
2429
2430            match req_result {
2431                Err(err) => {
2432                    if let common::Retry::After(d) = dlg.http_error(&err) {
2433                        sleep(d).await;
2434                        continue;
2435                    }
2436                    dlg.finished(false);
2437                    return Err(common::Error::HttpError(err));
2438                }
2439                Ok(res) => {
2440                    let (mut parts, body) = res.into_parts();
2441                    let mut body = common::Body::new(body);
2442                    if !parts.status.is_success() {
2443                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2444                        let error = serde_json::from_str(&common::to_string(&bytes));
2445                        let response = common::to_response(parts, bytes.into());
2446
2447                        if let common::Retry::After(d) =
2448                            dlg.http_failure(&response, error.as_ref().ok())
2449                        {
2450                            sleep(d).await;
2451                            continue;
2452                        }
2453
2454                        dlg.finished(false);
2455
2456                        return Err(match error {
2457                            Ok(value) => common::Error::BadRequest(value),
2458                            _ => common::Error::Failure(response),
2459                        });
2460                    }
2461                    let response = {
2462                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2463                        let encoded = common::to_string(&bytes);
2464                        match serde_json::from_str(&encoded) {
2465                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2466                            Err(error) => {
2467                                dlg.response_json_decode_error(&encoded, &error);
2468                                return Err(common::Error::JsonDecodeError(
2469                                    encoded.to_string(),
2470                                    error,
2471                                ));
2472                            }
2473                        }
2474                    };
2475
2476                    dlg.finished(true);
2477                    return Ok(response);
2478                }
2479            }
2480        }
2481    }
2482
2483    ///
2484    /// Sets the *request* property to the given value.
2485    ///
2486    /// Even though the property as already been set when instantiating this call,
2487    /// we provide this method for API completeness.
2488    pub fn request(mut self, new_value: CommitRequest) -> ProjectCommitCall<'a, C> {
2489        self._request = new_value;
2490        self
2491    }
2492    /// Required. The ID of the project against which to make the request.
2493    ///
2494    /// Sets the *project id* path property to the given value.
2495    ///
2496    /// Even though the property as already been set when instantiating this call,
2497    /// we provide this method for API completeness.
2498    pub fn project_id(mut self, new_value: &str) -> ProjectCommitCall<'a, C> {
2499        self._project_id = new_value.to_string();
2500        self
2501    }
2502    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2503    /// while executing the actual API request.
2504    ///
2505    /// ````text
2506    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2507    /// ````
2508    ///
2509    /// Sets the *delegate* property to the given value.
2510    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ProjectCommitCall<'a, C> {
2511        self._delegate = Some(new_value);
2512        self
2513    }
2514
2515    /// Set any additional parameter of the query string used in the request.
2516    /// It should be used to set parameters which are not yet available through their own
2517    /// setters.
2518    ///
2519    /// Please note that this method must not be used to set any of the known parameters
2520    /// which have their own setter method. If done anyway, the request will fail.
2521    ///
2522    /// # Additional Parameters
2523    ///
2524    /// * *$.xgafv* (query-string) - V1 error format.
2525    /// * *access_token* (query-string) - OAuth access token.
2526    /// * *alt* (query-string) - Data format for response.
2527    /// * *callback* (query-string) - JSONP
2528    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2529    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2530    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2531    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2532    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2533    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2534    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2535    pub fn param<T>(mut self, name: T, value: T) -> ProjectCommitCall<'a, C>
2536    where
2537        T: AsRef<str>,
2538    {
2539        self._additional_params
2540            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2541        self
2542    }
2543
2544    /// Identifies the authorization scope for the method you are building.
2545    ///
2546    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2547    /// [`Scope::CloudPlatform`].
2548    ///
2549    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2550    /// tokens for more than one scope.
2551    ///
2552    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2553    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2554    /// sufficient, a read-write scope will do as well.
2555    pub fn add_scope<St>(mut self, scope: St) -> ProjectCommitCall<'a, C>
2556    where
2557        St: AsRef<str>,
2558    {
2559        self._scopes.insert(String::from(scope.as_ref()));
2560        self
2561    }
2562    /// Identifies the authorization scope(s) for the method you are building.
2563    ///
2564    /// See [`Self::add_scope()`] for details.
2565    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectCommitCall<'a, C>
2566    where
2567        I: IntoIterator<Item = St>,
2568        St: AsRef<str>,
2569    {
2570        self._scopes
2571            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2572        self
2573    }
2574
2575    /// Removes all scopes, and no default scope will be used either.
2576    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2577    /// for details).
2578    pub fn clear_scopes(mut self) -> ProjectCommitCall<'a, C> {
2579        self._scopes.clear();
2580        self
2581    }
2582}
2583
2584/// Looks up entities by key.
2585///
2586/// A builder for the *lookup* method supported by a *project* resource.
2587/// It is not used directly, but through a [`ProjectMethods`] instance.
2588///
2589/// # Example
2590///
2591/// Instantiate a resource method builder
2592///
2593/// ```test_harness,no_run
2594/// # extern crate hyper;
2595/// # extern crate hyper_rustls;
2596/// # extern crate google_datastore1_beta3 as datastore1_beta3;
2597/// use datastore1_beta3::api::LookupRequest;
2598/// # async fn dox() {
2599/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2600///
2601/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2602/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2603/// #     .with_native_roots()
2604/// #     .unwrap()
2605/// #     .https_only()
2606/// #     .enable_http2()
2607/// #     .build();
2608///
2609/// # let executor = hyper_util::rt::TokioExecutor::new();
2610/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2611/// #     secret,
2612/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2613/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
2614/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
2615/// #     ),
2616/// # ).build().await.unwrap();
2617///
2618/// # let client = hyper_util::client::legacy::Client::builder(
2619/// #     hyper_util::rt::TokioExecutor::new()
2620/// # )
2621/// # .build(
2622/// #     hyper_rustls::HttpsConnectorBuilder::new()
2623/// #         .with_native_roots()
2624/// #         .unwrap()
2625/// #         .https_or_http()
2626/// #         .enable_http2()
2627/// #         .build()
2628/// # );
2629/// # let mut hub = Datastore::new(client, auth);
2630/// // As the method needs a request, you would usually fill it with the desired information
2631/// // into the respective structure. Some of the parts shown here might not be applicable !
2632/// // Values shown here are possibly random and not representative !
2633/// let mut req = LookupRequest::default();
2634///
2635/// // You can configure optional parameters by calling the respective setters at will, and
2636/// // execute the final call using `doit()`.
2637/// // Values shown here are possibly random and not representative !
2638/// let result = hub.projects().lookup(req, "projectId")
2639///              .doit().await;
2640/// # }
2641/// ```
2642pub struct ProjectLookupCall<'a, C>
2643where
2644    C: 'a,
2645{
2646    hub: &'a Datastore<C>,
2647    _request: LookupRequest,
2648    _project_id: String,
2649    _delegate: Option<&'a mut dyn common::Delegate>,
2650    _additional_params: HashMap<String, String>,
2651    _scopes: BTreeSet<String>,
2652}
2653
2654impl<'a, C> common::CallBuilder for ProjectLookupCall<'a, C> {}
2655
2656impl<'a, C> ProjectLookupCall<'a, C>
2657where
2658    C: common::Connector,
2659{
2660    /// Perform the operation you have build so far.
2661    pub async fn doit(mut self) -> common::Result<(common::Response, LookupResponse)> {
2662        use std::borrow::Cow;
2663        use std::io::{Read, Seek};
2664
2665        use common::{url::Params, ToParts};
2666        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2667
2668        let mut dd = common::DefaultDelegate;
2669        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2670        dlg.begin(common::MethodInfo {
2671            id: "datastore.projects.lookup",
2672            http_method: hyper::Method::POST,
2673        });
2674
2675        for &field in ["alt", "projectId"].iter() {
2676            if self._additional_params.contains_key(field) {
2677                dlg.finished(false);
2678                return Err(common::Error::FieldClash(field));
2679            }
2680        }
2681
2682        let mut params = Params::with_capacity(4 + self._additional_params.len());
2683        params.push("projectId", self._project_id);
2684
2685        params.extend(self._additional_params.iter());
2686
2687        params.push("alt", "json");
2688        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:lookup";
2689        if self._scopes.is_empty() {
2690            self._scopes
2691                .insert(Scope::CloudPlatform.as_ref().to_string());
2692        }
2693
2694        #[allow(clippy::single_element_loop)]
2695        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
2696            url = params.uri_replacement(url, param_name, find_this, false);
2697        }
2698        {
2699            let to_remove = ["projectId"];
2700            params.remove_params(&to_remove);
2701        }
2702
2703        let url = params.parse_with_url(&url);
2704
2705        let mut json_mime_type = mime::APPLICATION_JSON;
2706        let mut request_value_reader = {
2707            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2708            common::remove_json_null_values(&mut value);
2709            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2710            serde_json::to_writer(&mut dst, &value).unwrap();
2711            dst
2712        };
2713        let request_size = request_value_reader
2714            .seek(std::io::SeekFrom::End(0))
2715            .unwrap();
2716        request_value_reader
2717            .seek(std::io::SeekFrom::Start(0))
2718            .unwrap();
2719
2720        loop {
2721            let token = match self
2722                .hub
2723                .auth
2724                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2725                .await
2726            {
2727                Ok(token) => token,
2728                Err(e) => match dlg.token(e) {
2729                    Ok(token) => token,
2730                    Err(e) => {
2731                        dlg.finished(false);
2732                        return Err(common::Error::MissingToken(e));
2733                    }
2734                },
2735            };
2736            request_value_reader
2737                .seek(std::io::SeekFrom::Start(0))
2738                .unwrap();
2739            let mut req_result = {
2740                let client = &self.hub.client;
2741                dlg.pre_request();
2742                let mut req_builder = hyper::Request::builder()
2743                    .method(hyper::Method::POST)
2744                    .uri(url.as_str())
2745                    .header(USER_AGENT, self.hub._user_agent.clone());
2746
2747                if let Some(token) = token.as_ref() {
2748                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2749                }
2750
2751                let request = req_builder
2752                    .header(CONTENT_TYPE, json_mime_type.to_string())
2753                    .header(CONTENT_LENGTH, request_size as u64)
2754                    .body(common::to_body(
2755                        request_value_reader.get_ref().clone().into(),
2756                    ));
2757
2758                client.request(request.unwrap()).await
2759            };
2760
2761            match req_result {
2762                Err(err) => {
2763                    if let common::Retry::After(d) = dlg.http_error(&err) {
2764                        sleep(d).await;
2765                        continue;
2766                    }
2767                    dlg.finished(false);
2768                    return Err(common::Error::HttpError(err));
2769                }
2770                Ok(res) => {
2771                    let (mut parts, body) = res.into_parts();
2772                    let mut body = common::Body::new(body);
2773                    if !parts.status.is_success() {
2774                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2775                        let error = serde_json::from_str(&common::to_string(&bytes));
2776                        let response = common::to_response(parts, bytes.into());
2777
2778                        if let common::Retry::After(d) =
2779                            dlg.http_failure(&response, error.as_ref().ok())
2780                        {
2781                            sleep(d).await;
2782                            continue;
2783                        }
2784
2785                        dlg.finished(false);
2786
2787                        return Err(match error {
2788                            Ok(value) => common::Error::BadRequest(value),
2789                            _ => common::Error::Failure(response),
2790                        });
2791                    }
2792                    let response = {
2793                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2794                        let encoded = common::to_string(&bytes);
2795                        match serde_json::from_str(&encoded) {
2796                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2797                            Err(error) => {
2798                                dlg.response_json_decode_error(&encoded, &error);
2799                                return Err(common::Error::JsonDecodeError(
2800                                    encoded.to_string(),
2801                                    error,
2802                                ));
2803                            }
2804                        }
2805                    };
2806
2807                    dlg.finished(true);
2808                    return Ok(response);
2809                }
2810            }
2811        }
2812    }
2813
2814    ///
2815    /// Sets the *request* property to the given value.
2816    ///
2817    /// Even though the property as already been set when instantiating this call,
2818    /// we provide this method for API completeness.
2819    pub fn request(mut self, new_value: LookupRequest) -> ProjectLookupCall<'a, C> {
2820        self._request = new_value;
2821        self
2822    }
2823    /// Required. The ID of the project against which to make the request.
2824    ///
2825    /// Sets the *project id* path property to the given value.
2826    ///
2827    /// Even though the property as already been set when instantiating this call,
2828    /// we provide this method for API completeness.
2829    pub fn project_id(mut self, new_value: &str) -> ProjectLookupCall<'a, C> {
2830        self._project_id = new_value.to_string();
2831        self
2832    }
2833    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2834    /// while executing the actual API request.
2835    ///
2836    /// ````text
2837    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2838    /// ````
2839    ///
2840    /// Sets the *delegate* property to the given value.
2841    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ProjectLookupCall<'a, C> {
2842        self._delegate = Some(new_value);
2843        self
2844    }
2845
2846    /// Set any additional parameter of the query string used in the request.
2847    /// It should be used to set parameters which are not yet available through their own
2848    /// setters.
2849    ///
2850    /// Please note that this method must not be used to set any of the known parameters
2851    /// which have their own setter method. If done anyway, the request will fail.
2852    ///
2853    /// # Additional Parameters
2854    ///
2855    /// * *$.xgafv* (query-string) - V1 error format.
2856    /// * *access_token* (query-string) - OAuth access token.
2857    /// * *alt* (query-string) - Data format for response.
2858    /// * *callback* (query-string) - JSONP
2859    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2860    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2861    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2862    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2863    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2864    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2865    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2866    pub fn param<T>(mut self, name: T, value: T) -> ProjectLookupCall<'a, C>
2867    where
2868        T: AsRef<str>,
2869    {
2870        self._additional_params
2871            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2872        self
2873    }
2874
2875    /// Identifies the authorization scope for the method you are building.
2876    ///
2877    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2878    /// [`Scope::CloudPlatform`].
2879    ///
2880    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2881    /// tokens for more than one scope.
2882    ///
2883    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2884    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2885    /// sufficient, a read-write scope will do as well.
2886    pub fn add_scope<St>(mut self, scope: St) -> ProjectLookupCall<'a, C>
2887    where
2888        St: AsRef<str>,
2889    {
2890        self._scopes.insert(String::from(scope.as_ref()));
2891        self
2892    }
2893    /// Identifies the authorization scope(s) for the method you are building.
2894    ///
2895    /// See [`Self::add_scope()`] for details.
2896    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLookupCall<'a, C>
2897    where
2898        I: IntoIterator<Item = St>,
2899        St: AsRef<str>,
2900    {
2901        self._scopes
2902            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2903        self
2904    }
2905
2906    /// Removes all scopes, and no default scope will be used either.
2907    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2908    /// for details).
2909    pub fn clear_scopes(mut self) -> ProjectLookupCall<'a, C> {
2910        self._scopes.clear();
2911        self
2912    }
2913}
2914
2915/// Prevents the supplied keys' IDs from being auto-allocated by Cloud Datastore.
2916///
2917/// A builder for the *reserveIds* method supported by a *project* resource.
2918/// It is not used directly, but through a [`ProjectMethods`] instance.
2919///
2920/// # Example
2921///
2922/// Instantiate a resource method builder
2923///
2924/// ```test_harness,no_run
2925/// # extern crate hyper;
2926/// # extern crate hyper_rustls;
2927/// # extern crate google_datastore1_beta3 as datastore1_beta3;
2928/// use datastore1_beta3::api::ReserveIdsRequest;
2929/// # async fn dox() {
2930/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2931///
2932/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2933/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2934/// #     .with_native_roots()
2935/// #     .unwrap()
2936/// #     .https_only()
2937/// #     .enable_http2()
2938/// #     .build();
2939///
2940/// # let executor = hyper_util::rt::TokioExecutor::new();
2941/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2942/// #     secret,
2943/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2944/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
2945/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
2946/// #     ),
2947/// # ).build().await.unwrap();
2948///
2949/// # let client = hyper_util::client::legacy::Client::builder(
2950/// #     hyper_util::rt::TokioExecutor::new()
2951/// # )
2952/// # .build(
2953/// #     hyper_rustls::HttpsConnectorBuilder::new()
2954/// #         .with_native_roots()
2955/// #         .unwrap()
2956/// #         .https_or_http()
2957/// #         .enable_http2()
2958/// #         .build()
2959/// # );
2960/// # let mut hub = Datastore::new(client, auth);
2961/// // As the method needs a request, you would usually fill it with the desired information
2962/// // into the respective structure. Some of the parts shown here might not be applicable !
2963/// // Values shown here are possibly random and not representative !
2964/// let mut req = ReserveIdsRequest::default();
2965///
2966/// // You can configure optional parameters by calling the respective setters at will, and
2967/// // execute the final call using `doit()`.
2968/// // Values shown here are possibly random and not representative !
2969/// let result = hub.projects().reserve_ids(req, "projectId")
2970///              .doit().await;
2971/// # }
2972/// ```
2973pub struct ProjectReserveIdCall<'a, C>
2974where
2975    C: 'a,
2976{
2977    hub: &'a Datastore<C>,
2978    _request: ReserveIdsRequest,
2979    _project_id: String,
2980    _delegate: Option<&'a mut dyn common::Delegate>,
2981    _additional_params: HashMap<String, String>,
2982    _scopes: BTreeSet<String>,
2983}
2984
2985impl<'a, C> common::CallBuilder for ProjectReserveIdCall<'a, C> {}
2986
2987impl<'a, C> ProjectReserveIdCall<'a, C>
2988where
2989    C: common::Connector,
2990{
2991    /// Perform the operation you have build so far.
2992    pub async fn doit(mut self) -> common::Result<(common::Response, ReserveIdsResponse)> {
2993        use std::borrow::Cow;
2994        use std::io::{Read, Seek};
2995
2996        use common::{url::Params, ToParts};
2997        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2998
2999        let mut dd = common::DefaultDelegate;
3000        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3001        dlg.begin(common::MethodInfo {
3002            id: "datastore.projects.reserveIds",
3003            http_method: hyper::Method::POST,
3004        });
3005
3006        for &field in ["alt", "projectId"].iter() {
3007            if self._additional_params.contains_key(field) {
3008                dlg.finished(false);
3009                return Err(common::Error::FieldClash(field));
3010            }
3011        }
3012
3013        let mut params = Params::with_capacity(4 + self._additional_params.len());
3014        params.push("projectId", self._project_id);
3015
3016        params.extend(self._additional_params.iter());
3017
3018        params.push("alt", "json");
3019        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:reserveIds";
3020        if self._scopes.is_empty() {
3021            self._scopes
3022                .insert(Scope::CloudPlatform.as_ref().to_string());
3023        }
3024
3025        #[allow(clippy::single_element_loop)]
3026        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
3027            url = params.uri_replacement(url, param_name, find_this, false);
3028        }
3029        {
3030            let to_remove = ["projectId"];
3031            params.remove_params(&to_remove);
3032        }
3033
3034        let url = params.parse_with_url(&url);
3035
3036        let mut json_mime_type = mime::APPLICATION_JSON;
3037        let mut request_value_reader = {
3038            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3039            common::remove_json_null_values(&mut value);
3040            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3041            serde_json::to_writer(&mut dst, &value).unwrap();
3042            dst
3043        };
3044        let request_size = request_value_reader
3045            .seek(std::io::SeekFrom::End(0))
3046            .unwrap();
3047        request_value_reader
3048            .seek(std::io::SeekFrom::Start(0))
3049            .unwrap();
3050
3051        loop {
3052            let token = match self
3053                .hub
3054                .auth
3055                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3056                .await
3057            {
3058                Ok(token) => token,
3059                Err(e) => match dlg.token(e) {
3060                    Ok(token) => token,
3061                    Err(e) => {
3062                        dlg.finished(false);
3063                        return Err(common::Error::MissingToken(e));
3064                    }
3065                },
3066            };
3067            request_value_reader
3068                .seek(std::io::SeekFrom::Start(0))
3069                .unwrap();
3070            let mut req_result = {
3071                let client = &self.hub.client;
3072                dlg.pre_request();
3073                let mut req_builder = hyper::Request::builder()
3074                    .method(hyper::Method::POST)
3075                    .uri(url.as_str())
3076                    .header(USER_AGENT, self.hub._user_agent.clone());
3077
3078                if let Some(token) = token.as_ref() {
3079                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3080                }
3081
3082                let request = req_builder
3083                    .header(CONTENT_TYPE, json_mime_type.to_string())
3084                    .header(CONTENT_LENGTH, request_size as u64)
3085                    .body(common::to_body(
3086                        request_value_reader.get_ref().clone().into(),
3087                    ));
3088
3089                client.request(request.unwrap()).await
3090            };
3091
3092            match req_result {
3093                Err(err) => {
3094                    if let common::Retry::After(d) = dlg.http_error(&err) {
3095                        sleep(d).await;
3096                        continue;
3097                    }
3098                    dlg.finished(false);
3099                    return Err(common::Error::HttpError(err));
3100                }
3101                Ok(res) => {
3102                    let (mut parts, body) = res.into_parts();
3103                    let mut body = common::Body::new(body);
3104                    if !parts.status.is_success() {
3105                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3106                        let error = serde_json::from_str(&common::to_string(&bytes));
3107                        let response = common::to_response(parts, bytes.into());
3108
3109                        if let common::Retry::After(d) =
3110                            dlg.http_failure(&response, error.as_ref().ok())
3111                        {
3112                            sleep(d).await;
3113                            continue;
3114                        }
3115
3116                        dlg.finished(false);
3117
3118                        return Err(match error {
3119                            Ok(value) => common::Error::BadRequest(value),
3120                            _ => common::Error::Failure(response),
3121                        });
3122                    }
3123                    let response = {
3124                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3125                        let encoded = common::to_string(&bytes);
3126                        match serde_json::from_str(&encoded) {
3127                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3128                            Err(error) => {
3129                                dlg.response_json_decode_error(&encoded, &error);
3130                                return Err(common::Error::JsonDecodeError(
3131                                    encoded.to_string(),
3132                                    error,
3133                                ));
3134                            }
3135                        }
3136                    };
3137
3138                    dlg.finished(true);
3139                    return Ok(response);
3140                }
3141            }
3142        }
3143    }
3144
3145    ///
3146    /// Sets the *request* property to the given value.
3147    ///
3148    /// Even though the property as already been set when instantiating this call,
3149    /// we provide this method for API completeness.
3150    pub fn request(mut self, new_value: ReserveIdsRequest) -> ProjectReserveIdCall<'a, C> {
3151        self._request = new_value;
3152        self
3153    }
3154    /// Required. The ID of the project against which to make the request.
3155    ///
3156    /// Sets the *project id* path property to the given value.
3157    ///
3158    /// Even though the property as already been set when instantiating this call,
3159    /// we provide this method for API completeness.
3160    pub fn project_id(mut self, new_value: &str) -> ProjectReserveIdCall<'a, C> {
3161        self._project_id = new_value.to_string();
3162        self
3163    }
3164    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3165    /// while executing the actual API request.
3166    ///
3167    /// ````text
3168    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
3169    /// ````
3170    ///
3171    /// Sets the *delegate* property to the given value.
3172    pub fn delegate(
3173        mut self,
3174        new_value: &'a mut dyn common::Delegate,
3175    ) -> ProjectReserveIdCall<'a, C> {
3176        self._delegate = Some(new_value);
3177        self
3178    }
3179
3180    /// Set any additional parameter of the query string used in the request.
3181    /// It should be used to set parameters which are not yet available through their own
3182    /// setters.
3183    ///
3184    /// Please note that this method must not be used to set any of the known parameters
3185    /// which have their own setter method. If done anyway, the request will fail.
3186    ///
3187    /// # Additional Parameters
3188    ///
3189    /// * *$.xgafv* (query-string) - V1 error format.
3190    /// * *access_token* (query-string) - OAuth access token.
3191    /// * *alt* (query-string) - Data format for response.
3192    /// * *callback* (query-string) - JSONP
3193    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3194    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
3195    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3196    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3197    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3198    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3199    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3200    pub fn param<T>(mut self, name: T, value: T) -> ProjectReserveIdCall<'a, C>
3201    where
3202        T: AsRef<str>,
3203    {
3204        self._additional_params
3205            .insert(name.as_ref().to_string(), value.as_ref().to_string());
3206        self
3207    }
3208
3209    /// Identifies the authorization scope for the method you are building.
3210    ///
3211    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3212    /// [`Scope::CloudPlatform`].
3213    ///
3214    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3215    /// tokens for more than one scope.
3216    ///
3217    /// Usually there is more than one suitable scope to authorize an operation, some of which may
3218    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3219    /// sufficient, a read-write scope will do as well.
3220    pub fn add_scope<St>(mut self, scope: St) -> ProjectReserveIdCall<'a, C>
3221    where
3222        St: AsRef<str>,
3223    {
3224        self._scopes.insert(String::from(scope.as_ref()));
3225        self
3226    }
3227    /// Identifies the authorization scope(s) for the method you are building.
3228    ///
3229    /// See [`Self::add_scope()`] for details.
3230    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectReserveIdCall<'a, C>
3231    where
3232        I: IntoIterator<Item = St>,
3233        St: AsRef<str>,
3234    {
3235        self._scopes
3236            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3237        self
3238    }
3239
3240    /// Removes all scopes, and no default scope will be used either.
3241    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3242    /// for details).
3243    pub fn clear_scopes(mut self) -> ProjectReserveIdCall<'a, C> {
3244        self._scopes.clear();
3245        self
3246    }
3247}
3248
3249/// Rolls back a transaction.
3250///
3251/// A builder for the *rollback* method supported by a *project* resource.
3252/// It is not used directly, but through a [`ProjectMethods`] instance.
3253///
3254/// # Example
3255///
3256/// Instantiate a resource method builder
3257///
3258/// ```test_harness,no_run
3259/// # extern crate hyper;
3260/// # extern crate hyper_rustls;
3261/// # extern crate google_datastore1_beta3 as datastore1_beta3;
3262/// use datastore1_beta3::api::RollbackRequest;
3263/// # async fn dox() {
3264/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3265///
3266/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3267/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3268/// #     .with_native_roots()
3269/// #     .unwrap()
3270/// #     .https_only()
3271/// #     .enable_http2()
3272/// #     .build();
3273///
3274/// # let executor = hyper_util::rt::TokioExecutor::new();
3275/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3276/// #     secret,
3277/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3278/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
3279/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
3280/// #     ),
3281/// # ).build().await.unwrap();
3282///
3283/// # let client = hyper_util::client::legacy::Client::builder(
3284/// #     hyper_util::rt::TokioExecutor::new()
3285/// # )
3286/// # .build(
3287/// #     hyper_rustls::HttpsConnectorBuilder::new()
3288/// #         .with_native_roots()
3289/// #         .unwrap()
3290/// #         .https_or_http()
3291/// #         .enable_http2()
3292/// #         .build()
3293/// # );
3294/// # let mut hub = Datastore::new(client, auth);
3295/// // As the method needs a request, you would usually fill it with the desired information
3296/// // into the respective structure. Some of the parts shown here might not be applicable !
3297/// // Values shown here are possibly random and not representative !
3298/// let mut req = RollbackRequest::default();
3299///
3300/// // You can configure optional parameters by calling the respective setters at will, and
3301/// // execute the final call using `doit()`.
3302/// // Values shown here are possibly random and not representative !
3303/// let result = hub.projects().rollback(req, "projectId")
3304///              .doit().await;
3305/// # }
3306/// ```
3307pub struct ProjectRollbackCall<'a, C>
3308where
3309    C: 'a,
3310{
3311    hub: &'a Datastore<C>,
3312    _request: RollbackRequest,
3313    _project_id: String,
3314    _delegate: Option<&'a mut dyn common::Delegate>,
3315    _additional_params: HashMap<String, String>,
3316    _scopes: BTreeSet<String>,
3317}
3318
3319impl<'a, C> common::CallBuilder for ProjectRollbackCall<'a, C> {}
3320
3321impl<'a, C> ProjectRollbackCall<'a, C>
3322where
3323    C: common::Connector,
3324{
3325    /// Perform the operation you have build so far.
3326    pub async fn doit(mut self) -> common::Result<(common::Response, RollbackResponse)> {
3327        use std::borrow::Cow;
3328        use std::io::{Read, Seek};
3329
3330        use common::{url::Params, ToParts};
3331        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3332
3333        let mut dd = common::DefaultDelegate;
3334        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3335        dlg.begin(common::MethodInfo {
3336            id: "datastore.projects.rollback",
3337            http_method: hyper::Method::POST,
3338        });
3339
3340        for &field in ["alt", "projectId"].iter() {
3341            if self._additional_params.contains_key(field) {
3342                dlg.finished(false);
3343                return Err(common::Error::FieldClash(field));
3344            }
3345        }
3346
3347        let mut params = Params::with_capacity(4 + self._additional_params.len());
3348        params.push("projectId", self._project_id);
3349
3350        params.extend(self._additional_params.iter());
3351
3352        params.push("alt", "json");
3353        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:rollback";
3354        if self._scopes.is_empty() {
3355            self._scopes
3356                .insert(Scope::CloudPlatform.as_ref().to_string());
3357        }
3358
3359        #[allow(clippy::single_element_loop)]
3360        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
3361            url = params.uri_replacement(url, param_name, find_this, false);
3362        }
3363        {
3364            let to_remove = ["projectId"];
3365            params.remove_params(&to_remove);
3366        }
3367
3368        let url = params.parse_with_url(&url);
3369
3370        let mut json_mime_type = mime::APPLICATION_JSON;
3371        let mut request_value_reader = {
3372            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3373            common::remove_json_null_values(&mut value);
3374            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3375            serde_json::to_writer(&mut dst, &value).unwrap();
3376            dst
3377        };
3378        let request_size = request_value_reader
3379            .seek(std::io::SeekFrom::End(0))
3380            .unwrap();
3381        request_value_reader
3382            .seek(std::io::SeekFrom::Start(0))
3383            .unwrap();
3384
3385        loop {
3386            let token = match self
3387                .hub
3388                .auth
3389                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3390                .await
3391            {
3392                Ok(token) => token,
3393                Err(e) => match dlg.token(e) {
3394                    Ok(token) => token,
3395                    Err(e) => {
3396                        dlg.finished(false);
3397                        return Err(common::Error::MissingToken(e));
3398                    }
3399                },
3400            };
3401            request_value_reader
3402                .seek(std::io::SeekFrom::Start(0))
3403                .unwrap();
3404            let mut req_result = {
3405                let client = &self.hub.client;
3406                dlg.pre_request();
3407                let mut req_builder = hyper::Request::builder()
3408                    .method(hyper::Method::POST)
3409                    .uri(url.as_str())
3410                    .header(USER_AGENT, self.hub._user_agent.clone());
3411
3412                if let Some(token) = token.as_ref() {
3413                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3414                }
3415
3416                let request = req_builder
3417                    .header(CONTENT_TYPE, json_mime_type.to_string())
3418                    .header(CONTENT_LENGTH, request_size as u64)
3419                    .body(common::to_body(
3420                        request_value_reader.get_ref().clone().into(),
3421                    ));
3422
3423                client.request(request.unwrap()).await
3424            };
3425
3426            match req_result {
3427                Err(err) => {
3428                    if let common::Retry::After(d) = dlg.http_error(&err) {
3429                        sleep(d).await;
3430                        continue;
3431                    }
3432                    dlg.finished(false);
3433                    return Err(common::Error::HttpError(err));
3434                }
3435                Ok(res) => {
3436                    let (mut parts, body) = res.into_parts();
3437                    let mut body = common::Body::new(body);
3438                    if !parts.status.is_success() {
3439                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3440                        let error = serde_json::from_str(&common::to_string(&bytes));
3441                        let response = common::to_response(parts, bytes.into());
3442
3443                        if let common::Retry::After(d) =
3444                            dlg.http_failure(&response, error.as_ref().ok())
3445                        {
3446                            sleep(d).await;
3447                            continue;
3448                        }
3449
3450                        dlg.finished(false);
3451
3452                        return Err(match error {
3453                            Ok(value) => common::Error::BadRequest(value),
3454                            _ => common::Error::Failure(response),
3455                        });
3456                    }
3457                    let response = {
3458                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3459                        let encoded = common::to_string(&bytes);
3460                        match serde_json::from_str(&encoded) {
3461                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3462                            Err(error) => {
3463                                dlg.response_json_decode_error(&encoded, &error);
3464                                return Err(common::Error::JsonDecodeError(
3465                                    encoded.to_string(),
3466                                    error,
3467                                ));
3468                            }
3469                        }
3470                    };
3471
3472                    dlg.finished(true);
3473                    return Ok(response);
3474                }
3475            }
3476        }
3477    }
3478
3479    ///
3480    /// Sets the *request* property to the given value.
3481    ///
3482    /// Even though the property as already been set when instantiating this call,
3483    /// we provide this method for API completeness.
3484    pub fn request(mut self, new_value: RollbackRequest) -> ProjectRollbackCall<'a, C> {
3485        self._request = new_value;
3486        self
3487    }
3488    /// Required. The ID of the project against which to make the request.
3489    ///
3490    /// Sets the *project id* path property to the given value.
3491    ///
3492    /// Even though the property as already been set when instantiating this call,
3493    /// we provide this method for API completeness.
3494    pub fn project_id(mut self, new_value: &str) -> ProjectRollbackCall<'a, C> {
3495        self._project_id = new_value.to_string();
3496        self
3497    }
3498    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3499    /// while executing the actual API request.
3500    ///
3501    /// ````text
3502    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
3503    /// ````
3504    ///
3505    /// Sets the *delegate* property to the given value.
3506    pub fn delegate(
3507        mut self,
3508        new_value: &'a mut dyn common::Delegate,
3509    ) -> ProjectRollbackCall<'a, C> {
3510        self._delegate = Some(new_value);
3511        self
3512    }
3513
3514    /// Set any additional parameter of the query string used in the request.
3515    /// It should be used to set parameters which are not yet available through their own
3516    /// setters.
3517    ///
3518    /// Please note that this method must not be used to set any of the known parameters
3519    /// which have their own setter method. If done anyway, the request will fail.
3520    ///
3521    /// # Additional Parameters
3522    ///
3523    /// * *$.xgafv* (query-string) - V1 error format.
3524    /// * *access_token* (query-string) - OAuth access token.
3525    /// * *alt* (query-string) - Data format for response.
3526    /// * *callback* (query-string) - JSONP
3527    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3528    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
3529    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3530    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3531    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3532    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3533    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3534    pub fn param<T>(mut self, name: T, value: T) -> ProjectRollbackCall<'a, C>
3535    where
3536        T: AsRef<str>,
3537    {
3538        self._additional_params
3539            .insert(name.as_ref().to_string(), value.as_ref().to_string());
3540        self
3541    }
3542
3543    /// Identifies the authorization scope for the method you are building.
3544    ///
3545    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3546    /// [`Scope::CloudPlatform`].
3547    ///
3548    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3549    /// tokens for more than one scope.
3550    ///
3551    /// Usually there is more than one suitable scope to authorize an operation, some of which may
3552    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3553    /// sufficient, a read-write scope will do as well.
3554    pub fn add_scope<St>(mut self, scope: St) -> ProjectRollbackCall<'a, C>
3555    where
3556        St: AsRef<str>,
3557    {
3558        self._scopes.insert(String::from(scope.as_ref()));
3559        self
3560    }
3561    /// Identifies the authorization scope(s) for the method you are building.
3562    ///
3563    /// See [`Self::add_scope()`] for details.
3564    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectRollbackCall<'a, C>
3565    where
3566        I: IntoIterator<Item = St>,
3567        St: AsRef<str>,
3568    {
3569        self._scopes
3570            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3571        self
3572    }
3573
3574    /// Removes all scopes, and no default scope will be used either.
3575    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3576    /// for details).
3577    pub fn clear_scopes(mut self) -> ProjectRollbackCall<'a, C> {
3578        self._scopes.clear();
3579        self
3580    }
3581}
3582
3583/// Runs an aggregation query.
3584///
3585/// A builder for the *runAggregationQuery* method supported by a *project* resource.
3586/// It is not used directly, but through a [`ProjectMethods`] instance.
3587///
3588/// # Example
3589///
3590/// Instantiate a resource method builder
3591///
3592/// ```test_harness,no_run
3593/// # extern crate hyper;
3594/// # extern crate hyper_rustls;
3595/// # extern crate google_datastore1_beta3 as datastore1_beta3;
3596/// use datastore1_beta3::api::RunAggregationQueryRequest;
3597/// # async fn dox() {
3598/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3599///
3600/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3601/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3602/// #     .with_native_roots()
3603/// #     .unwrap()
3604/// #     .https_only()
3605/// #     .enable_http2()
3606/// #     .build();
3607///
3608/// # let executor = hyper_util::rt::TokioExecutor::new();
3609/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3610/// #     secret,
3611/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3612/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
3613/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
3614/// #     ),
3615/// # ).build().await.unwrap();
3616///
3617/// # let client = hyper_util::client::legacy::Client::builder(
3618/// #     hyper_util::rt::TokioExecutor::new()
3619/// # )
3620/// # .build(
3621/// #     hyper_rustls::HttpsConnectorBuilder::new()
3622/// #         .with_native_roots()
3623/// #         .unwrap()
3624/// #         .https_or_http()
3625/// #         .enable_http2()
3626/// #         .build()
3627/// # );
3628/// # let mut hub = Datastore::new(client, auth);
3629/// // As the method needs a request, you would usually fill it with the desired information
3630/// // into the respective structure. Some of the parts shown here might not be applicable !
3631/// // Values shown here are possibly random and not representative !
3632/// let mut req = RunAggregationQueryRequest::default();
3633///
3634/// // You can configure optional parameters by calling the respective setters at will, and
3635/// // execute the final call using `doit()`.
3636/// // Values shown here are possibly random and not representative !
3637/// let result = hub.projects().run_aggregation_query(req, "projectId")
3638///              .doit().await;
3639/// # }
3640/// ```
3641pub struct ProjectRunAggregationQueryCall<'a, C>
3642where
3643    C: 'a,
3644{
3645    hub: &'a Datastore<C>,
3646    _request: RunAggregationQueryRequest,
3647    _project_id: String,
3648    _delegate: Option<&'a mut dyn common::Delegate>,
3649    _additional_params: HashMap<String, String>,
3650    _scopes: BTreeSet<String>,
3651}
3652
3653impl<'a, C> common::CallBuilder for ProjectRunAggregationQueryCall<'a, C> {}
3654
3655impl<'a, C> ProjectRunAggregationQueryCall<'a, C>
3656where
3657    C: common::Connector,
3658{
3659    /// Perform the operation you have build so far.
3660    pub async fn doit(mut self) -> common::Result<(common::Response, RunAggregationQueryResponse)> {
3661        use std::borrow::Cow;
3662        use std::io::{Read, Seek};
3663
3664        use common::{url::Params, ToParts};
3665        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3666
3667        let mut dd = common::DefaultDelegate;
3668        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3669        dlg.begin(common::MethodInfo {
3670            id: "datastore.projects.runAggregationQuery",
3671            http_method: hyper::Method::POST,
3672        });
3673
3674        for &field in ["alt", "projectId"].iter() {
3675            if self._additional_params.contains_key(field) {
3676                dlg.finished(false);
3677                return Err(common::Error::FieldClash(field));
3678            }
3679        }
3680
3681        let mut params = Params::with_capacity(4 + self._additional_params.len());
3682        params.push("projectId", self._project_id);
3683
3684        params.extend(self._additional_params.iter());
3685
3686        params.push("alt", "json");
3687        let mut url =
3688            self.hub._base_url.clone() + "v1beta3/projects/{projectId}:runAggregationQuery";
3689        if self._scopes.is_empty() {
3690            self._scopes
3691                .insert(Scope::CloudPlatform.as_ref().to_string());
3692        }
3693
3694        #[allow(clippy::single_element_loop)]
3695        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
3696            url = params.uri_replacement(url, param_name, find_this, false);
3697        }
3698        {
3699            let to_remove = ["projectId"];
3700            params.remove_params(&to_remove);
3701        }
3702
3703        let url = params.parse_with_url(&url);
3704
3705        let mut json_mime_type = mime::APPLICATION_JSON;
3706        let mut request_value_reader = {
3707            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3708            common::remove_json_null_values(&mut value);
3709            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3710            serde_json::to_writer(&mut dst, &value).unwrap();
3711            dst
3712        };
3713        let request_size = request_value_reader
3714            .seek(std::io::SeekFrom::End(0))
3715            .unwrap();
3716        request_value_reader
3717            .seek(std::io::SeekFrom::Start(0))
3718            .unwrap();
3719
3720        loop {
3721            let token = match self
3722                .hub
3723                .auth
3724                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3725                .await
3726            {
3727                Ok(token) => token,
3728                Err(e) => match dlg.token(e) {
3729                    Ok(token) => token,
3730                    Err(e) => {
3731                        dlg.finished(false);
3732                        return Err(common::Error::MissingToken(e));
3733                    }
3734                },
3735            };
3736            request_value_reader
3737                .seek(std::io::SeekFrom::Start(0))
3738                .unwrap();
3739            let mut req_result = {
3740                let client = &self.hub.client;
3741                dlg.pre_request();
3742                let mut req_builder = hyper::Request::builder()
3743                    .method(hyper::Method::POST)
3744                    .uri(url.as_str())
3745                    .header(USER_AGENT, self.hub._user_agent.clone());
3746
3747                if let Some(token) = token.as_ref() {
3748                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3749                }
3750
3751                let request = req_builder
3752                    .header(CONTENT_TYPE, json_mime_type.to_string())
3753                    .header(CONTENT_LENGTH, request_size as u64)
3754                    .body(common::to_body(
3755                        request_value_reader.get_ref().clone().into(),
3756                    ));
3757
3758                client.request(request.unwrap()).await
3759            };
3760
3761            match req_result {
3762                Err(err) => {
3763                    if let common::Retry::After(d) = dlg.http_error(&err) {
3764                        sleep(d).await;
3765                        continue;
3766                    }
3767                    dlg.finished(false);
3768                    return Err(common::Error::HttpError(err));
3769                }
3770                Ok(res) => {
3771                    let (mut parts, body) = res.into_parts();
3772                    let mut body = common::Body::new(body);
3773                    if !parts.status.is_success() {
3774                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3775                        let error = serde_json::from_str(&common::to_string(&bytes));
3776                        let response = common::to_response(parts, bytes.into());
3777
3778                        if let common::Retry::After(d) =
3779                            dlg.http_failure(&response, error.as_ref().ok())
3780                        {
3781                            sleep(d).await;
3782                            continue;
3783                        }
3784
3785                        dlg.finished(false);
3786
3787                        return Err(match error {
3788                            Ok(value) => common::Error::BadRequest(value),
3789                            _ => common::Error::Failure(response),
3790                        });
3791                    }
3792                    let response = {
3793                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3794                        let encoded = common::to_string(&bytes);
3795                        match serde_json::from_str(&encoded) {
3796                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3797                            Err(error) => {
3798                                dlg.response_json_decode_error(&encoded, &error);
3799                                return Err(common::Error::JsonDecodeError(
3800                                    encoded.to_string(),
3801                                    error,
3802                                ));
3803                            }
3804                        }
3805                    };
3806
3807                    dlg.finished(true);
3808                    return Ok(response);
3809                }
3810            }
3811        }
3812    }
3813
3814    ///
3815    /// Sets the *request* property to the given value.
3816    ///
3817    /// Even though the property as already been set when instantiating this call,
3818    /// we provide this method for API completeness.
3819    pub fn request(
3820        mut self,
3821        new_value: RunAggregationQueryRequest,
3822    ) -> ProjectRunAggregationQueryCall<'a, C> {
3823        self._request = new_value;
3824        self
3825    }
3826    /// Required. The ID of the project against which to make the request.
3827    ///
3828    /// Sets the *project id* path property to the given value.
3829    ///
3830    /// Even though the property as already been set when instantiating this call,
3831    /// we provide this method for API completeness.
3832    pub fn project_id(mut self, new_value: &str) -> ProjectRunAggregationQueryCall<'a, C> {
3833        self._project_id = new_value.to_string();
3834        self
3835    }
3836    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3837    /// while executing the actual API request.
3838    ///
3839    /// ````text
3840    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
3841    /// ````
3842    ///
3843    /// Sets the *delegate* property to the given value.
3844    pub fn delegate(
3845        mut self,
3846        new_value: &'a mut dyn common::Delegate,
3847    ) -> ProjectRunAggregationQueryCall<'a, C> {
3848        self._delegate = Some(new_value);
3849        self
3850    }
3851
3852    /// Set any additional parameter of the query string used in the request.
3853    /// It should be used to set parameters which are not yet available through their own
3854    /// setters.
3855    ///
3856    /// Please note that this method must not be used to set any of the known parameters
3857    /// which have their own setter method. If done anyway, the request will fail.
3858    ///
3859    /// # Additional Parameters
3860    ///
3861    /// * *$.xgafv* (query-string) - V1 error format.
3862    /// * *access_token* (query-string) - OAuth access token.
3863    /// * *alt* (query-string) - Data format for response.
3864    /// * *callback* (query-string) - JSONP
3865    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3866    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
3867    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3868    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3869    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3870    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3871    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3872    pub fn param<T>(mut self, name: T, value: T) -> ProjectRunAggregationQueryCall<'a, C>
3873    where
3874        T: AsRef<str>,
3875    {
3876        self._additional_params
3877            .insert(name.as_ref().to_string(), value.as_ref().to_string());
3878        self
3879    }
3880
3881    /// Identifies the authorization scope for the method you are building.
3882    ///
3883    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3884    /// [`Scope::CloudPlatform`].
3885    ///
3886    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3887    /// tokens for more than one scope.
3888    ///
3889    /// Usually there is more than one suitable scope to authorize an operation, some of which may
3890    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3891    /// sufficient, a read-write scope will do as well.
3892    pub fn add_scope<St>(mut self, scope: St) -> ProjectRunAggregationQueryCall<'a, C>
3893    where
3894        St: AsRef<str>,
3895    {
3896        self._scopes.insert(String::from(scope.as_ref()));
3897        self
3898    }
3899    /// Identifies the authorization scope(s) for the method you are building.
3900    ///
3901    /// See [`Self::add_scope()`] for details.
3902    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectRunAggregationQueryCall<'a, C>
3903    where
3904        I: IntoIterator<Item = St>,
3905        St: AsRef<str>,
3906    {
3907        self._scopes
3908            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3909        self
3910    }
3911
3912    /// Removes all scopes, and no default scope will be used either.
3913    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3914    /// for details).
3915    pub fn clear_scopes(mut self) -> ProjectRunAggregationQueryCall<'a, C> {
3916        self._scopes.clear();
3917        self
3918    }
3919}
3920
3921/// Queries for entities.
3922///
3923/// A builder for the *runQuery* method supported by a *project* resource.
3924/// It is not used directly, but through a [`ProjectMethods`] instance.
3925///
3926/// # Example
3927///
3928/// Instantiate a resource method builder
3929///
3930/// ```test_harness,no_run
3931/// # extern crate hyper;
3932/// # extern crate hyper_rustls;
3933/// # extern crate google_datastore1_beta3 as datastore1_beta3;
3934/// use datastore1_beta3::api::RunQueryRequest;
3935/// # async fn dox() {
3936/// # use datastore1_beta3::{Datastore, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3937///
3938/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3939/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3940/// #     .with_native_roots()
3941/// #     .unwrap()
3942/// #     .https_only()
3943/// #     .enable_http2()
3944/// #     .build();
3945///
3946/// # let executor = hyper_util::rt::TokioExecutor::new();
3947/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3948/// #     secret,
3949/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3950/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
3951/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
3952/// #     ),
3953/// # ).build().await.unwrap();
3954///
3955/// # let client = hyper_util::client::legacy::Client::builder(
3956/// #     hyper_util::rt::TokioExecutor::new()
3957/// # )
3958/// # .build(
3959/// #     hyper_rustls::HttpsConnectorBuilder::new()
3960/// #         .with_native_roots()
3961/// #         .unwrap()
3962/// #         .https_or_http()
3963/// #         .enable_http2()
3964/// #         .build()
3965/// # );
3966/// # let mut hub = Datastore::new(client, auth);
3967/// // As the method needs a request, you would usually fill it with the desired information
3968/// // into the respective structure. Some of the parts shown here might not be applicable !
3969/// // Values shown here are possibly random and not representative !
3970/// let mut req = RunQueryRequest::default();
3971///
3972/// // You can configure optional parameters by calling the respective setters at will, and
3973/// // execute the final call using `doit()`.
3974/// // Values shown here are possibly random and not representative !
3975/// let result = hub.projects().run_query(req, "projectId")
3976///              .doit().await;
3977/// # }
3978/// ```
3979pub struct ProjectRunQueryCall<'a, C>
3980where
3981    C: 'a,
3982{
3983    hub: &'a Datastore<C>,
3984    _request: RunQueryRequest,
3985    _project_id: String,
3986    _delegate: Option<&'a mut dyn common::Delegate>,
3987    _additional_params: HashMap<String, String>,
3988    _scopes: BTreeSet<String>,
3989}
3990
3991impl<'a, C> common::CallBuilder for ProjectRunQueryCall<'a, C> {}
3992
3993impl<'a, C> ProjectRunQueryCall<'a, C>
3994where
3995    C: common::Connector,
3996{
3997    /// Perform the operation you have build so far.
3998    pub async fn doit(mut self) -> common::Result<(common::Response, RunQueryResponse)> {
3999        use std::borrow::Cow;
4000        use std::io::{Read, Seek};
4001
4002        use common::{url::Params, ToParts};
4003        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
4004
4005        let mut dd = common::DefaultDelegate;
4006        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
4007        dlg.begin(common::MethodInfo {
4008            id: "datastore.projects.runQuery",
4009            http_method: hyper::Method::POST,
4010        });
4011
4012        for &field in ["alt", "projectId"].iter() {
4013            if self._additional_params.contains_key(field) {
4014                dlg.finished(false);
4015                return Err(common::Error::FieldClash(field));
4016            }
4017        }
4018
4019        let mut params = Params::with_capacity(4 + self._additional_params.len());
4020        params.push("projectId", self._project_id);
4021
4022        params.extend(self._additional_params.iter());
4023
4024        params.push("alt", "json");
4025        let mut url = self.hub._base_url.clone() + "v1beta3/projects/{projectId}:runQuery";
4026        if self._scopes.is_empty() {
4027            self._scopes
4028                .insert(Scope::CloudPlatform.as_ref().to_string());
4029        }
4030
4031        #[allow(clippy::single_element_loop)]
4032        for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
4033            url = params.uri_replacement(url, param_name, find_this, false);
4034        }
4035        {
4036            let to_remove = ["projectId"];
4037            params.remove_params(&to_remove);
4038        }
4039
4040        let url = params.parse_with_url(&url);
4041
4042        let mut json_mime_type = mime::APPLICATION_JSON;
4043        let mut request_value_reader = {
4044            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
4045            common::remove_json_null_values(&mut value);
4046            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
4047            serde_json::to_writer(&mut dst, &value).unwrap();
4048            dst
4049        };
4050        let request_size = request_value_reader
4051            .seek(std::io::SeekFrom::End(0))
4052            .unwrap();
4053        request_value_reader
4054            .seek(std::io::SeekFrom::Start(0))
4055            .unwrap();
4056
4057        loop {
4058            let token = match self
4059                .hub
4060                .auth
4061                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
4062                .await
4063            {
4064                Ok(token) => token,
4065                Err(e) => match dlg.token(e) {
4066                    Ok(token) => token,
4067                    Err(e) => {
4068                        dlg.finished(false);
4069                        return Err(common::Error::MissingToken(e));
4070                    }
4071                },
4072            };
4073            request_value_reader
4074                .seek(std::io::SeekFrom::Start(0))
4075                .unwrap();
4076            let mut req_result = {
4077                let client = &self.hub.client;
4078                dlg.pre_request();
4079                let mut req_builder = hyper::Request::builder()
4080                    .method(hyper::Method::POST)
4081                    .uri(url.as_str())
4082                    .header(USER_AGENT, self.hub._user_agent.clone());
4083
4084                if let Some(token) = token.as_ref() {
4085                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
4086                }
4087
4088                let request = req_builder
4089                    .header(CONTENT_TYPE, json_mime_type.to_string())
4090                    .header(CONTENT_LENGTH, request_size as u64)
4091                    .body(common::to_body(
4092                        request_value_reader.get_ref().clone().into(),
4093                    ));
4094
4095                client.request(request.unwrap()).await
4096            };
4097
4098            match req_result {
4099                Err(err) => {
4100                    if let common::Retry::After(d) = dlg.http_error(&err) {
4101                        sleep(d).await;
4102                        continue;
4103                    }
4104                    dlg.finished(false);
4105                    return Err(common::Error::HttpError(err));
4106                }
4107                Ok(res) => {
4108                    let (mut parts, body) = res.into_parts();
4109                    let mut body = common::Body::new(body);
4110                    if !parts.status.is_success() {
4111                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4112                        let error = serde_json::from_str(&common::to_string(&bytes));
4113                        let response = common::to_response(parts, bytes.into());
4114
4115                        if let common::Retry::After(d) =
4116                            dlg.http_failure(&response, error.as_ref().ok())
4117                        {
4118                            sleep(d).await;
4119                            continue;
4120                        }
4121
4122                        dlg.finished(false);
4123
4124                        return Err(match error {
4125                            Ok(value) => common::Error::BadRequest(value),
4126                            _ => common::Error::Failure(response),
4127                        });
4128                    }
4129                    let response = {
4130                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4131                        let encoded = common::to_string(&bytes);
4132                        match serde_json::from_str(&encoded) {
4133                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
4134                            Err(error) => {
4135                                dlg.response_json_decode_error(&encoded, &error);
4136                                return Err(common::Error::JsonDecodeError(
4137                                    encoded.to_string(),
4138                                    error,
4139                                ));
4140                            }
4141                        }
4142                    };
4143
4144                    dlg.finished(true);
4145                    return Ok(response);
4146                }
4147            }
4148        }
4149    }
4150
4151    ///
4152    /// Sets the *request* property to the given value.
4153    ///
4154    /// Even though the property as already been set when instantiating this call,
4155    /// we provide this method for API completeness.
4156    pub fn request(mut self, new_value: RunQueryRequest) -> ProjectRunQueryCall<'a, C> {
4157        self._request = new_value;
4158        self
4159    }
4160    /// Required. The ID of the project against which to make the request.
4161    ///
4162    /// Sets the *project id* path property to the given value.
4163    ///
4164    /// Even though the property as already been set when instantiating this call,
4165    /// we provide this method for API completeness.
4166    pub fn project_id(mut self, new_value: &str) -> ProjectRunQueryCall<'a, C> {
4167        self._project_id = new_value.to_string();
4168        self
4169    }
4170    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
4171    /// while executing the actual API request.
4172    ///
4173    /// ````text
4174    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
4175    /// ````
4176    ///
4177    /// Sets the *delegate* property to the given value.
4178    pub fn delegate(
4179        mut self,
4180        new_value: &'a mut dyn common::Delegate,
4181    ) -> ProjectRunQueryCall<'a, C> {
4182        self._delegate = Some(new_value);
4183        self
4184    }
4185
4186    /// Set any additional parameter of the query string used in the request.
4187    /// It should be used to set parameters which are not yet available through their own
4188    /// setters.
4189    ///
4190    /// Please note that this method must not be used to set any of the known parameters
4191    /// which have their own setter method. If done anyway, the request will fail.
4192    ///
4193    /// # Additional Parameters
4194    ///
4195    /// * *$.xgafv* (query-string) - V1 error format.
4196    /// * *access_token* (query-string) - OAuth access token.
4197    /// * *alt* (query-string) - Data format for response.
4198    /// * *callback* (query-string) - JSONP
4199    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
4200    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
4201    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
4202    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
4203    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
4204    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
4205    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
4206    pub fn param<T>(mut self, name: T, value: T) -> ProjectRunQueryCall<'a, C>
4207    where
4208        T: AsRef<str>,
4209    {
4210        self._additional_params
4211            .insert(name.as_ref().to_string(), value.as_ref().to_string());
4212        self
4213    }
4214
4215    /// Identifies the authorization scope for the method you are building.
4216    ///
4217    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
4218    /// [`Scope::CloudPlatform`].
4219    ///
4220    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
4221    /// tokens for more than one scope.
4222    ///
4223    /// Usually there is more than one suitable scope to authorize an operation, some of which may
4224    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
4225    /// sufficient, a read-write scope will do as well.
4226    pub fn add_scope<St>(mut self, scope: St) -> ProjectRunQueryCall<'a, C>
4227    where
4228        St: AsRef<str>,
4229    {
4230        self._scopes.insert(String::from(scope.as_ref()));
4231        self
4232    }
4233    /// Identifies the authorization scope(s) for the method you are building.
4234    ///
4235    /// See [`Self::add_scope()`] for details.
4236    pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectRunQueryCall<'a, C>
4237    where
4238        I: IntoIterator<Item = St>,
4239        St: AsRef<str>,
4240    {
4241        self._scopes
4242            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
4243        self
4244    }
4245
4246    /// Removes all scopes, and no default scope will be used either.
4247    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
4248    /// for details).
4249    pub fn clear_scopes(mut self) -> ProjectRunQueryCall<'a, C> {
4250        self._scopes.clear();
4251        self
4252    }
4253}