import { GlideRecord } from "./GlideRecord"; /** * TypeScript definitions for ServiceNow GlideQuery */ /** * Represents a single record returned from a query */ interface GlideQueryRecord { [field: string]: any; } /** * Optional container that may or may not contain a value */ interface Optional { /** * Returns the value if present, otherwise returns the provided default value */ orElse(defaultValue: T): T; /** * Returns the value if present */ get(): T | undefined; /** * Returns true if a value is present */ isPresent(): boolean; /** * Executes the provided function if a value is present */ ifPresent(consumer: (value: T) => void): void; } /** * Stream interface for processing query results */ interface Stream { /** * Converts the stream to an array */ toArray(maxSize?: number): T[]; /** * Executes the provided function for each element */ forEach(callback: (item: T) => void): void; /** * Filters elements based on a predicate */ filter(predicate: (item: T) => boolean): Stream; /** * Maps elements to a new form */ map(mapper: (item: T) => R): Stream; /** * Reduces the stream to a single value */ reduce(accumulator: (acc: R, item: T) => R, initialValue: R): R; /** * Returns the first element as an Optional */ findFirst(): Optional; /** * Limits the stream to the specified number of elements */ limit(maxSize: number): Stream; /** * Returns true if any element matches the predicate */ anyMatch(predicate: (item: T) => boolean): boolean; /** * Returns true if all elements match the predicate */ allMatch(predicate: (item: T) => boolean): boolean; /** * Returns true if no elements match the predicate */ noneMatch(predicate: (item: T) => boolean): boolean; } /** * Valid comparison operators for where clauses */ type ComparisonOperator = '=' | '!=' | '>' | '>=' | '<' | '<='; /** * Valid array operators */ type ArrayOperator = 'IN' | 'NOT IN' | 'BETWEEN'; /** * Valid string operators */ type StringOperator = | 'STARTSWITH' | 'ENDSWITH' | 'CONTAINS' | 'DOES NOT CONTAIN' | 'INSTANCEOF' | 'SAMEAS' | 'NSAMEAS' | 'GT_FIELD' | 'LT_FIELD' | 'GT_OR_EQUALS_FIELD' | 'LT_OR_EQUALS_FIELD' | 'DYNAMIC' | 'EMPTYSTRING' | 'ANYTHING' | 'LIKE' | 'NOT LIKE' | 'ON'; /** * All valid operators */ type WhereOperator = ComparisonOperator | ArrayOperator | StringOperator; /** * Valid aggregate function types */ type AggregateType = 'sum' | 'avg' | 'min' | 'max' | 'count'; /** * Field flags that can be appended to field names */ type FieldFlag = 'DISPLAY' | 'CURRENCY_CODE' | 'CURRENCY_DISPLAY' | 'CURRENCY_STRING'; /** * Field name with optional flag (e.g., 'company$DISPLAY') */ type FieldWithFlag = string; /** * Key-value object for record data */ interface KeyValues { [key: string]: any; } /** * Options for GlideQuery constructor */ interface GlideQueryOptions { scope?: string; } /** * Result of updateMultiple operation */ interface UpdateMultipleResult { rowCount: number; } /** * Main GlideQuery class used to build and execute queries. * * @example * var query = new GlideQuery('sys_user'); */ export declare class GlideQuery { /** * Creates a new GlideQuery instance * * @param table - Table to query * @param plan - Contains an array of Step objects describing the query (internal use) * @param options - Additional options for the query */ constructor(table: T, plan?: any[], options?: GlideQueryOptions); readonly table: T; readonly plan: any[]; readonly type: 'GlideQuery'; // WHERE CLAUSES /** * Returns a new GlideQuery containing a where clause. * * @example * new GlideQuery('sys_user') * .where('active', true) * .where('last_login', '>', '2016-04-15') * * @example * // Nested query: active = true AND (priority = 1 OR severity = 1) * new GlideQuery('incident') * .where('active', true) * .where(new GlideQuery() * .where('priority', 1) * .orWhere('severity', 1)) */ where(field: string, value: any): GlideQuery; where(field: string, operator: WhereOperator, value: any): GlideQuery; where(query: GlideQuery): GlideQuery; /** * Returns a new GlideQuery containing an orWhere clause. * Must be preceded by a single where, whereNull, or whereNotNull expression. * * @example * new GlideQuery('sys_user') * .where('failed_attempts', '>', 0) * .orWhere('last_login', '<', '2019-04-15') * .select() */ orWhere(field: string, value: any): GlideQuery; orWhere(field: string, operator: WhereOperator, value: any): GlideQuery; orWhere(query: GlideQuery): GlideQuery; /** * Returns a new GlideQuery containing NOT NULL clause. * * @example * new GlideQuery('sys_user') * .whereNotNull('first_name') */ whereNotNull(field: string): GlideQuery; /** * Returns a new GlideQuery containing NOT NULL clause (OR version). * Must be preceded by a single where, whereNull, or whereNotNull expression. * * @example * new GlideQuery('sys_user') * .whereNotNull('first_name') * .orWhereNotNull('last_name') */ orWhereNotNull(field: string): GlideQuery; /** * Returns a new GlideQuery containing WHERE NULL clause. * * @example * new GlideQuery('sys_user') * .whereNull('last_name') */ whereNull(field: string): GlideQuery; /** * Returns a new GlideQuery containing WHERE NULL clause (OR version). * Must be preceded by a single where, whereNull, or whereNotNull expression. * * @example * new GlideQuery('sys_user') * .whereNull('last_name') * .orWhereNull('first_name') */ orWhereNull(field: string): GlideQuery; // RETRIEVE OPERATIONS /** * Returns a single record using keyValues as a set of key-values to query by. * Assumes the '=' operator for each key-value. * * @example * var user = new GlideQuery('sys_user') * .getBy({ * first_name: 'Fred', * last_name: 'Luddy' * }, ['first_name', 'last_name', 'city', 'active']) * .orElse({ * first_name: 'Nobody', * last_name: 'Found', * city: 'Nowhere', * active: false * }); */ getBy(keyValues: KeyValues, selectedFields?: string[]): Optional; /** * Returns a single record by querying primary key. * * @example * var user = new GlideQuery('sys_user') * .get('5137153cc611227c000bbd1bd8cd2005', ['first_name', 'last_name']) * .orElse({ first_name: 'Default', last_name: 'User' }); */ get(key: string, selectFields?: string[]): Optional; /** * Specifies which fields to return and returns a Stream containing the results. * Records aren't actually read until a terminal Stream method is called. * * @example * var stream = new GlideQuery('sys_user') * .select('first_name', 'last_name', 'company$DISPLAY'); */ select(...fields: FieldWithFlag[]): Stream; /** * Similar to select(), but only returns an Optional with a single record. * More efficient than select() if you only need one record. * * @example * var user = new GlideQuery('sys_user') * .where('zip', '12345') * .whereNotNull('last_name') * .selectOne('first_name', 'last_name', 'company$DISPLAY') * .get(); */ selectOne(...fields: FieldWithFlag[]): Optional; // WRITE OPERATIONS /** * Inserts a single record, returning an Optional of the newly-created record. * * @example * var fred = new GlideQuery('sys_user') * .insert({ first_name: 'Fred', last_name: 'Luddy' }) * .get(); * * @throws {Error} When insert fails (e.g., when a business rule rejects the insert) */ insert(keyValues: KeyValues, selectFields?: string[]): Optional; /** * Updates an existing record or inserts a new one if it doesn't exist. * Uses the primary key(s) in the recordValues object. * * @example * // Insert a new record * var user = new GlideQuery('sys_user') * .insertOrUpdate({ * first_name: 'George', * last_name: 'Griffey' * }) * .orElse(null); * * @example * // Update existing record * var user = new GlideQuery('sys_user') * .insertOrUpdate({ * sys_id: '2d0efd6c73662300bb513198caf6a72e', * first_name: 'George', * last_name: 'Griffey' * }) * .orElse(null); * * @throws {Error} When insert fails */ insertOrUpdate(changes: KeyValues, selectFields?: string[], reason?: string): Optional; /** * Updates an existing record. Requires a where call specifying all existing primary keys. * Returns an Optional of the newly-updated record. * * @example * new GlideQuery('sys_user') * .where('sys_id', userId) * .update({ city: 'Los Angeles' }); * * @throws {Error} When update fails */ update( changes: KeyValues, selectFields?: string[], reason?: string, prefetchedSchema?: any, planOverride?: any, insertWhenNotFound?: boolean ): Optional; /** * Updates all records matching the query with the values in the changes object. * Returns the number of records updated. * * @example * new GlideQuery('sys_user') * .where('active', false) * .where('last_name', 'Griffey') * .updateMultiple({ active: true }); */ updateMultiple(changes: KeyValues): UpdateMultipleResult; /** * Deletes all records matching the query. * * @example * new GlideQuery('sys_user') * .where('active', true) * .where('last_name', 'Jeter') * .deleteMultiple(); */ deleteMultiple(): void; /** * Alias for deleteMultiple() */ del(): void; // QUERY MODIFIERS /** * Returns a GlideQuery which disables the running of business rules, script engines, and audit. * * @example * var query = new GlideQuery('task') * .disableWorkflow() * .where('active', true) * .updateMultiple({ priority: 1 }); */ disableWorkflow(): GlideQuery; /** * Returns a GlideQuery which does not update sys fields such as sys_created_on, sys_updated_on, and sys_mod_count. * Equivalent to using autoSysFields(false) with GlideRecord. * * @example * new GlideQuery('task') * .disableAutoSysFields() * .insert({ description: 'example', priority: 1 }); */ disableAutoSysFields(): GlideQuery; /** * Returns a GlideQuery which forces an update even when no changes are made. * Useful when you want to force a business rule to execute. * Note: Cannot be called from a non-global scope. * * @example * new GlideQuery('task') * .forceUpdate() * .where('sys_id', taskId) * .update() */ forceUpdate(): GlideQuery; /** * Returns a GlideQuery which specifies that records should be returned in ascending order by a given field. * * @example * var query = new GlideQuery('incident') * .orderBy('number'); */ orderBy(field: string): GlideQuery; /** * Returns a GlideQuery which specifies that records should be returned in descending order. * Can be used with aggregate queries. * * @example * var query = new GlideQuery('incident') * .orderByDesc('number'); * * @example * new GlideQuery('incident') * .aggregate('sum', 'child_incidents') * .groupBy('category') * .orderByDesc('sum', 'child_incidents') */ orderByDesc(field: string): GlideQuery; orderByDesc(aggregateType: AggregateType, field: string): GlideQuery; /** * Returns a GlideQuery which limits the number of records returned. * * @example * var incidents = new GlideQuery('incident') * .limit(20) * .select('priority', 'description'); */ limit(limit: number): GlideQuery; /** * By default GlideQuery uses GlideRecord. By calling withAcls(), GlideQuery will use GlideRecordSecure, * which honors ACLs. * * @example * var users = new GlideQuery('sys_user') * .withAcls() * .limit(20) * .orderByDesc('first_name') * .select('first_name') * .toArray(100); */ withAcls(): GlideQuery; /** * By calling withSecurityDataFilters(), GlideQuery will apply Security Data Filters to the query. * * @example * var users = new GlideQuery('sys_user') * .withSecurityDataFilters() * .limit(20) * .orderByDesc('first_name') * .select('first_name') * .toArray(100); */ withSecurityDataFilters(): GlideQuery; // AGGREGATE FUNCTIONS /** * Returns the aggregate average of a given numeric field. * Can be used on fields of type: integer, longint, float, double, currency. * * @example * var faults = new GlideQuery('cmdb_ci') * .avg('fault_count') * .orElse(0); * * @throws {Error} When invalid field given */ avg(field: string): Optional; /** * Returns the aggregate maximum of a given field. * * @example * var name = new GlideQuery('sys_user') * .max('first_name') * .orElse(''); * * @throws {Error} When invalid field given */ max(field: string): Optional; /** * Returns the aggregate minimum of a given field. * * @example * var lowestModCount = new GlideQuery('sys_user') * .min('sys_mod_count') * .orElse(0); * * @throws {Error} When invalid field given */ min(field: string): Optional; /** * Returns the aggregate sum of a given numeric field. * Can be used on fields of type: integer, longint, float, double, currency. * * @example * var totalFaults = new GlideQuery('cmdb_ci') * .sum('fault_count') * .orElse(0); * * @throws {Error} When invalid field given */ sum(field: string): Optional; /** * Returns the row count of records matching the query. * * @example * var userCount = new GlideQuery('sys_user') * .where('active', true) * .count(); */ count(): number; /** * Groups query results. Used with aggregate(). * * @example * new GlideQuery('task') * .aggregate('count') * .groupBy('contact_type') * .select() */ groupBy(...fields: string[]): GlideQuery; /** * Aggregates a field using an aggregate function. * Used to build queries which aggregate against multiple fields and/or multiple aggregate functions. * * @example * new GlideQuery('task') * .aggregate('avg', 'reassignment_count') * .groupBy('contact_type') * .select() */ aggregate(aggregateType: AggregateType, field: string): GlideQuery; /** * Filters aggregate groups. Used with aggregate() and groupBy(). * * @example * new GlideQuery('task') * .where('description', description) * .groupBy('priority') * .aggregate('sum', 'reassignment_count') * .having('sum', 'reassignment_count', '>', 4) * .select() */ having( aggregateType: AggregateType, field: string, operator: ComparisonOperator, value: number ): GlideQuery; // UTILITY METHODS /** * Returns a GlideRecord representing the current GlideQuery. * The GlideRecord has not yet been queried, so query() may need to be called. * May be a GlideAggregate in case aggregate queries are used. * * @example * var userGr = new GlideQuery('sys_user') * .where('active', true) * .whereNotNull('first_name') * .limit(10) * .toGlideRecord(); * userGr.query(); * while (userGr.next()) { * doSomething(userGr); * } */ toGlideRecord(): GlideRecord; /** * Returns a string representation of the GlideQuery. */ toString(): string; // STATIC METHODS /** * Parses an encoded query string into a GlideQuery. * * @example * GlideQuery.parse('task', 'active=true^descriptionISNOTEMPTY') * .select('description') * .forEach(function (task) { gs.info(task.description); }); */ static parse(table: string, encodedQuery: string): GlideQuery; }