Record
Module | ejs.db.mapper |
Definition | class Record |
Inheritance | Record ![]() |
Specified | ejscript-2.5 |
Stability | Prototype. |
Example | public dynamic class MyModel implements Record {} @spec ejs |
Database record class.
A record instance corresponds to a row in the database. This class provides a low level Object Relational Mapping (ORM) between the database and Ejscript objects. This class provides methods to create, read, update and delete rows in the database. When read or initialized object properties are dynamically created in the Record instance for each column in the database table. Users should subclass the Record class for each database table to manage. When users subclass Record to create models, they should use "implement" rather than extend.
Properties
Qualifiers | Property | Type | Description |
---|
Record Class Methods
Qualifiers | Method |
---|---|
static | afterFilter(fn, options: Object = null): Void |
Run filters after saving data. | |
static | beforeFilter(fn, options: Object = null): Void |
Run filters before saving data. | |
static | belongsTo(owner, options: Object = null): Void |
Define a belonging reference to another model class. | |
static | cache(model = null, options: Object = expression): Void |
Database query caching. | |
static | find(key: Object, options: Object = expression): Object |
Find a record. | |
static | findAll(options: Object = expression): Array |
Find all the matching records. | |
static | findOneWhere(where: String): Object |
Find the first record matching a condition. | |
static | findWhere(where: String, count: Number = null): Array |
Find records matching a condition. | |
static | getColumnNames(): Array |
Return the column names for the table. | |
static | getColumnTitles(): Array |
Return the column names for the record. | |
static | getColumnType(field: String): String |
Get the type of a column. | |
static | getDb(): Database |
Get the database connection for this record class. | |
static | getKeyName(): String |
Get the key name for this record. | |
static | getNumRows(): Number |
Return the number of rows in the table. | |
static | getTableName(): String |
Get the associated name for this record. | |
static | hasAndBelongsToMany(model: Object, options: Object = expression): Void |
Define a containment relationship to another model class. | |
static | hasOne(model: Object, options: Object = null): Void |
Define a containment relationship to another model class. | |
static | remove(ids: Array): Void |
Remove records from the database. | |
static | setDb(database: Database) |
Set the database connection for this record class. | |
static | setKeyName(name: String): Void |
Set the key name for this record. | |
static | setTableName(name: String): Void |
Set the associated table name for this record. | |
static | hasMany(model: Object, options: Object = expression): Void |
Define a containment relationship to another model class. | |
static | sql(cmd: String, count: Number = null): Array |
Run an SQL statement and return selected records. | |
static | trace(on: Boolean): Void |
Trace SQL statements. | |
static | wrapFilter(fn, options: Object = null): Void |
Run filters before and after saving data. |
Record Instance Methods
Qualifiers | Method |
---|---|
Record(fields: Object = null) | |
Constructor for use when instantiating directly from Record. | |
error(field: String, msg: String): Void | |
Set an error message. | |
getErrors(): Object | |
Get the errors for the record. | |
hasError(field: String = null): Boolean | |
Check if the record has any errors. | |
initialize(fields: Object = null): Void | |
Construct a new record instance. | |
save(): Boolean | |
Save the record to the database. | |
saveUpdate(fields: Object): Boolean | |
Update a record based on the supplied fields and values. | |
validateRecord(): Boolean | |
Validate a record. |
Method Detail
Record(fields: Object = null)
- Description
- Constructor for use when instantiating directly from Record. Typically, use models will implement this class and will provdie their own constructor which calls initialize().
- Parameters
fields: Object null [default: null]
- Description
- Run filters after saving data.
- Parameters
fn Function to run. options: Object - reserved. [default: null]
- Description
- Run filters before saving data.
- Parameters
fn Function to run. options: Object - reserved. [default: null]
- Description
- Define a belonging reference to another model class. When a model belongs to another, it has a foreign key reference to another class.
- Parameters
owner Referenced model class that logically owns this model. options: Object Optional options hash. [default: null]
- Options
className Name of the class. foreignKey Key name for the foreign key. conditions SQL conditions for the relationship to be satisfied.
- Description
- Database query caching. This caches controls the caching of database records. If enabled, the results of queries are cached with a given lifetime. If the lifetime has not expired, subsequent queries will be optimized by retrieving cached data. If the record is updated, the cached data will be removed so that the next query retrieves fresh data. Caching is disabled/enabled via the ejsrc config.cache.database.enable field. It is enabled by default. Caching may be used for any Database model, though typically it is most useful for state-less GET requests.
- Parameters
model Model class. This can be a Model class object, "this" or a String model class name. You can specify "this" in static code or can also use "this" in class instance code and this routine will determine the underlying model class name. [default: null] options: Object Cache control options. Default options for all model caching can also be provided by the ejsrc config.cache.database field. [default: expression]
- Options
lifespan Time in seconds for the cached output to persist. query SQL query command to further differentiate cached content. If supplied, different cache data can be stored for each query that applies to the given model. If the URI is set to "*"" all URIs for the specified model will be uniquely cached.
- Example
cache() cache("Store", {lifespan: 200}) cache(this, {query: "SELECT * from Products"}) cache(this, {query: "*""}) P
- Description
- Find a record. Find and return a record identified by its primary key if supplied or by the specified options. If more than one record matches, return the first matching record.
- Parameters
key: Object Key Optional key value. Set to null if selecting via the options. options: Object Optional search option values. [default: expression]
- Options
columns List of columns to retrieve. conditions { field: value, ...} or [ "SQL condition", "id == 23", ...]. from Low level from clause (not fully implemented). keys [set of matching key values]. order ORDER BY clause. group GROUP BY clause. include [Model, ...] Models to join in the query and create associations for. Always preloads. The include Model entry may also be an array of [Model, "Join Condition"]. joins Low level join statement "LEFT JOIN vists on stockId = visits.id". Low level joins do not create association objects (or lazy loaders). The names of the joined columns are prefixed with the appropriate table name using camel case (tableColumn). limit LIMIT count. depth Specify the depth for which to create associations for belongsTo, hasOne and hasMany relationships. Depth of 1 creates associations only in the immediate fields of the result. Depth == 2 creates in the next level and so on. Defaults to one. offset OFFSET count. preload [Model1, ...] Preload "belongsTo" model associations rather than creating lazy loaders. This can reduce the number of database queries if iterating through associations. readonly null lock null
- Returns
- A model record or null if the record cannot be found.
- Throws
- IOError: on internal SQL errors
- Description
- Find the first record matching a condition. Select a record using a given SQL where clause.
- Parameters
where: String SQL WHERE clause to use when selecting rows.
- Returns
- A model record or null if the record cannot be found.
- Throws
- IOError: on internal SQL errors
- Example
rec = findOneWhere("cost < 200")
- Description
- Find records matching a condition. Select a set of records using a given SQL where clause.
- Parameters
where: String SQL WHERE clause to use when selecting rows. count: Number null [default: null]
- Returns
- An array of objects. Each object represents a matching row with fields for each column.
- Example
list = findWhere("cost < 200")
static getColumnNames(): Array
- Description
- Return the column names for the table.
- Returns
- An array containing the names of the database columns. This corresponds to the set of properties that will be created when a row is read using find.
static getColumnTitles(): Array
- Description
- Return the column names for the record.
- Returns
- An array containing the Pascal case names of the database columns. The names have the first letter capitalized.
- Description
- Get the type of a column.
- Parameters
field: String Name of the field to examine.
- Returns
- A string with the data type of the column.
static getDb(): Database
- Description
- Get the database connection for this record class.
- Returns
- Database instance object created via new Database.
static getKeyName(): String
- Description
- Get the key name for this record.
getErrors(): Object
- Description
- Get the errors for the record.
- Returns
- The error message collection for the record.
static getNumRows(): Number
- Description
- Return the number of rows in the table.
static getTableName(): String
- Description
- Get the associated name for this record.
- Returns
- The database table name backing this record class. Normally this is simply a plural class name.
- Description
- Define a containment relationship to another model class. When using "hasAndBelongsToMany" on another model, it means that other models have a foreign key reference to this class and this class can "contain" many instances of the other models.
- Parameters
model: Object Model. (TODO - not implemented). options: Object Object hash of options. (TODO - not implemented). [default: expression]
- Options
foreignKey Key name for the foreign key. (TODO - not implemented). through String Class name which mediates the many to many relationship. (TODO - not implemented). joinTable. (TODO - not implemented).
- Description
- Define a containment relationship to another model class. When using "hasOne" on another model, it means that other model has a foreign key reference to this class and this class can "contain" only one instance of the other.
- Parameters
model: Object Model class that is contained by this class. options: Object null [default: null]
- Options
thing Model that is posessed by this. (TODO - not implemented). foreignKey Key name for the foreign key (TODO - not implemented). as String (TODO - not implemented).
- Description
- Remove records from the database.
- Parameters
ids: Array Set of keys identifying the records to remove.
static setDb(database: Database)
- Description
- Set the associated table name for this record.
- Parameters
name: String Name of the database table to backup the record class.
- Description
- Check if the record has any errors.
- Parameters
field: String null [default: null]
- Returns
- True if the record has errors.
- Description
- Define a containment relationship to another model class. When using "hasMany" on another model, it means that other model has a foreign key reference to this class and this class can "contain" many instances of the other.
- Parameters
model: Object Model class that is contained by this class. options: Object Options parameter. [default: expression]
- Options
things Model object that is posessed by this. (TODO - not implemented). through String Class name which mediates the many to many relationship. (TODO - not implemented). foreignKey Key name for the foreign key. (TODO - not implemented).
- Description
- Construct a new record instance. This is really a constructor function, because the Record class is implemented by user models, no constructor will be invoked when a new user model is instantiated. The record may be initialized by optionally supplying field data. However, the record will not be written to the database until save is called. To read data from the database into the record, use one of the find methods.
- Parameters
fields: Object An optional object set of field names and values may be supplied to initialize the record. [default: null]
save(): Boolean
- Description
- Save the record to the database.
- Returns
- True if the record is validated and successfully written to the database.
- Throws
- IOError: Throws exception on sql errors
- Description
- Run an SQL statement and return selected records.
- Parameters
cmd: String SQL command to issue. Note: "SELECT" is automatically prepended and ";" is appended for you. count: Number null [default: null]
- Returns
- An array of objects. Each object represents a matching row with fields for each column.
- Description
- Update a record based on the supplied fields and values.
- Parameters
fields: Object Hash of field/value pairs to use for the record update.
- Returns
- True if the database is successfully updated. Returns false if validation fails. In this case, the record is not saved.
- Throws
- IOError: on database SQL errors
- Description
- Trace SQL statements. Control whether trace is enabled for the actual SQL statements issued against the database.
- Parameters
on: Boolean If true, display each SQL statement to the log.
validateRecord(): Boolean
- Description
- Validate a record. This call validates all the fields in a record.
- Returns
- True if the record has no errors.
- Description
- Run filters before and after saving data.
- Parameters
fn Function to run. options: Object - reserved. [default: null]