, throwIfNone?: boolean, throwIfMultiple?: boolean): E;
/** Lookup an object by primary key
* @param value the primary key value to lookup
* @param throwIfNotFound an optional flag which controls whether an error is throw if no result is found (default: true)
* @returns matching object
*/
lookup(value: K[P], throwIfNotFound?: boolean): E;
/** Get the first result, except that exactly one result is expected (equivalent to first(query, true, true))
* @returns a single object matching the query specified
* @throws Error if the query returns no results or more than one result
*/
single(query: MemDbQueryLike): E;
/** Starts a chained filter operation and returns a search result set which can be further refined
* @param func: a javascript Array.filter() style function that accepts an object
* and returns a flag indicating whether the object is a match or not
*/
where(func: (doc: E) => boolean): ResultSetLike;
/** Add a document to this collection
*/
add(docs: E, dstResultInfo?: Changes.CollectionChangeTracker): E;
/** Add a document to this collection AND do not run any collection actions on the document,
* such as generating primary keys
*/
addNoModify(docs: E, dstResultInfo?: Changes.CollectionChangeTracker): E;
/** Add multiple documents to this collection
*/
addAll(docs: E[], dstResultInfo?: Changes.CollectionChangeTracker): E[];
/** Add multiple documents to this collection AND do not run any collection actions on the documents,
* such as generating primary keys
*/
addAllNoModify(docs: E[], dstResultInfo?: Changes.CollectionChangeTracker): E[];
/** Queries this collection, if one or more matches are found, those documents are updated with the properties from 'obj' as defined in updateWhere(),
* if not matches are found, then the object/document is added to this collection.
* @param query: a mongo style query object, supports query fields like '$le', '$eq', '$ne', etc.
* @param obj: the properties to overwrite onto each document matching the provided query
*/
addOrUpdateWhere(query: MemDbQueryLike, obj: Partial & K, noModify?: boolean, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Queries this collection, if one or more matches are found, those documents are updated with the properties from 'obj' as defined in updateWhere(),
* if not matches are found, then the object/document is added to this collection AND no collection actions
* are applied to the added document, such as generating primary keys.
* @param query: a mongo style query object, supports query fields like '$le', '$eq', '$ne', etc.
* @param obj: the properties to overwrite onto each document matching the provided query
*/
addOrUpdateWhereNoModify(query: MemDbQueryLike, obj: Partial & K, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Queries this collection based on the primary key of each of the input document,
* if one or more matches are found for a given document, then those matching documents are updated
* with the properties from 'obj' as defined in updateWhere(),
* if not matches are found, then the documents are added to this collection.
* @param query: a mongo style query object, supports query fields like '$le', '$eq', '$ne', etc.
* @param obj: the properties to overwrite onto each document matching the provided query
*/
addOrUpdateAll(updatesArray: (Partial & K)[], noModify?: boolean, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Queries this collection based on the primary key of each of the input documents,
* if one or more matches are found for a given document, then those matching documents are updated
* with the properties from 'obj' as defined in updateWhere(),
* if not matches are found for a given doucment, then the document is added to this collection
* AND no collection actions are applied to the added document, such as generating primary keys.
* @param query: a mongo style query object, supports query fields like '$le', '$eq', '$ne', etc.
* @param obj: the properties to overwrite onto each document matching the provided query
*/
addOrUpdateAllNoModify(updatesArray: (Partial & K)[], dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Mark an existing document in this collection modified.
* The document specified must already exist in the collection
*/
update(doc: E, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Mark multiple existing documents in this collection modified.
* The documents specified must all already exist in the collection
*/
updateAll(docs: E[], dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Update documents matching a query with properties from a provided update object
* @param query: a mongo style query object, supports query fields like '$le', '$eq', '$ne', etc.
* @param obj: the properties to overwrite onto each document matching the provided query
*/
updateWhere(query: MemDbQueryLike, obj: Partial, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Remove a document from this collection.
*/
remove(doc: E, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Remove documents from this collection that match a given query
*/
removeWhere(query: MemDbQueryLike, dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Remove all documents from this collection
*/
clearCollection(dstResultInfo?: Changes.CollectionChangeTracker): void;
/** Remove this collection from the database instance
*/
deleteCollection(dstResultInfo?: Changes.CollectionChangeTracker): void;
}
// Work around for DataCollection.ts containing a class named 'DataCollection' and trying to implement this interface
interface _DataCollection extends DataCollection { }
/** Resultset allows for chainable queries. Intended to be instanced internally.
* Collection.find(), Collection.where(), and Collection.chain() instantiate this.
* Example:
* mycollection.chain()
* .find({ 'doors' : 4 })
* .where(function(obj) { return obj.name === 'Toyota' })
* .data();
* @template E the type of data stored in this result set
*/
interface MemDbResultset {
/** The collection which this Resultset will query against */
collection: MemDbCollection;
searchIsChained: boolean;
filteredrows: number[]; // technically number[] (e.g. = Object.keys(this.collection.data))
filterInitialized: boolean;
/** Override of toJSON to avoid circular references */
toJSON(): MemDbResultset;
/** Allows you to limit the number of documents passed to next chain operation.
* A resultset copy() is made to avoid altering original resultset.
* @param qty The number of documents to return.
* @returns Returns a copy of the resultset, limited by qty, for subsequent chain ops.
*/
limit(qty: number): MemDbResultset;
/** Used for skipping 'pos' number of documents in the resultset.
* @param pos Number of documents to skip; all preceding documents are filtered out.
* @returns Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops.
*/
offset(pos: number): MemDbResultset;
/** To support reuse of resultset in branched query situations.
* @returns Returns a copy of the resultset (set) but the underlying document references will be the same.
*/
copy(): MemDbResultset;
// add branch() as alias of copy()
branch(): MemDbResultset;
/** User supplied compare function is provided two documents to compare. (chainable)
* Example:
* rslt.sort(function(obj1, obj2) {
* if (obj1.name === obj2.name) return 0;
* if (obj1.name > obj2.name) return 1;
* if (obj1.name < obj2.name) return -1;
* });
* @param compareFunc A javascript compare function used for sorting.
* @returns Reference to this resultset, sorted, for future chain operations.
*/
sort(compareFunc: (a: E, b: E) => number): MemDbResultset;
/** Simpler, loose evaluation for user to sort based on a property name. (chainable)
* @param propname name of property to sort by.
* @param isdesc (Optional) If true, the property will be sorted in descending order
* @returns Reference to this resultset, sorted, for future chain operations.
*/
simplesort(propname: keyof E & string, isdesc?: boolean): MemDbResultset;
/** helper method for compoundsort(), performing individual object comparisons
* @param properties array of property names, in order, by which to evaluate sort order
* @param obj1 first object to compare
* @param obj2 second object to compare
* @returns 0, -1, or 1 to designate if identical (sortwise) or which should be first
*/
compoundeval(properties: (keyof E | [keyof E, boolean])[], obj1: E & MemDbObj, obj2: E & MemDbObj): -1 | 0 | 1;
/** Allows sorting a resultset based on multiple columns.
* Example : rs.compoundsort(['age', 'name']); to sort by age and then name (both ascending)
* Example : rs.compoundsort(['age', ['name', true]); to sort by age (ascending) and then by name (descending)
* @param properties array of property names or subarray of [propertyname, isdesc] used evaluate sort order
* @returns Reference to this resultset, sorted, for future chain operations.
*/
compoundsort(properties: (keyof E | [keyof E, boolean])[]): MemDbResultset;
/** oversee the operation of OR'ed query expressions.
* OR'ed expression evaluation runs each expression individually against the full collection,
* and finally does a set OR on each expression's results.
* Each evaluation can utilize a binary index to prevent multiple linear array scans.
* @param expressionArray array of expressions
* @returns this resultset for further chain ops.
*/
findOr(expressionArray: MemDbQuery[]): MemDbResultset;
/** oversee the operation of AND'ed query expressions.
* AND'ed expression evaluation runs each expression progressively against the full collection,
* internally utilizing existing chained resultset functionality.
* Only the first filter can utilize a binary index.
* @param expressionArray array of expressions
* @returns this resultset for further chain ops.
*/
findAnd(expressionArray: MemDbQuery[]): MemDbResultset;
/** Used for querying via a mongo-style query object.
* @param query A mongo-style query object used for filtering current results.
* @param firstOnly (Optional) Used by collection.findOne()
* @returns this resultset for further chain ops.
*/
find(query: MemDbQuery | null | undefined): MemDbResultset;
find(query: MemDbQuery | null | undefined, firstOnly: false): MemDbResultset;
find(query: MemDbQuery | null | undefined, firstOnly: true): E & MemDbObj;
find(query: MemDbQuery | null | undefined, firstOnly?: boolean): (E & MemDbObj) | MemDbResultset;
/** Used for filtering via a javascript filter function.
* @param searchFunc A javascript function used for filtering current results by.
* @returns this resultset for further chain ops.
*/
where(searchFunc: (obj: E) => boolean): MemDbResultset;
/** Terminates the chain and returns array of filtered documents
* @param options data materialize options, 'clone' option to return cloned documents rather than live data collection documents
* @returns Array of documents in the resultset
*/
data(options?: { clone?: boolean | CloneType } | null): (E & MemDbObj)[];
/** The number of results in the result set
* @returns the current number of results in the result set
*/
count(): number;
/** used to run an update operation on all documents currently in the resultset.
* @param updateFunc User supplied updateFunction(obj) will be executed for each document object.
* @returns this resultset for further chain ops.
*/
update(updateFunc: (obj: E) => U): MemDbResultset;
/** removes all document objects which are currently in resultset from collection (as well as resultset)
* @returns this (empty) resultset for further chain ops.
*/
remove(): MemDbResultset;
/** transform this result set via user supplied mapping functions
* @param mapFun this function transforms a single document
* @param options data mapping options, 'clone' option to clone documents from this result set to
* the new returned result set rather than references to the same live documents
* @returns A new result set transformed from this result set's data using the mapFun
*/
map(mapFun: (currentValue: E, index: number, array: E[]) => U, options?: { clone?: boolean } | null): MemDbResultset;
}
/** DynamicView class is a versatile 'live' view class which can have filters and sorts applied.
* Collection.addDynamicView(name) instantiates this DynamicView object and notifies it
* whenever documents are add/updated/removed so it can remain up-to-date. (chainable)
* Examples:
* var mydv = mycollection.addDynamicView('test'); // default is non-persistent
* mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; });
* mydv.applyFind({ 'doors' : 4 });
* var results = mydv.data();
* @template E the type of data stored in this dynamic view
*/
interface MemDbDynamicView {
cachedresultset: MemDbResultset | null;
/** A reference to the collection to work against */
collection: MemDbCollection;
/** keep ordered filter pipeline */
filterPipeline: ({ type: "find"; val: MemDbQuery } | { type: "where"; val: (obj: E) => boolean })[];
/** The name of this dynamic view */
name: string;
/** (Optional) If true, the results will be copied into an internal array for read efficiency or binding to. */
persistent: boolean;
resultdata: E[];
resultsdirty: boolean;
resultset: MemDbResultset;
// sorting member variables - we only support one active search, applied using applySort() or applySimpleSort()
sortCriteria: [keyof E, boolean][] | null;
sortDirty: boolean;
sortFunction: ((a: E, b: E) => number) | null;
// for now just 1 event for when we rebuilt lazy view
events: TsEventEmitter<{
'rebuild': any[];
}>;
/** intended for use immediately after deserialization (loading)
* This will clear out and reapply filterPipeline ops, recreating the view.
* Since where filters do not persist correctly, this method allows
* restoring the view to state where user can re-apply those where filters.
* @param options (Optional) allows specification of 'removeWhereFilters' option
* @returns This dynamic view for further chained ops.
*/
rematerialize(options?: { removeWhereFilters?: boolean; }): MemDbDynamicView;
/** Makes a copy of the internal resultset for branched queries.
* Unlike this dynamic view, the branched resultset will not be 'live' updated,
* so your branched query should be immediately resolved and not held for future evaluation.
* @returns A copy of the internal resultset for branched queries.
*/
branchResultset(): MemDbResultset;
/** Override of toJSON to avoid circular references */
toJSON(): MemDbDynamicView;
/** Used to apply a sort to the dynamic view
* @param compareFunc a javascript compare function used for sorting
* @returns this DynamicView object, for further chain ops.
*/
applySort(compareFunc: ((a: E, b: E) => number) | null): MemDbDynamicView;
/** Used to specify a property used for view translation.
* @param propname Name of property by which to sort.
* @param isdesc (Optional) If true, the sort will be in descending order.
* @returns this DynamicView object, for further chain ops.
*/
applySimpleSort(propname: keyof E & string, isdesc?: boolean): MemDbDynamicView;
/** Allows sorting a resultset based on multiple columns.
* Example: dv.applySortCriteria(['age', 'name']); to sort by age and then name (both ascending)
* Example: dv.applySortCriteria(['age', ['name', true]); to sort by age (ascending) and then by name (descending)
* Example: dv.applySortCriteria(['age', true], ['name', true]); to sort by age (descending) and then by name (descending)
* @param properties array of property names or subarray of [propertyname, isdesc] used evaluate sort order
* @returns Reference to this DynamicView, sorted, for future chain operations.
*/
applySortCriteria(criteria: [keyof E, boolean][] | null): MemDbDynamicView;
/** marks the beginning of a transaction.
* @returns this DynamicView object, for further chain ops.
*/
startTransaction(): MemDbDynamicView;
/** commits a transaction.
* @returns this DynamicView object, for further chain ops.
*/
commit(): MemDbDynamicView;
/** rolls back a transaction.
* @returns this DynamicView object, for further chain ops.
*/
rollback(): MemDbDynamicView;
/** Adds a mongo-style query option to the DynamicView filter pipeline
* @param query mongo-style query object to apply to pipeline
* @returns this DynamicView object, for further chain ops.
*/
applyFind(query: MemDbQuery): MemDbDynamicView;
/** Adds a javascript filter function to the DynamicView filter pipeline
* @param fun A javascript filter function to apply to pipeline
* @returns this DynamicView object, for further chain ops.
*/
applyWhere(fun: (obj: E) => boolean): MemDbDynamicView;
/** The number of results in this dynamic view.
* Can be quicker than '.data().length' since the results don't have to be materialized to count them,
* although pending/dirty filters may need to be re-evaluated.
* @returns the number of items in this dynamic view
*/
count(): number;
/** resolves and pending filtering and sorting, then returns document array as result.
* @returns An array of documents representing the current DynamicView contents.
*/
data(): E[];
/** */
queueSortPhase(): void;
/** invoked synchronously or asynchronously to perform final sort phase (if needed) */
performSortPhase(): void;
/** internal method for (re)evaluating document inclusion.
* Called by : collection.insert() and collection.update().
* @param objIndex index of document to (re)run through filter pipeline.
*/
evaluateDocument(objIndex: number): void;
/** internal function called on collection.delete() */
removeDocument(objIndex: number): void;
}