new DataSource(nameopt)
LoopBack models can manipulate data via the DataSource object.
Attaching a `DataSource` to a `Model` adds instance methods and static methods to the `Model`.
Define a data source to persist model data.
To create a DataSource programmatically, call `createDataSource()` on the LoopBack object; for example:
```js
var oracle = loopback.createDataSource({
connector: 'oracle',
host: '111.22.333.44',
database: 'MYDB',
username: 'username',
password: 'password'
});
```
All classes in single dataSource share same the connector type and
one database connection.
For example, the following creates a DataSource, and waits for a connection callback.
```
var dataSource = new DataSource('mysql', { database: 'myapp_test' });
dataSource.define(...);
dataSource.on('connected', function () {
// work with database
});
```
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
name |
String |
<optional> |
Optional name for datasource. |
Properties:
Name | Type | Description |
---|---|---|
connector |
String | Database connector to use. For any supported connector, can be any of: - The connector module from `require(connectorName)`. - The full name of the connector module, such as 'loopback-connector-oracle'. - The short name of the connector module, such as 'oracle'. - A local module under `./connectors/` folder. |
host |
String | Database server host name. |
port |
String | Database server port number. |
username |
String | Database user name. |
password |
String | Database password. |
database |
String | Name of the database to use. |
debug |
Boolean | Display debugging information. Default is false. The constructor allows the following styles: 1. new DataSource(dataSourceName, settings). For example: - new DataSource('myDataSource', {connector: 'memory'}); - new DataSource('myDataSource', {name: 'myDataSource', connector: 'memory'}); - new DataSource('myDataSource', {name: 'anotherDataSource', connector: 'memory'}); 2. new DataSource(settings). For example: - new DataSource({name: 'myDataSource', connector: 'memory'}); - new DataSource({connector: 'memory'}); 3. new DataSource(connectorModule, settings). For example: - new DataSource(connectorModule, {name: 'myDataSource}) - new DataSource(connectorModule) |
- Source:
Members
createModel
Define a model class. Returns newly created model object.
The first (String) argument specifying the model name is required.
You can provide one or two JSON object arguments, to provide configuration options.
See [Model definition reference](http://docs.strongloop.com/display/DOC/Model+definition+reference) for details.
Simple example:
```
var User = dataSource.createModel('User', {
email: String,
password: String,
birthDate: Date,
activated: Boolean
});
```
More advanced example
```
var User = dataSource.createModel('User', {
email: { type: String, limit: 150, index: true },
password: { type: String, limit: 50 },
birthDate: Date,
registrationDate: {type: Date, default: function () { return new Date }},
activated: { type: Boolean, default: false }
});
```
You can also define an ACL when you create a new data source with the `DataSource.create()` method. For example:
```js
var Customer = ds.createModel('Customer', {
name: {
type: String,
acls: [
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.WRITE, permission: ACL.DENY},
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
]
}
}, {
acls: [
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
]
});
```
- Source:
queueInvocation
Check if the data source is connected. If not, the method invocation will be
deferred and queued.
- Source:
stop
An alias for `disconnect` to make the datasource a LB4 life-cycle observer.
Please note that we are intentionally not providing a `start` method,
because the logic for establishing connection(s) is more complex
and usually started immediately from the datasoure constructor.
- Source:
(static) DEFAULT_MAX_OFFLINE_REQUESTS
Global maximum number of event listeners
- Source:
Methods
attach(modelClass)
Attach an existing model to a data source.
This will mixin all of the data access object functions (DAO) into your
modelClass definition.
Parameters:
Name | Type | Description |
---|---|---|
modelClass |
function | The model constructor that will be enhanced by DAO mixins. |
- Source:
automigrate(modelsopt, callbackopt)
Drop schema objects such as tables, indexes, views, triggers, etc that correspond
to model definitions attached to this DataSource instance, specified by the `models` parameter.
**WARNING**: In many situations, this will destroy data! `autoupdate()` will attempt to preserve
data while updating the schema on your target DataSource, but this is not guaranteed to be safe.
Please check the documentation for your specific connector(s) for a detailed breakdown of
behaviors for automigrate!
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
models |
String | Array.<String> |
<optional> |
Model(s) to migrate. If not present, apply to all models. |
callback |
function |
<optional> |
Callback function. Optional. |
- Source:
autoupdate(modelsopt, cbopt)
Update existing database tables.
This method applies only to database connectors.
**WARNING**: `autoupdate()` will attempt to preserve data while updating the
schema on your target DataSource, but this is not guaranteed to be safe.
Please check the documentation for your specific connector(s) for a detailed breakdown of
behaviors for automigrate!*
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
models |
String | Array.<String> |
<optional> |
Model(s) to migrate. If not present, apply to all models. |
cb |
function |
<optional> |
The callback function |
- Source:
beginTransaction(options)
Begin a new Transaction.
Parameters:
Name | Type | Description |
---|---|---|
options |
- Source:
Returns:
Promise A promise which resolves to a Transaction object
buildModelFromInstance(name, json, options) → {Model}
Introspect a JSON object and build a model class
Parameters:
Name | Type | Description |
---|---|---|
name |
String | Name of the model |
json |
Object | The json object representing a model instance |
options |
Object | Options |
- Source:
Returns:
A Model class
- Type
- Model
columnMetadata(modelName, propertyName) → {Object}
Return column metadata for specified modelName and propertyName
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
propertyName |
String | The property name |
- Source:
Returns:
column metadata
- Type
- Object
columnName(modelName, propertyName) → {String}
Return column name for specified modelName and propertyName
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
propertyName |
String | The property name |
- Source:
Returns:
columnName The column name.
- Type
- String
columnNames(modelName) → {Array.<String>}
Return column names for specified modelName
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
- Source:
Returns:
column names
- Type
- Array.<String>
connect(callback) → {Promise}
Connect to the data source.
If no callback is provided, it will return a Promise.
Emits the 'connect' event.
Parameters:
Name | Type | Description |
---|---|---|
callback |
- Source:
Fires:
- event:connected
Returns:
- Type
- Promise
defineForeignKey(className, key, foreignClassName, pkName)
Define foreign key to another model
Parameters:
Name | Type | Description |
---|---|---|
className |
String | The model name that owns the key |
key |
String | Name of key field |
foreignClassName |
String | The foreign model name |
pkName |
String | (optional) primary key used for foreignKey |
- Source:
defineOperation(name, options, fn)
Define an operation to the data source
Parameters:
Name | Type | Description |
---|---|---|
name |
String | The operation name |
options |
Object | The options |
fn |
function | The function |
- Source:
defineProperty(model, prop, params)
Define a property with name `prop` on a target `model`. See
[Properties](./Model-definition-JSON-file.html#properties) for more information
regarding valid options for `params`.
Parameters:
Name | Type | Description |
---|---|---|
model |
String | Name of model |
prop |
String | Name of property |
params |
Property | Property settings |
- Source:
deleteAllModels()
Remove all models from the registry, but keep the connector instance
(including the pool of database connections).
- Source:
deleteModelByName(modelName)
Remove a model from the registry.
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String |
- Source:
disableRemote(operation)
Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled
and disabled operations. To list the operations, call `dataSource.operations()`.
```js
var oracle = loopback.createDataSource({
connector: require('loopback-connector-oracle'),
host: '...',
...
});
oracle.disableRemote('destroyAll');
```
**Notes:**
- Disabled operations will not be added to attached models.
- Disabling the remoting for a method only affects client access (it will still be available from server models).
- Data sources must enable / disable operations before attaching or creating models.
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | The operation name |
- Source:
disconnect(cbopt)
Close connection to the DataSource.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
cb |
function |
<optional> |
The callback function. Optional. |
- Source:
discoverAndBuildModels(modelName, cbopt) → {Promise}
Discover and build models from the specified owner/modelName.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
modelName |
String | The model name. | |
cb |
function |
<optional> |
The callback function |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | Database owner or schema name. |
relations |
Boolean | True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean | True if all owners are included; false otherwise. |
views |
Boolean | True if views are included; false otherwise. |
- Source:
Returns:
A Promise object that resolves with a map of model
constructors, keyed by model name
- Type
- Promise
discoverAndBuildModelsSync(modelName, modelName, optionsopt) → {Object}
Discover and build models from the given owner/modelName synchronously.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
modelName |
String | The model name. | |
modelName |
String | The model name | |
options |
Object |
<optional> |
The options |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | Database owner or schema name. |
relations |
Boolean | True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean | True if all owners are included; false otherwise. |
views |
Boolean | True if views are included; false otherwise. |
- Source:
Returns:
A map of model constructors, keyed by model name
- Type
- Object
discoverExportedForeignKeys(modelName, cbopt) → {Promise}
Retrieves a description of the foreign key columns that reference the given table's primary key columns
(the foreign keys exported by a table), ordered by fkTableOwner, fkTableName, and keySeq.
Callback function return value is an object that can have the following properties:
| Key | Type | Description |
|-----|------|-------------|
|fkOwner |String | Foreign key table schema (may be null)
|fkName |String | Foreign key name (may be null)
|fkTableName |String | Foreign key table name
|fkColumnName |String | Foreign key column name
|keySeq |Number | Sequence number within a foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key).
|pkOwner |String | Primary key table schema being imported (may be null)
|pkName |String | Primary key name (may be null)
|pkTableName |String | Primary key table name being imported
|pkColumnName |String | Primary key column name being imported
See [Relations](/Model-definition-JSON-file.html#relations) for more
information.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
modelName |
String | The model name | |
cb |
function |
<optional> |
The callback function |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | The database owner or schema |
- Source:
Returns:
A Promise with an array of exported foreign key relations.
- Type
- Promise
discoverExportedForeignKeysSync(modelName, options) → {*}
The synchronous version of discoverExportedForeignKeys
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
options |
Object | The options |
- Source:
Returns:
- Type
- *
discoverForeignKeys(modelName, cbopt) → {Promise}
Discover foreign keys for a given owner/modelName
Callback function return value is an object that can have the following properties:
| Key | Type | Description |
|-----|------|-------------|
|fkOwner |String | Foreign key table schema (may be null)
|fkName |String | Foreign key name (may be null)
|fkTableName |String | Foreign key table name
|fkColumnName |String | Foreign key column name
|keySeq |Number | Sequence number within a foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key).
|pkOwner |String | Primary key table schema being imported (may be null)
|pkName |String | Primary key name (may be null)
|pkTableName |String | Primary key table name being imported
|pkColumnName |String | Primary key column name being imported
See [Relations](/Model-definition-JSON-file.html#relations) for more
information.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
modelName |
String | The model name | |
cb |
function |
<optional> |
The callback function |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | The database owner or schema |
- Source:
Returns:
A Promise with an array of foreign key relations.
- Type
- Promise
discoverForeignKeysSync(modelName, options) → {*}
The synchronous version of discoverForeignKeys
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
options |
Object | The options |
- Source:
Returns:
- Type
- *
discoverModelDefinitions(Callback) → {Array.<ModelDefinition>}
Discover existing database tables.
This method returns an array of model objects, including {type, name, onwer}
Parameters:
Name | Type | Description |
---|---|---|
Callback |
function | function. Optional. |
Properties:
Name | Type | Description |
---|---|---|
owner/schema |
String | The owner or schema to discover from. |
all |
Boolean | If true, discover all models; if false, discover only models owned by the current user. |
views |
Boolean | If true, include views; if false, only tables. |
limit |
Number | Page size |
offset |
Number | Starting index |
- Source:
Returns:
- Type
- Array.<ModelDefinition>
discoverModelDefinitionsSync() → {Array.<ModelDefinition>}
The synchronous version of discoverModelDefinitions.
Properties:
Name | Type | Description |
---|---|---|
all |
Boolean | If true, discover all models; if false, discover only models owned by the current user. |
views |
Boolean | If true, nclude views; if false, only tables. |
limit |
Number | Page size |
offset |
Number | Starting index |
- Source:
Returns:
- Type
- Array.<ModelDefinition>
discoverModelPropertiesSync(modelName, options) → {*}
The synchronous version of discoverModelProperties
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The table/view name |
options |
Object | The options |
- Source:
Returns:
- Type
- *
discoverPrimaryKeys(modelName, cbopt) → {Promise}
Discover primary keys for a given owner/modelName.
Callback function return value is an object that can have the following properties:
| Key | Type | Description |
|-----|------|-------------|
| owner |String | Table schema or owner (may be null). Owner defaults to current user.
| tableName |String| Table name
| columnName |String| Column name
| keySeq |Number| Sequence number within primary key (1 indicates the first column in the primary key; 2 indicates the second column in the primary key).
| pkName |String| Primary key name (may be null)
See [ID Properties](./Model-definition-JSON-file.html#id-properties) for more
information.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
modelName |
String | The model name | |
cb |
function |
<optional> |
The callback function |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | The database owner or schema |
- Source:
Returns:
A promise with an array of Primary Keys (Property[])
- Type
- Promise
discoverPrimaryKeysSync(modelName) → {*}
The synchronous version of discoverPrimaryKeys
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | The database owner or schema |
- Source:
Returns:
- Type
- *
discoverSchema(tableName, cbopt) → {Promise}
Discover one schema from the given model without following the relations.
*Example schema from oracle connector:**
```js
{
"name": "Product",
"options": {
"idInjection": false,
"oracle": {
"schema": "BLACKPOOL",
"table": "PRODUCT"
}
},
"properties": {
"id": {
"type": "String",
"required": true,
"length": 20,
"id": 1,
"oracle": {
"columnName": "ID",
"dataType": "VARCHAR2",
"dataLength": 20,
"nullable": "N"
}
},
"name": {
"type": "String",
"required": false,
"length": 64,
"oracle": {
"columnName": "NAME",
"dataType": "VARCHAR2",
"dataLength": 64,
"nullable": "Y"
}
},
...
"fireModes": {
"type": "String",
"required": false,
"length": 64,
"oracle": {
"columnName": "FIRE_MODES",
"dataType": "VARCHAR2",
"dataLength": 64,
"nullable": "Y"
}
}
}
}
```
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
tableName |
String | The name of the table to discover. | |
cb |
function |
<optional> |
The callback function |
- Source:
Returns:
A promise object that resolves to a single schema.
- Type
- Promise
discoverSchemas(tableName, cbopt) → {Promise}
Discover schema from a given tableName/viewName.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
tableName |
String | The table name. | |
cb |
function |
<optional> |
The callback function |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | Database owner or schema name. |
relations |
Boolean | True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean | True if all owners are included; false otherwise. |
views |
Boolean | True if views are included; false otherwise. |
- Source:
Returns:
A promise object that resolves to an array of schemas.
- Type
- Promise
discoverSchemasSync(modelName) → {Array.<Object>}
Discover schema from a given table/view synchronously
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | Database owner or schema name. |
relations |
Boolean | True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean | True if all owners are included; false otherwise. |
views |
Boolean | True if views are included; false otherwise. |
- Source:
Returns:
An array of schema definition objects.
- Type
- Array.<Object>
enableRemote(operation)
Enable remote access to a data source operation. Each [connector](#connector) has its own set of set
remotely enabled and disabled operations. To list the operations, call `dataSource.operations()`.
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | The operation name |
- Source:
execute()
Execute an arbitrary command. The commands are connector specific,
please refer to the documentation of your connector for more details.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
...params |
<optional> |
Array The command and its arguments, e.g. an SQL query. |
- Source:
Returns:
Promise A promise of the result
freeze()
Freeze dataSource. Behavior depends on connector
To continuously add artifacts to datasource until it is frozen, but it is not really used in loopback.
- Source:
getMaxOfflineRequests()
Get the maximum number of event listeners
- Source:
getModel()
See [ModelBuilder.getModel](http://apidocs.strongloop.com/loopback-datasource-juggler/#modelbuilder-prototype-getmodel)
for details.
- Source:
getModelDefinition()
See ModelBuilder.getModelDefinition
See [ModelBuilder.getModelDefinition](http://apidocs.strongloop.com/loopback-datasource-juggler/#modelbuilder-prototype-getmodeldefinition)
for details.
- Source:
getOperation(operation)
Get an operation's metadata.
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | The operation name |
- Source:
getTypes() → {Array.<String>}
Get the data source types collection.
- Source:
Returns:
The data source type array.
For example, ['db', 'nosql', 'mongodb'] would be represent a datasource of
type 'db', with a subtype of 'nosql', and would use the 'mongodb' connector.
Alternatively, ['rest'] would be a different type altogether, and would have
no subtype.
- Type
- Array.<String>
idColumnName(modelName) → {String}
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
- Deprecated:
- Function to get the id column name of the target model For SQL connectors, use `SqlConnector.prototype.column(ModelDefinition.prototype.idName())`. For NoSQL connectors, use `Connector.prototype.idMapping(ModelDefinition.prototype.idName())` instead.
- Source:
Returns:
columnName for ID
- Type
- String
idName(modelName) → {String}
Find the ID property name
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
- Source:
Returns:
property name for ID
- Type
- String
idNames(modelName) → {Array.<String>}
Find the ID property names sorted by the index
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
- Source:
Returns:
property names for IDs
- Type
- Array.<String>
idProperty(modelName) → {Object}
Find the id property definition
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name |
- Source:
Returns:
The id property definition
- Type
- Object
isActual(modelsopt) → {Boolean}
Check whether or not migrations are required for the database schema to match
the Model definitions attached to the DataSource.
Note: This method applies only to SQL connectors.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
models |
String | Array.<String> |
<optional> |
A model name or an array of model names. If not present, apply to all models. |
- Source:
Returns:
Whether or not migrations are required.
- Type
- Boolean
isRelational() → {Boolean}
Check if the backend is a relational DB
- Source:
Returns:
- Type
- Boolean
operations()
Return JSON object describing all operations.
Example return value:
```js
{
find: {
remoteEnabled: true,
accepts: [...],
returns: [...]
enabled: true
},
save: {
remoteEnabled: true,
prototype: true,
accepts: [...],
returns: [...],
enabled: true
},
...
}
```
- Source:
ping(cbopt)
Ping the underlying connector to test the connections
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
cb |
function |
<optional> |
Callback function |
- Source:
supportTypes(types) → {Boolean}
Check the data source supports the specified types.
Parameters:
Name | Type | Description |
---|---|---|
types |
String | Array.<String> | Type name or an array of type names. |
- Source:
Returns:
true if all types are supported by the data source
- Type
- Boolean
tableName(modelName) → {String}
Return table name for specified `modelName`.
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The model name. |
- Source:
Returns:
The table name.
- Type
- String
transaction(execute, cb) → {Promise|EventEmitter}
Run a transaction against the DataSource.
This method can be used in different ways based on the passed arguments and
type of underlying data source:
If no `execute()` function is provided and the underlying DataSource is a
database that supports transactions, a Promise is returned that resolves to
an EventEmitter representing the transaction once it is ready.
`transaction.models` can be used to receive versions of the DataSource's
model classes which are bound to the created transaction, so that all their
database methods automatically use the transaction. At the end of all
database transactions, `transaction.commit()` can be called to commit the
transactions, or `transaction.rollback()` to roll them back.
If no `execute()` function is provided on a transient or memory DataSource,
the EventEmitter representing the transaction is returned immediately. For
backward compatibility, this object also supports `transaction.exec()`
instead of `transaction.commit()`, and calling `transaction.rollback()` is
not required on such transient and memory DataSource instances.
If an `execute()` function is provided, then it is called as soon as the
transaction is ready, receiving `transaction.models` as its first
argument. `transaction.commit()` and `transaction.rollback()` are then
automatically called at the end of `execute()`, based on whether exceptions
happen during execution or not. If no callback is provided to be called at
the end of the execution, a Promise object is returned that is resolved or
rejected as soon as the execution is completed, and the transaction is
committed or rolled back.
Parameters:
Name | Type | Description |
---|---|---|
execute |
function | The execute function, called with (models). Note that the instances in `models` are bound to the created transaction, and are therefore not identical with the models in `app.models`, but slaves thereof (optional). |
cb |
function | Callback called with (err) |
- Source:
Returns:
- Type
- Promise | EventEmitter