-
Notifications
You must be signed in to change notification settings - Fork 1
SQLConnectionBase
class SQLConnectionBase extends ConnectionBase 📜
SQLConnectionBase is a support class for all other
SQL connection drivers built for Mythix ORM. It isn't
intended to be used on its own, but rather to add SQL
support to all other Mythix ORM SQL connections.
static property SQLConnectionBase::DefaultQueryGenerator = SQLQueryGeneratorBase 📜
method SQLConnectionBase::_escape(
value: any,
): string 📜
The low-level DB interface for escaping a
value. By default this function uses the
sqlstring
module to escape values. However, the escape
method for whatever database the connection is
using should be used instead of this. This is
a "default implementation" that is meant as a
fallback when a connection doesn't provide its
own, but each connection should provide its own
when it is able.
Notes:
- This method escapes "values" that are given in the underlying query language of the database. To escape identifiers, use the ConnectionBase._escapeID instead.
Arguments:
-
value:anyThe value to escape. This could be a number, a boolean, a string, or anything else that can be provided to your specific database.
Return value: string
The value provided, escaped for the specific underlying database driver.
method SQLConnectionBase::_escapeID(
value: string,
): string 📜
Low-level database method for escaping an identifier. Each database driver should provide its own version of this method. This is the "default" method Mythix ORM provides as a "fallback" to database drivers that don't supply their own.
It works by first stripping all quotes (single ', double ", and backtick `)
from the provided value. After this, it will split on the period (dot) character
., and then will map each resulting part through sqlstring
escapeId method, finally re-joining the parts with a period . character.
The extra processing is to allow for already escaped identifiers to not be double-escaped.
Arguments:
-
value:stringThe identifier to escape.
Return value: string
The provided identifier, escaped for the underlying database.
method SQLConnectionBase::buildModelDataMapFromSelectResults(
queryEngine: QueryEngine,
result: { rows: Array<any>; columns: Array<string>; },
): { [key: string]: Array<object> } 📜
This method will take a { rows: Array<any>; columns: Array<string>; } result from
a SELECT statement, and build a map of model data and sub-model data
to be later turned into model instances by SQLConnectionBase.buildModelsFromModelDataMap.
Arguments:
-
queryEngine: QueryEngineThe query engine that was used to generate the
SELECTstatement that returned these results. -
result:{ rows: Array<any>; columns: Array<string>; }The results as returned by the database, used to build the data map to later construct model instances.
Return value: { [key: string]: Array<object> }
Return result from the database, mapped to the models that were projected. Each key in
this object will be a model name, and each value an array of model attributes. The model
attributes in each array of models represents a model instance that will be created later
using these attributes. There is a special key Symbol.for('@_mythix/orm-sql-base/SQLConnectionBase/ModelRelations')
that can be present on any object of model attributes (a model). This special key--if present--will be
another mapped object that represents "sub-models" that are "owned" by the model that has this
special key. This is used when projecting and loading "related models" during a load operation.
See also: SQLConnectionBase.buildModelsFromModelDataMap
method SQLConnectionBase::buildModelsFromModelDataMap(
queryEngine: QueryEngine,
modelDataMap: { [key: string]: Array<object> },
callback?: (RootModel: class Model, model: Model) => Model,
): Array<Model> 📜
Take the result from a SQLConnectionBase.buildModelDataMapFromSelectResults call and instantiate all models defined by the model attribute map.
Arguments:
-
queryEngine: QueryEngineThe query engine that was used to generate the
SELECTstatement that returned these results. -
modelDataMap:{ [key: string]: Array<object> }The result from a call to SQLConnectionBase.buildModelDataMapFromSelectResults.
-
callback?: (RootModel: class Model, model: Model) => ModelA callback that is called for each root model instance created from the provided
modelDataMap. Sub-models, or other models projected for the operation will not be passed through this callback. Only instances of the "root model" (or "target model") of the query will be passed through this callback. This callback must return the original model instance provided to it, or an equivalent model instance (possibly the same instance modified by the callback).
Return value: Array<Model>
An array of all fully-instantiated "root models" returned from the SELECT query, including
any "sub-models" that were loaded along-side them. All models will be marked "clean".
See also: SQLConnectionBase.buildModelDataMapFromSelectResults
Create the table/bucket defined by Model.
Notes:
- Mythix ORM always refers to data-spaces as "tables", even though they might actually be "buckets" for example for no-SQL databases.
Arguments:
-
Model: class ModelThe model that defines the table to be created.
-
options?:objectThough these options can be database specific, they are commonly just the following options.
Option Type Default Value Description ifNotExistsbooleanfalseAdd an IF NOT EXISTSclause to the create table statement.
Return value: undefined
This method returns nothing.
Drop the table/bucket defined by Model.
Notes:
- Mythix ORM always refers to data-spaces as "tables", even though they might actually be "buckets" for example for no-SQL databases.
Arguments:
-
Model: class ModelThe model that defines the table to be dropped.
-
options?:objectThough these options can be database specific, they are commonly just the following options.
Option Type Default Value Description ifExistsbooleanfalseAdd an IF EXISTSclause to the drop table statement.cascadebooleantrueAdd a CASCADEclause to the drop table statement (destroying rows in other tables defined by foreign key constraints).
Return value: undefined
This method returns nothing.
method SQLConnectionBase::enableForeignKeyConstraints(
enable: boolean,
) 📜
For databases that support it, enable or disable foreign key constraints.
Arguments:
-
enable:booleanIf
true, enable foreign key constraints in the underlying database, otherwise disable foreign key constraints in the underlying database.
method SQLConnectionBase::findAllFieldsFromFieldProjectionMap(
projectionFieldMap: Map<string, string> | Array<string>,
): Array<Field | string> 📜
Given a Map or an Array from a projection field-set, find all matching
projected fields through this connection, and return
them as an array.
Arguments:
-
projectionFieldMap:Map<string, string>|Array<string>A set of projected fields, as a
Mapor anArray. AMaptype will usually be generated by SQLQueryGeneratorBase.getProjectedFields. TheMapis expected to have fully qualified field names and expanded literal strings as keys, with the projected database fields (or literals) in database format for values. As anArraytype, this should be a list of fully qualified field names, or expanded literals as values. AnArrayof field names is generally used when thecolumnsfrom the database result are passed into this method.
Return value: Array<Field | string>
All fields found from the projection Map. Any field that wasn't able to be
found on this connection will instead just be returned as its raw string form.
Any raw strings returned are likely literals, and so couldn't be matched to fields.
However, they may not always be literals, but instead may be a custom field or field
alias that the user requested on the projection.
method SQLConnectionBase::generateSavePointName(): string 📜
Generate a SAVEPOINT name for use in sub-transactions.
This will generate a UUID v4 ID, and then mutate it so
that the name is SQL-safe. Finally, it will add an SP
prefix to the SAVEPOINT name.
Return value: string
A random SQL-safe SAVEPOINT name.
method SQLConnectionBase::getUpdateOrDeleteChangeCount(
queryResult: any,
): number 📜
Parse the database-specific return value for an
UPDATE or DELETE operation to retrieve the
number of rows that were updated or deleted.
Notes:
- Each database driver should overload this method to
properly parse the results of an
UPDATEorDELETEstatement to return the number of rows affected.
Arguments:
-
queryResult:anyThe raw database response for an
UPDATEorDELETEstatement.
Return value: number
The number of rows that were affected by the operation.
method SQLConnectionBase::prepareArrayValuesForSQL(
array: Array<any>,
): Array<any> 📜
Prepare an array of values for use in an IN statement.
This method will flatten the provided array, and then
will filter out all non-primitive values from the array.
Only null, boolean, number, bigint, and string
values will remain in the resulting array. The array is
also reduced to only unique values, with duplicates removed.
Arguments:
-
array:Array<any>The array to flatten, filter, and remove duplicates from.
Return value: Array<any>
Return a copy of the array provided, after being flattened, filtered, and duplicates removed.
method SQLConnectionBase::queryResultRowsToRawData(
result: { rows: Array<any>; columns: Array<string>; },
): Array<object> 📜
Convert the raw { rows: Array<any>; columns: Array<string>; } results
from a database into an array of mapped objects.
This method simply takes the rows and columns reported by the database
for a SELECT operation, and maps them to objects, where each key is
a column name, and each value is a column from one of the returned rows.
Arguments:
-
result:{ rows: Array<any>; columns: Array<string>; }The raw results as returned by the database.
Return value: Array<object>
The raw results from the database, with each row mapped to an object.
method SQLConnectionBase::updateModelsFromResults(
Model: class Model,
storedModels: Array<Model>,
results: { rows: Array<any>; columns: Array<string>; },
): Array<Model> 📜
Take the { rows: Array<any>; columns: Array<string>; } result from
the database for a RETURNING statement, and update the effected models
with the results.
This is used by UPDATE and INSERT statements to sync model attributes
with the database update/insert operation that just took place.
This will also set all models provided to the call as "persisted".
Arguments:
-
Model: class ModelThe model class of the array of
storedModelsthat are being operated upon. -
storedModels: Array<Model>The models that were just persisted.
-
results:{ rows: Array<any>; columns: Array<string>; }The raw results from the database, used to update all persisted models.
Return value: Array<Model>
Return storedModels, with each model being updated with the returned results
from the database, and each model marked as "persisted".
- Home
-
class SQLConnectionBase
- property DefaultQueryGenerator
- method _escape
- method _escapeID
- method buildModelDataMapFromSelectResults
- method buildModelsFromModelDataMap
- method createTable
- method dropTable
- method enableForeignKeyConstraints
- method findAllFieldsFromFieldProjectionMap
- method generateSavePointName
- method getUpdateOrDeleteChangeCount
- method isLimitSupportedInContext
- method isOrderSupportedInContext
- method prepareArrayValuesForSQL
- method queryResultRowsToRawData
- method updateModelsFromResults
-
class SQLQueryGeneratorBase
- method _averageLiteralToString
- method _collectRemoteReturningFields
- method _countLiteralToString
- method _distinctLiteralToString
- method _fieldLiteralToString
- method _getLiteralAlias
- method _maxLiteralToString
- method _minLiteralToString
- method _sumLiteralToString
- method formatLikeValue
- method generateAddColumnStatement
- method generateAlterColumnChangePrimaryKeyConstraintStatement
- method generateAlterColumnChangeTypeStatement
- method generateAlterColumnChangeUniqueConstraintStatement
- method generateAlterColumnRenameStatement
- method generateAlterColumnSetDefaultStatement
- method generateAlterColumnSetOrDropNullConstraintStatement
- method generateAlterColumnStatements
- method generateAlterTableStatement
- method generateColumnDeclarationStatement
- method generateColumnIndexes
- method generateConditionPostfix
- method generateCreateIndexStatement
- method generateCreateTableStatement
- method generateCreateTableStatementInnerTail
- method generateCreateTableStatementOuterTail
- method generateDeleteStatement
- method generateDeleteStatementReturningClause
- method generateDropColumnStatement
- method generateDropIndexStatement
- method generateDropTableStatement
- method generateForeignKeyConstraint
- method generateFromTableOrTableJoin
- method generateGroupByAndHavingClause
- method generateGroupByClause
- method generateHavingClause
- method generateIndexName
- method generateInsertFieldValuesFromModel
- method generateInsertStatement
- method generateInsertStatementTail
- method generateInsertValuesFromModels
- method generateJoinOnTableQueryConditions
- method generateLimitClause
- method generateOffsetClause
- method generateOrderClause
- method generateReturningClause
- method generateSelectJoinOnTableQueryCondition
- method generateSelectOrderLimitOffset
- method generateSelectQueryCondition
- method generateSelectQueryFieldProjection
- method generateSelectQueryJoinTables
- method generateSelectQueryOperatorFromQueryEngineOperator
- method generateSelectStatement
- method generateSelectWhereConditions
- method generateSQLJoinTypeFromQueryEngineJoinType
- method generateTruncateTableStatement
- method generateUpdateStatement
- method generateUpdateStatementTail
- method generateWhereAndOrderLimitOffset
- method getEscapedColumnName
- method getEscapedFieldName
- method getEscapedModelFields
- method getEscapedProjectionName
- method getEscapedTableName
- method getFieldDefaultValue
- method getJoinTableInfoFromQueryContexts
- method getProjectedFields
- method getQueryEngineOrder
- method prepareArrayValuesForSQL
- method sortJoinRelationOrder
- method toConnectionString