import { ListModel } from '../models/list-model' ; import { Backend } from '../base-backend' ; import { Record } from '../datatypes/record' ; import { ListRow } from '../datatypes/list-row' ; import { Condition , Q } from './q' ; import { utilRecordModelFromRawData } from '../utils' ; import { Query , UpdateQuery } from './query' ; import { RowDoesNotExistError , MultipleRowsReturnedError } from '../exceptions' ; import { Observable } from 'rxjs' ; export interface PagedRowsResult { rows : ( Record | ListRow ) [ ] ; lastRow : boolean ; } export class QuerySet { backend : Backend ; model : ListModel ; query : Query ; constructor ( model , query ? ) { this . model = model ; this . query = query ? query : new Query ( model ) ; this . backend = model . backend ; } private _clone ( ) { var query = this . query . clone ( ) ; var qsClass = Object . getPrototypeOf ( this ) . constructor ; var clone = new qsClass ( this . model , query ) ; return clone ; } filter ( cond ) { var q = ( cond instanceof Q ) ? cond : new Q ( cond ) ; return this . _filter_or_exclude ( false , q ) ; } exclude ( cond ) { var q = ( cond instanceof Q ) ? cond : new Q ( cond ) ; return this . _filter_or_exclude ( true , q ) ; } _filter_or_exclude ( negate , cond ) { var clone = this . _clone ( ) ; if ( negate ) clone . query . add_q ( cond . swapNegate ( ) ) ; else clone . query . add_q ( cond ) ; return clone ; } limit ( start , stop ) { var cloned_qs = this . _clone ( ) ; cloned_qs . query . setLimits ( start , stop ) ; return cloned_qs ; } getRows ( ... fields ) { return this . backend . getRows ( this . query , fields ) . map ( rawRows => { var records = [ ] ; rawRows . forEach ( rawRow => { if ( this . backend . modelNameField in rawRow ) { var model = utilRecordModelFromRawData ( this . backend , rawRow ) ; records . push ( model . constructRecord ( false , rawRow ) ) ; } else { records . push ( new ListRow ( rawRow , this . model ) ) ; } } ) ; return records ; } ) ; } count ( ) { var alias = '__count' ; return this . backend . getRows ( this . query . getCount ( alias ) ) . map ( rawRows => { return rawRows [ 0 ] [ alias ] ; } ) ; } getRow ( ... fields ) { return this . limit ( 0 , 2 ) . getRows ( ... fields ) . map ( rows => { if ( rows . length == 0 ) { throw new RowDoesNotExistError ( ) ; } else if ( rows . length > 1 ) { throw new MultipleRowsReturnedError ( ) ; } else { return rows [ 0 ] ; } } ) ; } update ( values ) { var query = this . query . clone ( UpdateQuery ) as UpdateQuery ; query . addUpdateValues ( values ) ; } orderBy ( ... fieldNames ) { var obj = this . _clone ( ) ; obj . query . clearOrdering ( false ) ; obj . query . addOrdering ( ... fieldNames ) ; return obj ; } getOrdering ( ) { return this . query . getOrdering ( ) ; } }