UNPKG

14.7 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 */
16/// <reference types="node" />
17import { Key } from 'readline';
18import { Datastore } from '.';
19import { Entity } from './entity';
20import { Transaction } from './transaction';
21import { CallOptions } from 'google-gax';
22import { RunQueryStreamOptions } from '../src/request';
23export declare type Operator = '=' | '<' | '>' | '<=' | '>=' | 'HAS_ANCESTOR';
24export interface OrderOptions {
25 descending?: boolean;
26}
27export interface Order {
28 name: string;
29 sign: '-' | '+';
30}
31export interface Filter {
32 name: string;
33 val: any;
34 op: Operator;
35}
36/**
37 * Build a Query object.
38 *
39 * **Queries are built with {module:datastore#createQuery} and
40 * {@link Transaction#createQuery}.**
41 *
42 * @see {@link http://goo.gl/Cag0r6| Datastore Queries}
43 *
44 * @class
45 * @param {Datastore|Transaction} scope The parent scope the query was created
46 * from.
47 * @param {string} [namespace] Namespace to query entities from.
48 * @param {string[]} kinds Kind to query.
49 *
50 * @example
51 * ```
52 * const {Datastore} = require('@google-cloud/datastore');
53 * const datastore = new Datastore();
54 * const query = datastore.createQuery('AnimalNamespace', 'Lion');
55 * ```
56 */
57declare class Query {
58 scope?: Datastore | Transaction;
59 namespace?: string | null;
60 kinds: string[];
61 filters: Filter[];
62 orders: Order[];
63 groupByVal: Array<{}>;
64 selectVal: Array<{}>;
65 startVal: string | Buffer | null;
66 endVal: string | Buffer | null;
67 limitVal: number;
68 offsetVal: number;
69 constructor(scope?: Datastore | Transaction, kinds?: string[] | null);
70 constructor(scope?: Datastore | Transaction, namespace?: string | null, kinds?: string[]);
71 /**
72 * Datastore allows querying on properties. Supported comparison operators
73 * are `=`, `<`, `>`, `<=`, and `>=`. "Not equal" and `IN` operators are
74 * currently not supported.
75 *
76 * *To filter by ancestors, see {module:datastore/query#hasAncestor}.*
77 *
78 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-property-filter-nodejs| Datastore Filters}
79 *
80 * @param {string} property The field name.
81 * @param {string} [operator="="] Operator (=, <, >, <=, >=).
82 * @param {*} value Value to compare property to.
83 * @returns {Query}
84 *
85 * @example
86 * ```
87 * const {Datastore} = require('@google-cloud/datastore');
88 * const datastore = new Datastore();
89 * const query = datastore.createQuery('Company');
90 *
91 * //-
92 * // List all companies that are located in California.
93 * //-
94 * const caliQuery = query.filter('state', 'CA');
95 *
96 * //-
97 * // List all companies named Google that have less than 400 employees.
98 * //-
99 * const companyQuery = query
100 * .filter('name', 'Google')
101 * .filter('size', '<', 400);
102 *
103 * //-
104 * // To filter by key, use `__key__` for the property name. Filter on keys
105 * // stored as properties is not currently supported.
106 * //-
107 * const key = datastore.key(['Company', 'Google']);
108 * const keyQuery = query.filter('__key__', key);
109 * ```
110 */
111 filter(property: string, value: {}): Query;
112 filter(property: string, operator: Operator, value: {}): Query;
113 /**
114 * Filter a query by ancestors.
115 *
116 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-ancestor-query-nodejs| Datastore Ancestor Filters}
117 *
118 * @param {Key} key Key object to filter by.
119 * @returns {Query}
120 *
121 * @example
122 * ```
123 * const {Datastore} = require('@google-cloud/datastore');
124 * const datastore = new Datastore();
125 * const query = datastore.createQuery('MyKind');
126 * const ancestoryQuery = query.hasAncestor(datastore.key(['Parent', 123]));
127 * ```
128 */
129 hasAncestor(key: Key): this;
130 /**
131 * Sort the results by a property name in ascending or descending order. By
132 * default, an ascending sort order will be used.
133 *
134 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-ascending-sort-nodejs| Datastore Sort Orders}
135 *
136 * @param {string} property The property to order by.
137 * @param {object} [options] Options object.
138 * @param {boolean} [options.descending=false] Sort the results by a property
139 * name in descending order.
140 * @returns {Query}
141 *
142 * @example
143 * ```
144 * const {Datastore} = require('@google-cloud/datastore');
145 * const datastore = new Datastore();
146 * const companyQuery = datastore.createQuery('Company');
147 *
148 * // Sort by size ascendingly.
149 * const companiesAscending = companyQuery.order('size');
150 *
151 * // Sort by size descendingly.
152 * const companiesDescending = companyQuery.order('size', {
153 * descending: true
154 * });
155 * ```
156 */
157 order(property: string, options?: OrderOptions): this;
158 /**
159 * Group query results by a list of properties.
160 *
161 * @param {array} properties Properties to group by.
162 * @returns {Query}
163 *
164 * @example
165 * ```
166 * const {Datastore} = require('@google-cloud/datastore');
167 * const datastore = new Datastore();
168 * const companyQuery = datastore.createQuery('Company');
169 * const groupedQuery = companyQuery.groupBy(['name', 'size']);
170 * ```
171 */
172 groupBy(fieldNames: string | string[]): this;
173 /**
174 * Retrieve only select properties from the matched entities.
175 *
176 * Queries that select a subset of properties are called Projection Queries.
177 *
178 * @see {@link https://cloud.google.com/datastore/docs/concepts/projectionqueries| Projection Queries}
179 *
180 * @param {string|string[]} fieldNames Properties to return from the matched
181 * entities.
182 * @returns {Query}
183 *
184 * @example
185 * ```
186 * const {Datastore} = require('@google-cloud/datastore');
187 * const datastore = new Datastore();
188 * const companyQuery = datastore.createQuery('Company');
189 *
190 * // Only retrieve the name property.
191 * const selectQuery = companyQuery.select('name');
192 *
193 * // Only retrieve the name and size properties.
194 * const selectQuery = companyQuery.select(['name', 'size']);
195 * ```
196 */
197 select(fieldNames: string | string[]): this;
198 /**
199 * Set a starting cursor to a query.
200 *
201 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#cursors_limits_and_offsets| Query Cursors}
202 *
203 * @param {string} cursorToken The starting cursor token.
204 * @returns {Query}
205 *
206 * @example
207 * ```
208 * const {Datastore} = require('@google-cloud/datastore');
209 * const datastore = new Datastore();
210 * const companyQuery = datastore.createQuery('Company');
211 *
212 * const cursorToken = 'X';
213 *
214 * // Retrieve results starting from cursorToken.
215 * const startQuery = companyQuery.start(cursorToken);
216 * ```
217 */
218 start(start: string | Buffer): this;
219 /**
220 * Set an ending cursor to a query.
221 *
222 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#Datastore_Query_cursors| Query Cursors}
223 *
224 * @param {string} cursorToken The ending cursor token.
225 * @returns {Query}
226 *
227 * @example
228 * ```
229 * const {Datastore} = require('@google-cloud/datastore');
230 * const datastore = new Datastore();
231 * const companyQuery = datastore.createQuery('Company');
232 *
233 * const cursorToken = 'X';
234 *
235 * // Retrieve results limited to the extent of cursorToken.
236 * const endQuery = companyQuery.end(cursorToken);
237 * ```
238 */
239 end(end: string | Buffer): this;
240 /**
241 * Set a limit on a query.
242 *
243 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-limit-nodejs| Query Limits}
244 *
245 * @param {number} n The number of results to limit the query to.
246 * @returns {Query}
247 *
248 * @example
249 * ```
250 * const {Datastore} = require('@google-cloud/datastore');
251 * const datastore = new Datastore();
252 * const companyQuery = datastore.createQuery('Company');
253 *
254 * // Limit the results to 10 entities.
255 * const limitQuery = companyQuery.limit(10);
256 * ```
257 */
258 limit(n: number): this;
259 /**
260 * Set an offset on a query.
261 *
262 * @see {@link https://cloud.google.com/datastore/docs/concepts/queries#datastore-limit-nodejs| Query Offsets}
263 *
264 * @param {number} n The offset to start from after the start cursor.
265 * @returns {Query}
266 *
267 * @example
268 * ```
269 * const {Datastore} = require('@google-cloud/datastore');
270 * const datastore = new Datastore();
271 * const companyQuery = datastore.createQuery('Company');
272 *
273 * // Start from the 101st result.
274 * const offsetQuery = companyQuery.offset(100);
275 * ```
276 */
277 offset(n: number): this;
278 /**
279 * Run the query.
280 *
281 * @param {object} [options] Optional configuration.
282 * @param {string} [options.consistency] Specify either `strong` or `eventual`.
283 * If not specified, default values are chosen by Datastore for the
284 * operation. Learn more about strong and eventual consistency
285 * [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).
286 * @param {object} [options.gaxOptions] Request configuration options, outlined
287 * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
288 * @param {boolean | IntegerTypeCastOptions} [options.wrapNumbers=false]
289 * Wrap values of integerValue type in {@link Datastore#Int} objects.
290 * If a `boolean`, this will wrap values in {@link Datastore#Int} objects.
291 * If an `object`, this will return a value returned by
292 * `wrapNumbers.integerTypeCastFunction`.
293 * Please see {@link IntegerTypeCastOptions} for options descriptions.
294 * @param {function} [callback] The callback function. If omitted, a readable
295 * stream instance is returned.
296 * @param {?error} callback.err An error returned while making this request
297 * @param {object[]} callback.entities A list of entities.
298 * @param {object} callback.info An object useful for pagination.
299 * @param {?string} callback.info.endCursor Use this in a follow-up query to
300 * begin from where these results ended.
301 * @param {string} callback.info.moreResults Datastore responds with one of:
302 *
303 * - {@link Datastore#MORE_RESULTS_AFTER_LIMIT}: There *may* be more
304 * results after the specified limit.
305 * - {@link Datastore#MORE_RESULTS_AFTER_CURSOR}: There *may* be more
306 * results after the specified end cursor.
307 * - {@link Datastore#NO_MORE_RESULTS}: There are no more results.
308 *
309 * @example
310 * ```
311 * const {Datastore} = require('@google-cloud/datastore');
312 * const datastore = new Datastore();
313 * const query = datastore.createQuery('Company');
314 *
315 * query.run((err, entities, info) => {
316 * // entities = An array of records.
317 *
318 * // Access the Key object for an entity.
319 * const firstEntityKey = entities[0][datastore.KEY];
320 * });
321 *
322 * //-
323 * // A keys-only query returns just the keys of the result entities instead
324 * of
325 * // the entities themselves, at lower latency and cost.
326 * //-
327 * query.select('__key__');
328 *
329 * query.run((err, entities) => {
330 * const keys = entities.map((entity) => {
331 * return entity[datastore.KEY];
332 * });
333 * });
334 *
335 * //-
336 * // If the callback is omitted, we'll return a Promise.
337 * //-
338 * query.run().then((data) => {
339 * const entities = data[0];
340 * });
341 * ```
342 */
343 run(options?: RunQueryOptions): Promise<RunQueryResponse>;
344 run(options: RunQueryOptions, callback: RunQueryCallback): void;
345 run(callback: RunQueryCallback): void;
346 /**
347 * Run the query as a readable object stream.
348 *
349 * @method Query#runStream
350 * @param {object} [options] Optional configuration. See
351 * {@link Query#run} for a complete list of options.
352 * @returns {stream}
353 *
354 * @example
355 * ```
356 * const {Datastore} = require('@google-cloud/datastore');
357 * const datastore = new Datastore();
358 * const query = datastore.createQuery('Company');
359 *
360 * query.runStream()
361 * .on('error', console.error)
362 * .on('data', function (entity) {
363 * // Access the Key object for this entity.
364 * const key = entity[datastore.KEY];
365 * })
366 * .on('info', (info) => {})
367 * .on('end', () => {
368 * // All entities retrieved.
369 * });
370 *
371 * //-
372 * // If you anticipate many results, you can end a stream early to prevent
373 * // unnecessary processing and API requests.
374 * //-
375 * query.runStream()
376 * .on('data', function (entity) {
377 * this.end();
378 * });
379 * ```
380 */
381 runStream(options?: RunQueryStreamOptions): import("stream").Transform;
382}
383export interface QueryProto {
384 startCursor?: string | Buffer;
385 distinctOn: {};
386 kind: {};
387 order: {};
388 projection: {};
389 endCursor?: string | Buffer;
390 limit?: {};
391 offset?: number;
392 filter?: {};
393}
394/**
395 * Reference to the {@link Query} class.
396 * @name module:@google-cloud/datastore.Query
397 * @see Query
398 */
399export { Query };
400export interface IntegerTypeCastOptions {
401 integerTypeCastFunction: Function;
402 properties?: string | string[];
403}
404export interface RunQueryOptions {
405 consistency?: 'strong' | 'eventual';
406 gaxOptions?: CallOptions;
407 wrapNumbers?: boolean | IntegerTypeCastOptions;
408}
409export interface RunQueryCallback {
410 (err: Error | null, entities?: Entity[], info?: RunQueryInfo): void;
411}
412export declare type RunQueryResponse = [Entity[], RunQueryInfo];
413export interface RunQueryInfo {
414 endCursor?: string;
415 moreResults?: 'MORE_RESULTS_TYPE_UNSPECIFIED' | 'NOT_FINISHED' | 'MORE_RESULTS_AFTER_LIMIT' | 'MORE_RESULTS_AFTER_CURSOR' | 'NO_MORE_RESULTS';
416}