-
Notifications
You must be signed in to change notification settings - Fork 0
ConnectionBase
ConnectionBase is the base class that all connection classes should inherit from. It provides common functionality to all connections, and converts literals and types into their native database representation.
A "connection" in Mythix ORM is essentially the "application" for the ORM. It stores all models used by the connection, stores and defines the query generator (if any), converts literals and types, and also provides the query engine.
Multiple connections can be used at the same time in Mythix ORM. It is also planned that someday Mythix ORM (or the community) will provide a multiplex connection, to mix multiple connections into a single connection for the entire application.
For now you can use multiple connections at once. Just know that you should read and fully understand Connection Binding if you plan on using more than one connection for your application.
ConnectionBase is also an Event Emitter,
so you can bind events to a connection instance with .on, and unbind
with .off. Events are connection specific, but common events that
can be bound to are:
-
connect- Commonly fired when a connection is successfully established -
acquire- Commonly fired when a connection is acquired from a connection pool -
error- Commonly fired when a database level error occurs -
disconnect- Commonly fired when a connection is disconnected
This is just an example of common connection driver events. Please see documentation for your specific database connection for the proper events.
Helper for type checking methods. Should always be true.
The dialect of the database, i.e. 'sqlite', or 'postgresql'.
All default Mythix ORM literal classes, provided for convenient access.
method ConnectionBase::buildConnectionContext(connection?: Connection = this): Map<any, any>
This builds a "connection context" to provide to the AsyncLocalStorage context of a Connection.createContext call.
By default, this will set a connection property on the context,
which will be the value of this connection instance. It also sets
a connection property on the sub-contexts for each model. This
is because models might have different connections, and so need
a context per-model to work properly.
"How could a model have different connections?" you ask? Well, it probably won't. But being as this is an AsyncLocalStorage context, it provides the connection to every model inside the context. Your application might be using other models that aren't part of this connection, and we wouldn't want those to get the wrong connection for those models.
Arguments:
connection?: Connection (Default:this)The connection to create the context for. This can be provided, and is used in place of
thisinstance, for example, in the case of transactions. Transactions generally are the "same" connection, but not the same instance.Return value:
Map<any, any>The new context that will be used for Connection.createContext.
method ConnectionBase::constructor(options: object): Connection
Create a connection.
The options argument is generally connection
specific. However, there are a few generic options,
which you will find listed in the table below:
| Option | Type | Default Value | Description |
|---|---|---|---|
bindModels |
boolean |
true |
If true, then bind the provided models to this connection. Models are bound to a connection by setting a static _mythixBoundConnection property on each model class to this connection instance. |
forceConnectionBinding |
boolean |
false |
Normally attempting to bind a connection to a model more than once will result in an exception being thrown. However, if you set this property to true, then Mythix ORM will rebind the connection without complaint, even if a connection is already bound to your models. Make sure you know what you are doing if you use this option. |
models |
Array or Object of Models
|
undefined |
Models to provide to this connection. This can be either an array of Models, or an Object where each value is a Model |
QueryEngine |
class QueryEngine | QueryEngine | The QueryEngine class to use for this connection and all this connection's models. You can provide your own class if you wish to add onto the query interface. |
queryGenerator |
QueryGenerator | Connection specific | The query generator for this connection. If a QueryGenerator instance is provided (the correct one for the connection you are using), then this provided query generator will be used. If one isn't provided, then the connection will create its own query generator that is specific to the connection type. |
Arguments:
options:objectConnection specific options to supply to your connection. These will commonly include things like a hostname to connect to, a user name and password, and any connection specific parameters.
Return value: Connection
method ConnectionBase::createContext(callback: async Function, connection?: Connection = this, thisArg?: any = this): any
Create a connection context to serve all code running inside it this connection.
This uses AsyncLocalStorage to create a context that is passed through the entire call stack of the callback. In this way, a connection can be provided to every model and every operation within the call.
Arguments:
callback:async FunctionThe method to provide the context to. Every call inside this call stack will be provided the connection.
connection?: Connection (Default:this)The connection to provide. Generally this will just be
thisconnection instance, however, it can be specified, and is for example inside transactions.thisArg?:any(Default:this)The
thisvalue to provide to the givencallback.Return value:
anyThe return value of the given
callback.
Find a specific field across all registered models.
This method is similar to Array.find,
except that the arguments to this finder method are those provided by
Model.iterateFields. If this finder method
returns a truthy value for a given field, then that is the field that will be returned.
Notes:
- This will search for the field across all models registered to the connection. To find a specific field for a known model use Connection.getField instead.
Arguments:
finder:FunctionA function to assist in finding the specified field. The signature for this function must match that used by Model.iterateFields.
Return value:
Field|undefinedThe field found, if any.
Get a value from the AsyncLocalStorage context.
AsyncLocalStorage is used primarily for two purposes: 1) to provide a connection to models, and 2) to pass a transaction connection down through the call stack. However, it can also be used for any "context" level values the user wishes to store.
Notes:
- An
AsyncLocalStoragecontext might not exist when this call is made, in which case this method will returnundefined, or thedefaultValueif any was provided.Arguments:
key:anyThe key for the value you wish to fetch. The underlying "context" provided by
AsyncLocalStorageis aMap, so the "key" can be any value.defaultValue?:anyThe default value to return if there is no current
AsyncLocalStoragecontext, or if the requested key is not found.Return value:
any
method ConnectionBase::getDefaultOrder(Model: class Model, options: object): Array<string>
Get the default order for selecting rows from the database. This will call the Model's Model.defaultOrder method first to see if the model specifies a default order for itself. If it doesn't, then the connection driver itself might specify a default order for each table.
Arguments:
Model: class ModelThe model/table to fetch the default order for.
options:objectOperation specific options (i.e. options for a "select" call)
Return value:
Array<string>An array of fully qualified field names for this model should be returned by this method. An empty array,
null, orundefinedare also valid return values (in which case no order will be applied to the given operation).
This method is an internal method that parses the "lock mode" options passed to a call to Connection.transaction.
These might be different depending on the connection driver you are using. Please refer to the documentation for your connection driver for more details.
Arguments:
options:anyPossibly connection specific lock options for a connection's Connection.transaction method. Generally this will either be a
truevalue, a Model name (for which table to lock), or a complete lock options object, which generally will look something like:{ lock: boolean; modelName: string; read: boolean; write: boolean }
lock- Iftrue, then lock the transactionmodelName- The name of the table(s) to lockread- Iftrue, then lock for readswrite- Iftrue, then lock for writes.Return value:
objectReturn the lock options for a transaction. These might change based on the connection driver you are using, but will generally look like
{ lock: boolean; modelName: string; read: boolean; write: boolean }.
lock- Iftrue, then lock the transactionmodelName- The name of the table(s) to lockread- Iftrue, then lock for readswrite- Iftrue, then lock for writes.
Get the options for this connection.
These will be the options provided to the connection during creation, plus any other options the connection driver itself internally sets.
Return value:
objectThe options for this connection.
This method is called (and often provided)
by the underlying database driver to see
if a LIMIT clause is allowed to appear in
a given context/operation.
Arguments:
options:objectDriver specific options for the context.
Return value:
boolean
This method is called (and often provided)
by the underlying database driver to see
if an ORDER BY clause is allowed to appear in
a given context/operation.
Arguments:
options:objectDriver specific options for the context.
Return value:
boolean
Check to see if start has already been called
on this connection. This is used to know if a
connection is "active" or not.
Return value:
boolean
This is simply a convenience method that calls ModelUtils.parseQualifiedName.
Arguments:
fieldName:stringThe field name, fully qualified field name, or model name to parse. See ModelUtils.parseQualifiedName for more information.
Return value:
objectThe result. See ModelUtils.parseQualifiedName for more information.
See also: ModelUtils.parseQualifiedName
Register the provided model class.
This will register the provided model class with this
connection. The model must not already be bound to
another connection, or you must specify the option
{ forceConnectionBinding: true } if it is. You
can specify the option of { bindModels: false }
if you don't wish to bind this model to this connection.
Any options provided are optional, and will override
the same options provided to the connection itself when
it was created.
Arguments:
Model: class ModelThe model class to register with this connection. If not bound, then it will simply exist in the model pool for this connection. If bound, then this connection will bind itself to the model being registered.
options?:objectOptions looks like
{ forceConnectionBinding: boolean; bindModels: boolean; }. This is an optional argument. Both options will default to the same options provided to the connection when it was created. If you specify either of these options they simply override the connection's default.Return value: class Model
The registered model class, which may have changed during registration. It is not uncommon for the connection driver itself to modify the model class, or to return a new model class that inherits from your model class. The class that is returned should be the class that you use for this connection, and will be the same class returned by a call to Connection.getModel, or Connection.getModels.
method ConnectionBase::registerModels(Model: Array<class Model> | { [key: string]: class Model }, options?: object): class Model
Register multiple models at the same time.
This will register the provided models with this
connection. The models provided must not already be bound to
another connection, or you must specify the option
{ forceConnectionBinding: true } if any of them are. You
can specify the option of { bindModels: false }
if you don't wish to bind these models to this connection.
Any options provided are optional, and will override
the same options provided to the connection itself when
it was created.
Arguments:
Model: Array<class Model> | { [key: string]: class Model }The model classes to register with this connection. If no models are bound, then they will simply exist in the model pool for this connection. If bound, then this connection will bind itself to every model being registered.
options?:objectOptions looks like
{ forceConnectionBinding: boolean; bindModels: boolean; }. This is an optional argument. Both options will default to the same options provided to the connection when it was created. If you specify either of these options they simply override the connection's default.Return value: class Model
The registered model classes, which may have changed during registration. It is not uncommon for the connection driver itself to modify the model classes, or to return a new model classes that inherit from your model classes. The classes that are returned should be the classes that you use for this connection, and will be the same classes returned by a call to Connection.getModel, or Connection.getModels.
Set a value onto the AsyncLocalStorage context.
AsyncLocalStorage is used primarily for two purposes: 1) to provide a connection to models, and 2) to pass a transaction connection down through the call stack. However, it can also be used for any "context" level values the user wishes to store.
Notes:
- An
AsyncLocalStoragecontext might not exist when this call is made, in which case this method will do nothing, and silently return.Arguments:
key:anyThe key for the value you wish to set. The underlying "context" provided by
AsyncLocalStorageis aMap, so the "key" can be any value.value:anyThe value to set to the specified key.
Return value:
any
static method ConnectionBase::getLiteralClassByName(name: string): class LiteralBase
Fetch a literal class by its name.
The following is a table that displays
the name argument that can be provided,
and the resulting Literal class that would
be returned for that name.
name |
Resulting literal class |
|---|---|
'Average' |
AverageLiteral |
'Base' |
LiteralBase |
'Count' |
CountLiteral |
'Distinct' |
DistinctLiteral |
'Field' |
FieldLiteral |
'FieldBase' |
LiteralFieldBase |
'Literal' |
Literal |
'Max' |
MaxLiteral |
'Min' |
MinLiteral |
'Sum' |
SumLiteral |
Arguments:
name:stringThe name of the literal class to return.
Return value: class LiteralBase
Return the literal class requested.
Check to see if the provided value is
an instance of a Mythix ORM ConnectionBase.
Unlike ConnectionBase.static isConnectionClass, which
checks if a class is a ConnectionBase, this will check
to see if an instance is an instance of a
Mythix ORM ConnectionBase. It will return
true if the provided value is an instanceof
ConnectionBase, or if the value's constructor
property has a truthy _isMythixConnection property
(value.constructor._isMythixConnection)
Arguments:
value:anyValue to check.
Return value:
boolean
Use this method to check if a class
is a Mythix ORM connection. It will return
true if the provided value is a class
that inherits from ConnectionBase, or
if the provided value has an attribute
named _isMythixConnection that is truthy.
Arguments:
value:FunctionValue to check.
Return value:
boolean
static method ConnectionBase::Literal(name: string): LiteralBase
Create the literal specified by name.
Whereas ConnectionBase.static getLiteralClassByName will simply return the literal class specified, this will create the specified literal, with the provided arguments.
Please see ConnectionBase.static getLiteralClassByName for
possible names that can be provided as the name argument.
Arguments:
name:stringThe name of the literal to create. See ConnectionBase.static getLiteralClassByName for possible values. ...args: Array Arguments to provide to the literal constructor.
Return value: LiteralBase
Return an instance the literal requested, using the arguments specified.
See also: static ConnectionBase.getLiteralClassByName
method ConnectionBase::toQueryEngine(value: any): QueryEngine | undefined
This will take something that can be turned into a query and turn it into a query.
If a QueryEngine instance is provided, it will simply be returned.
If a Model is provided, then Model.where
will be returned, returning a QueryEngine
for the model provided.
In the future this may also accept other possible values that could be turned into a query.
This is often internally called by methods of the connection on a given argument provided by the user, which could validly be either a model or a query. Connection.destroyAll is one example of this.
Arguments:
value:anyThe value to attempt to turn into a QueryEngine.
Return value: QueryEngine |
undefined
- Associations
- Certifications
- Connection Binding
- Home
- Models
- Queries
- TypeScript
- Types Reference
-
namespace AsyncStore
- function getContextStore
- function getContextValue
- function runInContext
- function setContextValue
-
namespace Helpers
- function checkDefaultValueFlags
- function defaultValueFlags
- function getDefaultValueFlags
- property FLAG_LITERAL
- property FLAG_ON_INITIALIZE
- property FLAG_ON_INSERT
- property FLAG_ON_STORE
- property FLAG_ON_UPDATE
- property FLAG_REMOTE
-
namespace MiscUtils
- function collect
- function valueToDateTime
-
namespace ModelUtils
- function parseQualifiedName
-
namespace QueryUtils
- function generateQueryFromFilter
- function mergeFields
- function parseFilterFieldAndOperator
-
class AverageLiteral
- method static isAggregate
- method toString
-
class BigIntType
- property Default
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class BlobType
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class BooleanType
- method castToType
- method isValidValue
- method static getDisplayName
- method toString
-
class CacheKey
- method constructor
- method valueOf
-
class CharType
- method castToType
- method isValidValue
- method static getDisplayName
- method toString
-
class ConnectionBase
- property _isMythixConnection
- property DefaultQueryGenerator
- property dialect
- property Literals
- method _averageLiteralToString
- method _bigintTypeToString
- method _blobTypeToString
- method _booleanTypeToString
- method _charTypeToString
- method _countLiteralToString
- method _datetimeTypeToString
- method _dateTypeToString
- method _distinctLiteralToString
- method _escape
- method _escapeID
- method _fieldLiteralToString
- method _getFromModelCache
- method _integerTypeToString
- method _maxLiteralToString
- method _minLiteralToString
- method _numericTypeToString
- method _realTypeToString
- method _setToModelCache
- method _stringTypeToString
- method _sumLiteralToString
- method _textTypeToString
- method _uuidV1TypeToString
- method _uuidV3TypeToString
- method _uuidV4TypeToString
- method _uuidV5TypeToString
- method _xidTypeToString
- method addColumn
- method addIndex
- method aggregate
- method alterColumn
- method alterTable
- method average
- method buildConnectionContext
- method bulkModelOperation
- method constructor
- method convertDateToDBTime
- method count
- method createContext
- method createQueryGenerator
- method createTable
- method createTables
- method destroy
- method destroyModels
- method dirtyFieldHelper
- method dropColumn
- method dropIndex
- method dropTable
- method dropTables
- method ensureAllModelsAreInstances
- method escape
- method escapeID
- method exists
- method finalizeQuery
- method findModelField
- method getContextValue
- method getDefaultFieldValue
- method getDefaultOrder
- method getField
- method getLockMode
- method getModel
- method getModels
- method getOptions
- method getQueryEngineClass
- method getQueryGenerator
- method insert
- method isStarted
- method literalToString
- method max
- method min
- method parseQualifiedName
- method pluck
- method prepareAllModelsAndSubModelsForOperation
- method prepareAllModelsForOperation
- method query
- method registerModel
- method registerModels
- method runSaveHooks
- method select
- method setContextValue
- method setPersisted
- method setQueryGenerator
- method splitModelAndSubModels
- method stackAssign
- method start
- method static getLiteralClassByName
- method static isConnection
- method static isConnectionClass
- method static Literal
- method stop
- method sum
- method toQueryEngine
- method transaction
- method truncate
- method typeToString
- method update
- method updateAll
- method upsert
-
class CountLiteral
- method static isAggregate
- method static isFieldRequired
- method toString
-
class DateTimeType
- property Default
- method castToType
- method constructor
- method deserialize
- method isValidValue
- method serialize
- method static getDisplayName
- method toString
-
class DateType
- property Default
- method castToType
- method constructor
- method deserialize
- method isValidValue
- method serialize
- method static getDisplayName
- method toString
-
class DistinctLiteral
- method toString
-
class Field
- property _isMythixField
- property allowNull
- property defaultValue
- property fieldName
- property get
- property index
- property primaryKey
- property set
- property type
- property unique
- property validate
- method clone
- method constructor
- method setModel
- method static isField
- method static isFieldClass
-
class FieldLiteral
- method toString
- class FieldScope
-
class ForeignKeyType
- method castToType
- method constructor
- method getOptions
- method getTargetField
- method getTargetFieldName
- method getTargetModel
- method getTargetModelName
- method initialize
- method isValidValue
- method parseOptionsAndCheckForErrors
- method static getDisplayName
- method static isForeignKey
- method toString
-
class IntegerType
- property Default
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class Literal
- method constructor
-
class LiteralBase
- property _isMythixLiteral
- method constructor
- method definitionToField
- method fullyQualifiedNameToDefinition
- method static isAggregate
- method static isLiteral
- method static isLiteralClass
- method static isLiteralType
- method toString
- method valueOf
-
class LiteralFieldBase
- method constructor
- method getField
- method getFullyQualifiedFieldName
- method static isFieldRequired
- method valueOf
-
class MaxLiteral
- method static isAggregate
- method toString
-
class MinLiteral
- method static isAggregate
- method toString
-
class Model
- property _isMythixModel
- method _castFieldValue
- method _constructField
- method _constructFields
- method _constructor
- method _getConnection
- method _getDirtyFields
- method _getFieldValue
- method _initializeFieldData
- method _initializeModelData
- method _setFieldValue
- method clearDirty
- method constructor
- method destroy
- method getAttributes
- method getConnection
- method getDataValue
- method getDirtyFields
- method getOptions
- method hasValidPrimaryKey
- method isDirty
- method isPersisted
- method onAfterCreate
- method onAfterSave
- method onAfterUpdate
- method onBeforeCreate
- method onBeforeSave
- method onBeforeUpdate
- method onValidate
- method reload
- method save
- method setAttributes
- method setDataValue
- method static _getConnection
- method static all
- method static bindConnection
- method static count
- method static create
- method static cursor
- method static defaultScope
- method static finalizeQuery
- method static first
- method static getConcreteFieldCount
- method static getContextValue
- method static getField
- method static getFields
- method static getForeignKeyFieldsMap
- method static getForeignKeysTargetField
- method static getForeignKeysTargetFieldNames
- method static getForeignKeysTargetModelNames
- method static getForeignKeysTargetModels
- method static getModel
- method static getModelContext
- method static getModelName
- method static getPluralModelName
- method static getPrimaryKeyField
- method static getPrimaryKeyFieldName
- method static getQueryEngine
- method static getQueryEngineClass
- method static getSingularName
- method static getSortedFields
- method static getTableName
- method static getUnscopedQueryEngine
- method static getWhereWithConnection
- method static hasField
- method static hasRemoteFieldValues
- method static initializeFields
- method static isForeignKeyTargetModel
- method static isModel
- method static isModelClass
- method static iterateFields
- method static last
- method static mergeFields
- method static pluck
- method static primaryKeyHasRemoteValue
- method static setContextValue
- method static toString
- method static updateModelContext
- method toJSON
- method toString
- method updateDirtyID
-
class ModelScope
- method _getField
- method AND
- method CROSS_JOIN
- method DISTINCT
- method EXISTS
- method Field
- method FULL_JOIN
- method GROUP_BY
- method HAVING
- method INNER_JOIN
- method JOIN
- method LEFT_JOIN
- method LIMIT
- method mergeFields
- method NOT
- method OFFSET
- method OR
- method ORDER
- method PROJECT
- method RIGHT_JOIN
-
class ModelType
- method fieldNameToOperationName
- method initialize
-
class ModelsType
- method fieldNameToOperationName
- method initialize
-
class NumericType
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class ProxyClass
- property APPLY
- property AUTO_CALL
- property AUTO_CALL_CALLED
- property AUTO_CALL_CALLER
- property CALLABLE
- property CONSTRUCT
- property DEFINE_PROPERTY
- property DELETE_PROPERTY
- property GET
- property GET_OWN_PROPERTY_DESCRIPTOR
- property GET_PROTOTYPEOF
- property HAS
- property IS_EXTENSIBLE
- property MISSING
- property OWN_KEYS
- property PREVENT_EXTENSIONS
- property PROXY
- property SELF
- property SET
- property SET_PROTOTYPEOF
- property shouldSkipProxy
- property TARGET
- method ___autoCall
- method ___call
- method constructor
-
class QueryEngine
- method all
- method average
- method constructor
- method count
- method cursor
- method destroy
- method exists
- method finalizeQuery
- method first
- method getFieldScopeClass
- method getModelScopeClass
- method last
- method max
- method MERGE
- method min
- method Model
- method pluck
- method sum
- method toString
- method unscoped
- method updateAll
-
class QueryEngineBase
- method _fetchScope
- method _inheritContext
- method _newFieldScope
- method _newModelScope
- method _newQueryEngineScope
- method _pushOperationOntoStack
- method clone
- method constructor
- method filter
- method getAllModelsUsedInQuery
- method getConnection
- method getFieldScopeClass
- method getModel
- method getModelScopeClass
- method getOperationContext
- method getOperationStack
- method getQueryEngineClass
- method getQueryEngineScope
- method getQueryEngineScopeClass
- method getQueryID
- method isLastOperationCondition
- method isLastOperationControl
- method isModelUsedInQuery
- method logQueryOperations
- method map
- method queryHasConditions
- method queryHasJoins
- method static generateID
- method static getQueryOperationInfo
- method static isQuery
- method static isQueryOperationContext
- method walk
-
class QueryGeneratorBase
- method _averageLiteralToString
- method _countLiteralToString
- method _distinctLiteralToString
- method _fieldLiteralToString
- method _maxLiteralToString
- method _minLiteralToString
- method _sumLiteralToString
- method constructor
- method escape
- method escapeID
- method getConnection
- method getFieldDefaultValue
- method getIndexFieldsFromFieldIndex
- method setConnection
- method stackAssign
- method toConnectionString
-
class RealType
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class SerializedType
- method castToType
- method constructor
- method deserialize
- method getOptions
- method initialize
- method isDirty
- method isValidValue
- method onSetFieldValue
- method serialize
- method static getDisplayName
- method toString
-
class StringType
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class SumLiteral
- method static isAggregate
- method toString
-
class TextType
- method castToType
- method constructor
- method isValidValue
- method static getDisplayName
- method toString
-
class Type
- property _isMythixFieldType
- property clone
- method castToType
- method clone
- method constructor
- method deserialize
- method exposeToModel
- method getDisplayName
- method getField
- method getModel
- method initialize
- method isDirty
- method isForeignKey
- method isRelational
- method isRemote
- method isValidValue
- method isVirtual
- method onSetFieldValue
- method serialize
- method setField
- method setModel
- method static instantiateType
- method static isSameType
- method static isType
- method static isTypeClass
- method static wrapConstructor
- method toConnectionType
-
class UUIDV1Type
- property Default
- method castToType
- method getArgsForUUID
- method isValidValue
- method static getDisplayName
- method validateOptions
-
class UUIDV3Type
- property Default
- method castToType
- method getArgsForUUID
- method isValidValue
- method static getDisplayName
- method validateOptions
-
class UUIDV4Type
- property Default
- method castToType
- method getArgsForUUID
- method isValidValue
- method static getDisplayName
- method validateOptions
-
class UUIDV5Type
- property Default
- method castToType
- method getArgsForUUID
- method isValidValue
- method static getDisplayName
- method validateOptions
-
class XIDType
- property Default
- method castToType
- method isValidValue
- method static getDisplayName