CustomRepository

CustomRepository

CustomRepository

Constructor

new CustomRepository(entityName)

Base data access class for server-side, client(browser)-side and client(console) side Repositories. Usually used via UB#Repository fabric function.

Do not use it directly, use UB.Repository instead.

Arguments:
  1. entityName (String)  name of Entity we create for
Author:
  • pavel.mash 23.09.2014

Members

WhereCondition: string

Enumeration of all condition types. This enumeration defines a set of String values. It exists primarily for documentation purposes - in code use the actual string values like '>', don't reference them through this class like WhereCondition.more.

We define several aliases for the same condition. In case of direct HTTP request (without Repository) use only non-aliased values (i.e. more instead of '>' or 'gt')

Properties:
Name Type Description
gt string
">" string
more string
lt string
"<" string
less string
eq string
"=" string
equal string
ge string
geq string
">=" string
moreEqual string
le string
leq string
"<=" string
lessEqual string
ne string
neq string
"<>" string
"!=" string
"!==" string
notEqual string
contains string
like string
notContains string
notLike string
isNull string
null string
notNull string
notIsNull string
isNotNull string
beginWith string
startWith string
startsWith string
startswith string
notBeginWith string
notStartWith string
notStartsWith string
includes string
in string
notIncludes string
notIn string
match string
subquery string
exists string
notExists string
custom string

Methods

using(methodName)

Retrieve a data from server using methodName entity method. By default select method will be used.
Arguments:
  1. methodName (string)

attrs(attr)CustomRepository

Add fields to collection. Can take one attribute name as string or array of attributes. Duplicate is not checked and in case of duplicate attribute caller got server error.

 UB.Repository('tri_srf_reg').attrs('ID').attrs(['code', 'name']).attrs('fullName', 'newCode');

Can take expression as a field. In this case entity attribute name must be wrapped into [] brackets. In case of client-side execution the only valid expression is one of:

  • 'SUM', 'COUNT', 'AVG', 'MAX', 'MIN', 'CAST', 'COALESCE'

Example:

 UB.Repository('tri_srf_reg').attrs('SUM([payment])').where('documentID', '=', value); //will calculate sum of document payments

If case of server-side execution any valid SQL expression is accepted:

 UB.Repository('uba_user').attrs('[ID] / 100 + 1').selectAsArray()
Arguments:
  1. attr (String|Array)

where(expression, condition, valuesopt, clauseNameopt)CustomRepository

Add where expression. Fix some known issues:

  • if attribute name without brackets is passed to expression parameter then wrap attribute to brackets "ID" -> "[ID]"

  • transform some dummy expressions to more simple form: in ['one'] -> equal 'one',in []->0=1,? null->isNull` e.t.c.

  • expression may contains this functions: 'SUM', 'COUNT', 'AVG', 'MAX', 'MIN', 'CAST', 'COALESCE', 'LENGTH', 'LOWER', 'UPPER', 'DAY', 'MONTH', 'YEAR', 'ROUND', 'FLOOR', 'CEILING'

In and 'notIn` conditions can take a sub-repository as a values parameter value. See CustomRepository.exists for a conplex example

Arguments:
  1. expression (String)  Attribute name (with or without []) or valid expression with attributes in [].
  2. condition (WhereCondition|String)  Any value from WhereCondition list.
  3. [values] (*)  Condition value. In case expression is complex can take {Object} as value. In case values === undefined no values property passed to where list
  4. [clauseName] (String)  Optional clause name to be used in {CustomRepository.logicalPredicates}. If not passed where will generate unique clause named 'c1', 'c2', ......
