UNPKG

17.1 kBTypeScriptView Raw
1/*!
2 * Copyright 2014 Google LLC.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16import { CallOptions } from 'google-gax';
17import { google } from '../protos/protos';
18import { Datastore, TransactionOptions } from '.';
19import { Entity, Entities } from './entity';
20import { Query } from './query';
21import { CommitCallback, CommitResponse, DatastoreRequest } from './request';
22/**
23 * A transaction is a set of Datastore operations on one or more entities. Each
24 * transaction is guaranteed to be atomic, which means that transactions are
25 * never partially applied. Either all of the operations in the transaction are
26 * applied, or none of them are applied.
27 *
28 * @see {@link https://cloud.google.com/datastore/docs/concepts/transactions| Transactions Reference}
29 *
30 * @class
31 * @extends {Request}
32 * @param {Datastore} datastore A Datastore instance.
33 * @mixes module:datastore/request
34 *
35 * @example
36 * ```
37 * const {Datastore} = require('@google-cloud/datastore');
38 * const datastore = new Datastore();
39 * const transaction = datastore.transaction();
40 * ```
41 */
42declare class Transaction extends DatastoreRequest {
43 namespace?: string;
44 readOnly: boolean;
45 request: Function;
46 modifiedEntities_: ModifiedEntities;
47 skipCommit?: boolean;
48 constructor(datastore: Datastore, options?: TransactionOptions);
49 /*! Developer Documentation
50 *
51 * Below, we override two methods that we inherit from DatastoreRequest:
52 * `delete` and `save`. This is done because:
53 *
54 * A) the documentation needs to be different for a transactional save, and
55 * B) we build up a "modifiedEntities_" array on this object, used to build
56 * the final commit request with.
57 */
58 /**
59 * Commit the remote transaction and finalize the current transaction
60 * instance.
61 *
62 * If the commit request fails, we will automatically rollback the
63 * transaction.
64 *
65 * @param {object} [gaxOptions] Request configuration options, outlined here:
66 * https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
67 * @param {function} callback The callback function.
68 * @param {?error} callback.err An error returned while making this request.
69 * If the commit fails, we automatically try to rollback the transaction
70 * (see {module:datastore/transaction#rollback}).
71 * @param {object} callback.apiResponse The full API response.
72 *
73 * @example
74 * ```
75 * const {Datastore} = require('@google-cloud/datastore');
76 * const datastore = new Datastore();
77 * const transaction = datastore.transaction();
78 *
79 * transaction.commit((err, apiResponse) => {
80 * if (err) {
81 * // Transaction could not be committed.
82 * }
83 * });
84 *
85 * //-
86 * // If the callback is omitted, we'll return a Promise.
87 * //-
88 * transaction.commit().then((data) => {
89 * const apiResponse = data[0];
90 * });
91 * ```
92 */
93 commit(gaxOptions?: CallOptions): Promise<CommitResponse>;
94 commit(callback: CommitCallback): void;
95 commit(gaxOptions: CallOptions, callback: CommitCallback): void;
96 /**
97 * Create a query for the specified kind. See {module:datastore/query} for all
98 * of the available methods.
99 *
100 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries| Datastore Queries}
101 *
102 * @see {@link Query}
103 *
104 * @param {string} [namespace] Namespace.
105 * @param {string} kind The kind to query.
106 * @returns {Query}
107 *
108 * @example
109 * ```
110 * const {Datastore} = require('@google-cloud/datastore');
111 * const datastore = new Datastore();
112 * const transaction = datastore.transaction();
113 *
114 * // Run the query inside the transaction.
115 * transaction.run((err) => {
116 * if (err) {
117 * // Error handling omitted.
118 * }
119 * const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);
120 *
121 * const query = transaction.createQuery('Company')
122 * .hasAncestor(ancestorKey);
123 *
124 * query.run((err, entities) => {
125 * if (err) {
126 * // Error handling omitted.
127 * }
128 *
129 * transaction.commit((err) => {
130 * if (!err) {
131 * // Transaction committed successfully.
132 * }
133 * });
134 * });
135 * });
136 *
137 * // Run the query inside the transaction.with namespace
138 * transaction.run((err) => {
139 * if (err) {
140 * // Error handling omitted.
141 * }
142 * const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);
143 *
144 * const query = transaction.createQuery('CompanyNamespace', 'Company')
145 * .hasAncestor(ancestorKey);
146 *
147 * query.run((err, entities) => {
148 * if (err) {
149 * // Error handling omitted.
150 * }
151 *
152 * transaction.commit((err) => {
153 * if (!err) {
154 * // Transaction committed successfully.
155 * }
156 * });
157 * });
158 * });
159 * ```
160 */
161 createQuery(kind?: string): Query;
162 createQuery(kind?: string[]): Query;
163 createQuery(namespace: string, kind: string): Query;
164 createQuery(namespace: string, kind: string[]): Query;
165 /**
166 * Delete all entities identified with the specified key(s) in the current
167 * transaction.
168 *
169 * @param {Key|Key[]} key Datastore key object(s).
170 *
171 * @example
172 * ```
173 * const {Datastore} = require('@google-cloud/datastore');
174 * const datastore = new Datastore();
175 * const transaction = datastore.transaction();
176 *
177 * transaction.run((err) => {
178 * if (err) {
179 * // Error handling omitted.
180 * }
181 *
182 * // Delete a single entity.
183 * transaction.delete(datastore.key(['Company', 123]));
184 *
185 * // Delete multiple entities at once.
186 * transaction.delete([
187 * datastore.key(['Company', 123]),
188 * datastore.key(['Product', 'Computer'])
189 * ]);
190 *
191 * transaction.commit((err) => {
192 * if (!err) {
193 * // Transaction committed successfully.
194 * }
195 * });
196 * });
197 * ```
198 */
199 delete(entities?: Entities): any;
200 /**
201 * Maps to {@link Datastore#save}, forcing the method to be `insert`.
202 *
203 * @param {object|object[]} entities Datastore key object(s).
204 * @param {Key} entities.key Datastore key object.
205 * @param {string[]} [entities.excludeFromIndexes] Exclude properties from
206 * indexing using a simple JSON path notation. See the examples in
207 * {@link Datastore#save} to see how to target properties at different
208 * levels of nesting within your entity.
209 * @param {object} entities.data Data to save with the provided key.
210 */
211 insert(entities: Entities): void;
212 /**
213 * Reverse a transaction remotely and finalize the current transaction
214 * instance.
215 *
216 * @param {object} [gaxOptions] Request configuration options, outlined here:
217 * https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
218 * @param {function} callback The callback function.
219 * @param {?error} callback.err An error returned while making this request.
220 * @param {object} callback.apiResponse The full API response.
221 *
222 * @example
223 * ```
224 * const {Datastore} = require('@google-cloud/datastore');
225 * const datastore = new Datastore();
226 * const transaction = datastore.transaction();
227 *
228 * transaction.run((err) => {
229 * if (err) {
230 * // Error handling omitted.
231 * }
232 *
233 * transaction.rollback((err) => {
234 * if (!err) {
235 * // Transaction rolled back successfully.
236 * }
237 * });
238 * });
239 *
240 * //-
241 * // If the callback is omitted, we'll return a Promise.
242 * //-
243 * transaction.rollback().then((data) => {
244 * const apiResponse = data[0];
245 * });
246 * ```
247 */
248 rollback(callback: RollbackCallback): void;
249 rollback(gaxOptions?: CallOptions): Promise<RollbackResponse>;
250 rollback(gaxOptions: CallOptions, callback: RollbackCallback): void;
251 /**
252 * Begin a remote transaction. In the callback provided, run your
253 * transactional commands.
254 *
255 * @param {object} [options] Configuration object.
256 * @param {object} [options.gaxOptions] Request configuration options, outlined
257 * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
258 * @param {boolean} [options.readOnly=false] A read-only transaction cannot
259 * modify entities.
260 * @param {string} [options.transactionId] The ID of a previous transaction.
261 * @param {function} callback The function to execute within the context of
262 * a transaction.
263 * @param {?error} callback.err An error returned while making this request.
264 * @param {Transaction} callback.transaction This transaction
265 * instance.
266 * @param {object} callback.apiResponse The full API response.
267 *
268 * @example
269 * ```
270 * const {Datastore} = require('@google-cloud/datastore');
271 * const datastore = new Datastore();
272 * const transaction = datastore.transaction();
273 *
274 * transaction.run((err, transaction) => {
275 * // Perform Datastore transactional operations.
276 * const key = datastore.key(['Company', 123]);
277 *
278 * transaction.get(key, (err, entity) => {
279 * entity.name = 'Google';
280 *
281 * transaction.save({
282 * key: key,
283 * data: entity
284 * });
285 *
286 * transaction.commit((err) => {
287 * if (!err) {
288 * // Data saved successfully.
289 * }
290 * });
291 * });
292 * });
293 *
294 * //-
295 * // If the callback is omitted, we'll return a Promise.
296 * //-
297 * transaction.run().then((data) => {
298 * const transaction = data[0];
299 * const apiResponse = data[1];
300 * });
301 * ```
302 */
303 run(options?: RunOptions): Promise<RunResponse>;
304 run(callback: RunCallback): void;
305 run(options: RunOptions, callback: RunCallback): void;
306 /**
307 * Insert or update the specified object(s) in the current transaction. If a
308 * key is incomplete, its associated object is inserted and the original Key
309 * object is updated to contain the generated ID.
310 *
311 * This method will determine the correct Datastore method to execute
312 * (`upsert`, `insert`, or `update`) by using the key(s) provided. For
313 * example, if you provide an incomplete key (one without an ID), the request
314 * will create a new entity and have its ID automatically assigned. If you
315 * provide a complete key, the entity will be updated with the data specified.
316 *
317 * By default, all properties are indexed. To prevent a property from being
318 * included in *all* indexes, you must supply an `excludeFromIndexes` array.
319 * See below for an example.
320 *
321 * @param {object|object[]} entities Datastore key object(s).
322 * @param {Key} entities.key Datastore key object.
323 * @param {string[]} [entities.excludeFromIndexes] Exclude properties from
324 * indexing using a simple JSON path notation. See the example below to
325 * see how to target properties at different levels of nesting within your
326 * entity.
327 * @param {object} entities.data Data to save with the provided key.
328 *
329 * @example
330 * ```
331 * <caption>Save a single entity.</caption>
332 * const {Datastore} = require('@google-cloud/datastore');
333 * const datastore = new Datastore();
334 * const transaction = datastore.transaction();
335 *
336 * // Notice that we are providing an incomplete key. After the transaction is
337 * // committed, the Key object held by the `key` variable will be populated
338 * // with a path containing its generated ID.
339 * //-
340 * const key = datastore.key('Company');
341 *
342 * transaction.run((err) => {
343 * if (err) {
344 * // Error handling omitted.
345 * }
346 *
347 * transaction.save({
348 * key: key,
349 * data: {
350 * rating: '10'
351 * }
352 * });
353 *
354 * transaction.commit((err) => {
355 * if (!err) {
356 * // Data saved successfully.
357 * }
358 * });
359 * });
360 *
361 * ```
362 * @example
363 * ```
364 * const {Datastore} = require('@google-cloud/datastore');
365 * const datastore = new Datastore();
366 * const transaction = datastore.transaction();
367 *
368 * // Use an array, `excludeFromIndexes`, to exclude properties from indexing.
369 * // This will allow storing string values larger than 1500 bytes.
370 *
371 * transaction.run((err) => {
372 * if (err) {
373 * // Error handling omitted.
374 * }
375 *
376 * transaction.save({
377 * key: key,
378 * excludeFromIndexes: [
379 * 'description',
380 * 'embeddedEntity.description',
381 * 'arrayValue[].description'
382 * ],
383 * data: {
384 * description: 'Long string (...)',
385 * embeddedEntity: {
386 * description: 'Long string (...)'
387 * },
388 * arrayValue: [
389 * {
390 * description: 'Long string (...)'
391 * }
392 * ]
393 * }
394 * });
395 *
396 * transaction.commit((err) => {
397 * if (!err) {
398 * // Data saved successfully.
399 * }
400 * });
401 * });
402 *
403 * ```
404 * @example
405 * ```
406 * <caption>Save multiple entities at once.</caption>
407 * const {Datastore} = require('@google-cloud/datastore');
408 * const datastore = new Datastore();
409 * const transaction = datastore.transaction();
410 * const companyKey = datastore.key(['Company', 123]);
411 * const productKey = datastore.key(['Product', 'Computer']);
412 *
413 * transaction.run((err) => {
414 * if (err) {
415 * // Error handling omitted.
416 * }
417 *
418 * transaction.save([
419 * {
420 * key: companyKey,
421 * data: {
422 * HQ: 'Dallas, TX'
423 * }
424 * },
425 * {
426 * key: productKey,
427 * data: {
428 * vendor: 'Dell'
429 * }
430 * }
431 * ]);
432 *
433 * transaction.commit((err) => {
434 * if (!err) {
435 * // Data saved successfully.
436 * }
437 * });
438 * });
439 * ```
440 */
441 save(entities: Entities): void;
442 /**
443 * Maps to {@link Datastore#save}, forcing the method to be `update`.
444 *
445 * @param {object|object[]} entities Datastore key object(s).
446 * @param {Key} entities.key Datastore key object.
447 * @param {string[]} [entities.excludeFromIndexes] Exclude properties from
448 * indexing using a simple JSON path notation. See the examples in
449 * {@link Datastore#save} to see how to target properties at different
450 * levels of nesting within your entity.
451 * @param {object} entities.data Data to save with the provided key.
452 */
453 update(entities: Entities): void;
454 /**
455 * Maps to {@link Datastore#save}, forcing the method to be `upsert`.
456 *
457 * @param {object|object[]} entities Datastore key object(s).
458 * @param {Key} entities.key Datastore key object.
459 * @param {string[]} [entities.excludeFromIndexes] Exclude properties from
460 * indexing using a simple JSON path notation. See the examples in
461 * {@link Datastore#save} to see how to target properties at different
462 * levels of nesting within your entity.
463 * @param {object} entities.data Data to save with the provided key.
464 */
465 upsert(entities: Entities): void;
466}
467export declare type ModifiedEntities = Array<{
468 entity: {
469 key: Entity;
470 };
471 method: string;
472 args: Entity[];
473}>;
474export declare type RunResponse = [Transaction, google.datastore.v1.IBeginTransactionResponse];
475export interface RunCallback {
476 (error: Error | null, transaction: Transaction | null, response?: google.datastore.v1.IBeginTransactionResponse): void;
477}
478export interface RollbackCallback {
479 (error: Error | null, response?: google.datastore.v1.IRollbackResponse): void;
480}
481export declare type RollbackResponse = [google.datastore.v1.IRollbackResponse];
482export interface RunOptions {
483 readOnly?: boolean;
484 transactionId?: string;
485 transactionOptions?: TransactionOptions;
486 gaxOptions?: CallOptions;
487}
488/**
489 * Reference to the {@link Transaction} class.
490 * @name module:@google-cloud/datastore.Transaction
491 * @see Transaction
492 */
493export { Transaction };