Detalhes do pacote

persist

nearinfinity3.2kMIT0.2.7

Node.js ORM framework supporting various relational databases

database, db, orm, sqlite

readme (leia-me)

persist

persis is an orm framework for node.js.

The following databases are currently supported:

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

database.json

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

persist

persist.connect([options], callback)

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](#databaseJson) and [SetDefaultConnectOptions](#persistSetDefaultConnectOptions)
    
    • 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
});

persist.define(modelName, properties): Model

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 }
})

persist.setDefaultConnectOptions(options)

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});

Connection

connection.chain(chainables, callback)

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
});

connection.tx(callback)

Begins a transaction on the connection.

Arguments

Example

connection.tx(function(err, tx) {
  person1.save(connection, function(err) {
    tx.commit(function(err) {
      // person1 saved and committed to database
    });
  });
});

Model

Model.hasMany(AssociatedModel, [options]): Model

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);

Model.using(connection): query

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(...);

Model.save(connection, callback)

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
});

Model.delete(connection, callback)

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
});

Associated Object Properties

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
  });
});

Query

query.all([connection], callback)

Gets all items from a query as a single array of items.

Arguments

Example

Person.all(connection, function(err, people) {
  // all the people
});

query.each([connection], callback, doneCallback)

Gets items from a query calling the callback for each item returned.

Arguments

Example

Person.each(connection, function(err, person) {
  // a person
}, function() {
  // all done
});

query.first([connection], callback)

Gets the first item from a query.

Arguments

Example

Person.first(connection, function(err, person) {
  // gets the first person
});

query.orderBy(propertyName): query

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
});

query.limit(count, [offset]): query

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
});

query.where(clause, [values...]): query

query.where(hash): query

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
});

query.count([connection], callback)

Counts the number of items that would be returned by the query.

Arguments

Example

Person.where('name = ?', 'bob').count(connection, function(err, count) {
  // count = the number of people with the name bob
});

query.min([connection], fieldName, callback)

Gets the minimum value in the query of the given field.

Arguments

Example

Person.where('name = ?', 'bob').min(connection, 'age', function(err, min) {
  // the minimum age of all bobs
});

query.max([connection], fieldName, callback)

Gets the maximum value in the query of the given field.

Arguments

Example

Person.where('name = ?', 'bob').max(connection, 'age', function(err, min) {
  // the maximum age of all bobs
});

query.deleteAll([connection], callback)

Deletes all the items specified by the query.

Arguments

Example

Person.where('name = ?', 'bob').deleteAll(connection, function(err) {
  // all people name 'bob' have been deleted.
});

query.include(propertyName): query

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) {});
});

Transaction

tx.commit(callback)

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
    });
  });
});

tx.rollback(callback)

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.
    });
  });
});