persist
v0.2.7
Published
Node.js ORM framework supporting various relational databases
Downloads
1,399
Readme
persist
persis is an orm framework for node.js.
The following databases are currently supported:
- sqlite3 - via: node-sqlite3
- mysql - via: node-mysql
- PostgreSQL - via: node-postgres
Quick Examples
var persist = require("persist");
var type = persist.type;
// define some model objects
Phone = persist.define("Phone", {
"number": type.STRING
});
Person = persist.define("Person", {
"name": type.STRING
}).hasMany(this.Phone);
persist.connect({
driver: 'sqlite3',
filename: 'test.db',
trace: true
}, function(err, connection) {
Person.using(connection).all(function(err, people) {
// people contains all the people
});
});
Download
You can install using Node Package Manager (npm):
npm install persist
Index
database.json
persist
Connection
Model
Query
Transaction
If the current working directory contains a file called database.json this file will be loaded upon requiring persist. The file should follow a format like this:
{
"default": "dev",
"dev": {
"driver": "sqlite3",
"filename": ":memory:"
},
"test": {
"driver": "sqlite3",
"filename": ":memory:"
},
"prod": {
"driver": "sqlite3",
"filename": "prod.db"
}
}
"default" specifies which environment to load.
API Documentation
Connects to a database.
Arguments
- options - (optional) Options used to connect to the database. If options are not specified the default connect options are used. see database.json and SetDefaultConnectOptions
- driver - The driver to use to connect (ie sqlite3, mysql, or postgresql).
- other - see the documentation for your driver. The options hash will be passed to that driver.
- callback(err, connection) - Callback to be called when the connection is established.
Example
persist.connect({
driver: 'sqlite3',
filename: 'test.db',
trace: true
}, function(err, connection) {
// connnection esablished
});
Defines a model object for use in persist.
Arguments
- modelName - The name of the model. This name will map to the database name.
- properties - Hash of properties (or columns). The value of each property can simply be the type name (ie type.String) or it can be a hash of more options.
- type - type of the property (ie type.String)
- defaultValue - this can be a value or a function that will be called each time this model object is created
- dbColumnName - the name of the database column. (default: name of the property, all lower case, seperated by '_')
Returns
A model class.
Example
Person = persist.define("Person", {
"name": type.String,
"createdDate": { type: persist.DateTime, defaultValue: function() { return self.testDate1 }, dbColumnName: 'new_date' },
"lastUpdated": { type: persist.DateTime }
})
Sets the default connection options to be used on future connect calls. see database.json
Arguments
- options - See connect for the description of options
Example
persist.setDefaultConnectOptions({
driver: 'sqlite3',
filename: 'test.db',
trace: true});
Chains multiple statements together in order and gets the results.
Arguments
- chainables - An array of chainable queries. These can be save, updates, selects, or deletes. Each item in the array will be executed, wait for the results, and then execute the next.
- callback(err, results) - Callback called when all the items have been executed.
Example
connection.chain([
person3.save,
Person.min('age'),
Person.max('age'),
phone3.delete,
person2.delete,
Person.orderBy('name').all,
Phone.orderBy('number').first,
Phone.count,
Phone.deleteAll,
Phone.all
], function(err, results) {
// results[0] = person3
// results[1] = 21
// results[2] = 25
// results[3] = []
// results[4] = []
// results[5] = -- all people ordered by name
// results[6] = -- first phone ordered by number
// results[7] = 100
// results[8] = []
// results[9] = [] -- nobody left
});
Begins a transaction on the connection.
Arguments
- callback(err, tx) - Callback called when the transaction has started. tx is a transaction object which you can call commit or rollback
Example
connection.tx(function(err, tx) {
person1.save(connection, function(err) {
tx.commit(function(err) {
// person1 saved and committed to database
});
});
});
Adds a has many relationship to a model. This will automatically add a property to the associated model which links to this model. It will also define a property on instances of this model to get the releated objects - see Associated Object Properties
Arguments
- AssociatedModel - The name of the model to associate to.
- options - (optional) An hash of options.
- through - creates a many to many relationship using the value of through as the join table.
Returns
The model class object suitable for chaining.
Example
Phone = persist.define("Phone", {
"number": persist.String
});
Person = persist.define("Person", {
"name": persist.String
}).hasMany(Phone);
Gets a query object bound to a connection object.
Arguments
- connection - The connection to bind the query object to.
Returns
A new Query object.
Example
Person.using(connection).first(...);
Saves the model object to the database
Arguments
- connection - The connection to use to save the object with.
- callback(err) - The callback to be called when the save is complete
Example
person1.save(connection, function() {
// person1 saved
});
Deletes the model object from the database
Arguments
- connection - The connection to use to delete the object with.
- callback(err) - The callback to be called when the delete is complete
Example
person1.delete(connection, function() {
// person1 deleted
});
If you have setup an associated property using hasMany instances of your model will have an additional property which allows you to get the associated data. This property returns a Query object which you can further chain to limit the results.
Example
Phone = persist.define("Phone", {
"number": persist.String
});
Person = persist.define("Person", {
"name": persist.String
}).hasMany(Phone);
Person.using(connection).first(function(err, person) {
person.phones.orderBy('number').all(function(err, phones) {
// all the phones of the first person
});
});
Gets all items from a query as a single array of items.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- callback(err, items) - Callback to be called after the rows have been fetched. items is an array of model instances.
Example
Person.all(connection, function(err, people) {
// all the people
});
Gets items from a query calling the callback for each item returned.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- callback(err, item) - Callback to be called after each row has been fetched. item is a model instance.
- doneCallback(err) - Callback called after all rows have been retrieved.
Example
Person.each(connection, function(err, person) {
// a person
}, function() {
// all done
});
Gets the first item from a query.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- callback(err, item) - Callback to be called after the row has been fetched. item is a model instance.
Example
Person.first(connection, function(err, person) {
// gets the first person
});
Orders the results of a query.
Arguments
- propertyName - Name of the property to order by.
Returns
The query object suitable for chaining.
Example
Person.orderBy('name').all(connection, function(err, people) {
// all the people ordered by name
});
Limits the number of results of a query.
Arguments
- count - Number of items to return.
- offset - (Optional) The number of items to skip.
Returns
The query object suitable for chaining.
Example
Person.orderBy('name').limit(5, 5).all(connection, function(err, people) {
// The 5-10 people ordered by name
});
Filters the results by a where clause.
Arguments
- clause - A clause to filter the results by.
- values - (Optional) A single value or array of values to substitute in for '?'s in the clause.
- hash - A hash of columns and values to match on (see example)
Returns
The query object suitable for chaining.
Example
Person.where('name = ?', 'bob').all(connection, function(err, people) {
// All the people named 'bob'
});
Person.where({'name': 'bob', 'age': 23}).all(connection, function(err, people) {
// All the people named 'bob' with the age of 23
});
Counts the number of items that would be returned by the query.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- callback(err, count) - Callback with the count of items.
Example
Person.where('name = ?', 'bob').count(connection, function(err, count) {
// count = the number of people with the name bob
});
Gets the minimum value in the query of the given field.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- fieldName - The field name of the value you would like to get the minimum for.
- callback(err, min) - Callback with the minimum value.
Example
Person.where('name = ?', 'bob').min(connection, 'age', function(err, min) {
// the minimum age of all bobs
});
Gets the maximum value in the query of the given field.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- fieldName - The field name of the value you would like to get the maximum for.
- callback(err, min) - Callback with the maximum value.
Example
Person.where('name = ?', 'bob').max(connection, 'age', function(err, min) {
// the maximum age of all bobs
});
Deletes all the items specified by the query.
Arguments
- connection - (Optional) The connection to use. If this is not specified a using statement must be specified earlier.
- callback(err) - Callback called upon completion.
Example
Person.where('name = ?', 'bob').deleteAll(connection, function(err) {
// all people name 'bob' have been deleted.
});
Includes the associated data linked by (hasMany or hasMany(through)) the propertyName when retrieving data from the database. This will replace obj.propertyName with an array of results as opposed to the default before which is a query.
Internally this will do a join to the associated table in the case of a one to many. And will do a join to the associated through table and the associated table in the case of a many to many.
Arguments
- propertyName - This can be a single property name or an array of property names to include.
Example
Person.include("phones").where('name = ?', 'bob').all(connection, function(err, people) {
// all people named 'bob' and all their phone numbers
// so you can do... people[0].phones[0].number
// as opposed to... people[0].phones.all(function(err, phones) {});
});
Commits a transaction.
Arguments
- callback(err) - Callback called when the transaction has committed.
Example
connection.tx(function(err, tx) {
person1.save(connection, function(err) {
tx.commit(function(err) {
// person1 saved and committed to database
});
});
});
Rollsback a transaction.
Arguments
- callback(err) - Callback called when the transaction has rolledback.
Example
connection.tx(function(err, tx) {
person1.save(connection, function(err) {
tx.rollback(function(err) {
// person1 not saved. Transaction rolledback.
});
});
});