Example
UB.Repository('my_entity').attrs('id')
          .where('code', 'in', ['1', '2', '3'])  // code in ('1', '2', '3')
          .where('code', 'in', UB.Repository('my_codes').attr('code').where('ID', '<', 10)  // code in (select code from my_codes where id = 10)
          .where('[name]', 'contains', 'Homer'). // name like '%homer%'
          .where('[birtday]', 'geq', new Date()).where('birtday', 'leq', new Date() + 10) //(birtday >= '2012-01-01') AND (birtday <= '2012-01-02')
          .where('[age] -10', '>=', {age: 15}, 'byAge') // (age + 10 >= 15)
          .where('LENGTH([code]), '<', 5)
          .where('', 'match', 'myvalue') // for condition match expression not need

exists(subRepository, clauseNameopt)CustomRepository

Add an expression with EXISTS sub-query. Inside a sub-query there is two macro:

  • {master} will be replaced by master entity alias
  • {self} will be replaced by sub-query entity alias

    //select users UB.Repository('uba_user').attrs(['ID', 'name'])

    // who are not disabled
    .where('disabled', '=', 0)
    // which allowed access from Kiev
    .where('trustedIP', 'in',
      UB.Repository('geo_ip').attrs('IPAddr')
        .where('city', '=', 'Kiev')
    )
    // who do not login during this year
    .notExists(
      UB.Repository('uba_audit')
        .correlation('actionUser', 'name')  // here we link to uba_user.name
        .where('actionTime', '>', new Date(2016, 1, 1))
        .where('actionType', '=', 'LOGIN')
    )
    // but modify some data
    .exists(
      UB.Repository('ubs_audit')
        .correlation('actionUser', 'ID') // here we link to uba_user.ID
        .where('actionTime', '>', new Date(2016, 1, 1))
    )
    .select()
Arguments:
  1. subRepository (CustomRepository)  Repository, what represent a sub-query to be execute inside EXISTS statement
  2. [clauseName] (String)  Optional clause name

notExists(subRepository, clauseNameopt)CustomRepository

Add an expression with NOT EXISTS sub-query. See CustomRepository.exists for sample
Arguments:
  1. subRepository (CustomRepository)  Repository, what represent a sub-query to be execute inside EXISTS statement
  2. [clauseName] (String)  Optional clause name

correlation(subQueryAttribute, masterAttribute, conditionopt, clauseNameopt)CustomRepository

If current repository are used as a sub-query for exists, notExists, in or notIn conditions will add a correlation with a master repository
Arguments:
  1. subQueryAttribute (String)
  2. masterAttribute (String)
  3. [condition=eq] (WhereCondition|String)  A subset from WhereCondition list applicable for correlation join
  4. [clauseName] (String)  Optional clause name to be used in {CustomRepository.logicalPredicates}. If not passed where will generate unique clause named 'c1', 'c2', ......

logic(predicate)CustomRepository

Arrange where expressions in logical order. By default where expressions is joined by AND logical predicate. Here is possible to join it in custom order.

 UB.Repository('my_entity').attrs('id')
     .where('code', 'in', ['1', '2', '3'], 'byCode')  // code in ('1', '2', '3')
     .where('name', 'contains', 'Homer', 'byName') // name like '%homer%'
     .where('birtday', 'geq', new Date()).where('birtday', 'leq', new Date() + 10) //(birtday >= '2012-01-01') AND (birtday <= '2012-01-02')
     .where('[age] -10', '>=', {age: 15}, 'byAge') // (age + 10 >= 15)
     .logic('(([byCode]) OR ([byName]))') // (byCode OR byName) AND (all where items, not included in logic)
Arguments:
  1. predicate (String)  logical predicate.

join(whereItemName)CustomRepository

Force where expressions to be used in join SQL statement instead of where. Applicable only for not cached entities.

 // will generate
 // SELECT A.ID, B.code FROM tst_document A LEFT JOIN tst_category B ON (B.instanceID = A.ID and B.ubUser = 10)
 // instead of
 // SELECT A.ID, B.code FROM tst_document A LEFT JOIN tst_category B ON B.instanceID = A.ID WHERE B.ubUser = 10
 UB.Repository('tst_document').attrs(['ID', '[caregory.code]'])
     .where('[caregory.ubUser]', '=', 10, 'wantInJoin')
     .join('wantInJoin')
     .selectAsObject().done(UB.logDebug);
Arguments:
  1. whereItemName (String)  name of where item to use in join.

joinCondition(expression, condition, valuesopt, clauseNameopt)CustomRepository

Add join condition. Fix some known issues
Arguments:
  1. expression (String)  Attribute name (with or without []) or valid expression with attributes in [].
  2. condition (WhereCondition)  Any value from WhereCondition list.
  3. [values] (*)  Condition value. In case expression is complex can take {Object} as value. In case values === undefined no values property passed to where list
  4. [clauseName] (String)  Optional clause name to be used in {CustomRepository.logicalPredicates}. If not passed where will generate unique clause named 'c1', 'c2', ......

orderBy(attr, directionopt)CustomRepository

Add sorting

 UB.CustomRepository('my_entity').attrs('ID').orderBy('code')
Arguments:
  1. attr   Sorted attribute
  2. [direction='asc']   Sort direction ('asc'|'desc')

orderByDesc(attr)CustomRepository

Add desc sorting. The same as orderBy(attr, 'desc')

 UB.Repository('my_entity').attrs('ID').orderBy('code').orderByDesc('date_create') // ORDER BY code, date_create DESC
Arguments:
  1. attr (String)

groupBy(attr)CustomRepository

Add grouping Can take one attribute name as string or array of attributes name

 UB.Repository('my_entity').attrs('ID').groupBy('code')
 UB.Repository('uba_user').attrs('disabled').groupBy('disabled').select()
 UB.Repository('uba_user').attrs(['disabled','uPassword','COUNT([ID])']).groupBy(['disabled','uPassword']).select()
Arguments:
  1. attr   Grouped attribute

start(start)CustomRepository

Add options.start value to retrieve first start rows

 var store = UB.Repository('my_entity').attrs('id').start(15).limit(10).select() //will return ID's from 15 to 25
Arguments:
  1. start (Number)

limit(resultRowsLimit)CustomRepository

Add options.limit value. Can be combined with {@link CustomRepository#start).

 var store = UB.CRepository('my_entity').attrs('id').limit(2).select() ; //will return first two ID's from my_entity
Arguments:
  1. resultRowsLimit (Number)

describe(value)CustomRepository

For debug purpose only.

If set, in GUI mode will put this description into log before query execution

 var store = UB.Repository('my_entity').attrs('ID').describe('Select all record for "my_entity"').select()
Arguments:
  1. value (String)

ubql()Object

Construct a UBQL JSON request. Used in CustomRepository#select

  var repo = UB.Repository('my_entity').attrs('ID').where('code', '=', 'a')
  var inst = new TubDataStore(my_entity);
  inst.run('select', repo.ubql());

selectAsObject() abstract

Must be implemented in descendants and return (or resolved for async clients) to array of object representation of result, like this

 [{"ID":3000000000004,"code":"uba_user"},{"ID":3000000000039,"code":"ubs_audit"}]

selectAsArray() abstract

Must be implemented in descendants and return (or resolved for async clients) to array of array representation of result, like this

 {"resultData":{"fields":["ID","name","ID.name"],"rowCount":1,"data":[[10,"admin","admin"]]},"total":1,"__totalRecCount": totolRecCountIfWithTotalRequest}

selectAsStore(storeConfigopt) abstract

Must be implemented in descendants and return (or resolved for async clients) to DataSet class instance, implemented in caller level. It can be:

  • {TubDataStore} for in-server context
  • {UB.ux.data.UBStore} for UnityBase adminUI client
  • array of array data representation for UnityBase remote connection
  • etc.
Arguments:
  1. [storeConfig]

select(storeConfigopt) abstract

Must be implemented in descendants as a alias to the most appropriate method
Arguments:
  1. [storeConfig]

misc(flags)CustomRepository

Apply miscellaneous options to resulting ubRequest:

     // this server-side call will select all currency, including deleted
     UB.Repository('cdn_currency').attrs(['ID']).misc({__allowSelectSafeDeleted: true}).selectAsArray();
Arguments:
  1. flags (Object)
    Properties
    1. [__mip_ondate] (Date)  Specify date on which to select data for entities with dataHistory mixin. Default to Now()
    2. [__mip_recordhistory=false] (Boolean)  Select only record history data for specified ID (for entities with dataHistory mixin)
    3. [__mip_recordhistory_all=false] (Boolean)  Ignore __mip_ondate and select all data (acts as select for entities without dataHistory mixin)
    4. [__mip_disablecache=false] (Boolean)  For entities with cacheType in ["Session", "SessionEntity"] not check is data modified and always return result
    5. [__skipOptimisticLock=false] (Boolean)  Skip optimistic lock for entities with mStorage.simpleAudit = true
    6. [__allowSelectSafeDeleted=false] (Boolean)  Server-side only.
    7. [__skipSelectAfterUpdate=false] (Boolean)  Server-side only.
    8. [__skipSelectAfterInsert=false] (Boolean)  Server-side only.
    9. [__skipRls=false] (Boolean)  Server-side only.
    10. [__skipAclRls=false] (Boolean)  Server-side only.

withTotal()CustomRepository

Calculate total row number. WARNING!! This is VERY slow operation on DB level in case of many record

Result of calculation is returned in __totalRecCount parameter value in case selectAsArray() client call:

     var result = UB.Repository('uba_user').attrs(['ID', 'description']).withTotal().selectAsArray();
            console.log('Total count is:', result.__totalRecCount)

Or into TubDataStore.totalRowCount in case of server side selectAsStore() call:

     var store = UB.Repository('uba_user').attrs(['ID', 'description']).withTotal().selectAsStore();
            console.log('Total count is:', store.totalRowCount);