{"id":15019204,"url":"https://github.com/joeferner/node-persist","last_synced_at":"2025-09-06T11:39:29.293Z","repository":{"id":1994312,"uuid":"2927152","full_name":"joeferner/node-persist","owner":"joeferner","description":"Node.js ORM framework supporting MySQL and SQLite 3 relational databases.","archived":false,"fork":false,"pushed_at":"2015-07-02T12:38:56.000Z","size":2398,"stargazers_count":253,"open_issues_count":39,"forks_count":46,"subscribers_count":19,"default_branch":"master","last_synced_at":"2024-10-29T22:56:26.494Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/joeferner.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2011-12-06T19:03:33.000Z","updated_at":"2024-07-03T03:39:14.000Z","dependencies_parsed_at":"2022-08-26T01:10:31.821Z","dependency_job_id":null,"html_url":"https://github.com/joeferner/node-persist","commit_stats":null,"previous_names":["nearinfinity/node-persist"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-persist","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-persist/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-persist/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joeferner%2Fnode-persist/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joeferner","download_url":"https://codeload.github.com/joeferner/node-persist/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248112706,"owners_count":21049703,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-09-24T19:53:09.584Z","updated_at":"2025-04-09T21:22:16.927Z","avatar_url":"https://github.com/joeferner.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# persist is not maintained anymore. If you would like to take it over from me please contact me.\n\n# persist\n\npersist is an ORM framework for node.js.\n\nThe following databases are currently supported:\n\n * sqlite3 - via: [node-sqlite3](https://github.com/developmentseed/node-sqlite3)\n * mysql - via: [node-mysql](https://github.com/felixge/node-mysql)\n * PostgreSQL - via: [node-postgres](https://github.com/brianc/node-postgres)\n * Oracle - via: [node-oracle](https://github.com/nearinfinity/node-oracle)\n\n# Quick Examples\n```javascript\nvar persist = require(\"persist\");\nvar type = persist.type;\n\n// define some model objects\nPhone = persist.define(\"Phone\", {\n  \"number\": type.STRING\n});\n\nPerson = persist.define(\"Person\", {\n  \"name\": type.STRING\n}).hasMany(this.Phone);\n\npersist.connect({\n  driver: 'sqlite3',\n  filename: 'test.db',\n  trace: true\n}, function(err, connection) {\n  Person.using(connection).all(function(err, people) {\n    // people contains all the people\n  });\n});\n```\n# Download\n\nYou can install using Node Package Manager (npm):\n\n    npm install persist\n\n# Index\n\n## [database.json](#databaseJson)\n\n## persist\n * [env](#persistEnv)\n * [connect](#persistConnect)\n * [define](#persistDefine)\n * [defineAuto](#persistDefineAuto)\n * [setDefaultConnectOptions](#persistSetDefaultConnectOptions)\n * [shutdown](#persistShutdown)\n\n## Connection\n\n * [chain](#connectionChain)\n * [tx](#connectionTx)\n * [runSql](#connectionRunSql)\n * [runSqlAll](#connectionRunSqlAll)\n * [runSqlEach](#connectionRunSqlEach)\n * [runSqlFromFile](#connectionRunSqlFromFile)\n * [runSqlAllFromFile](#connectionRunSqlAllFromFile)\n * [runSqlEachFromFile](#connectionRunSqlEachFromFile)\n\n## Model\n\n * [hasMany](#modelHasMany)\n * [hasOne](#modelHasOne)\n * [using](#modelUsing)\n * [save](#modelSave)\n * [update (instance)](#modelInstanceUpdate)\n * [update](#modelUpdate)\n * [delete](#modelDelete)\n * [getById](#modelGetById)\n * [defineClause](#modelDefineClause)\n * [onSave](#modelOnSave)\n * [onLoad](#modelOnLoad)\n * [validate](#modelValidate)\n * [Associated Object Properties](#associatedObjectProperties)\n * [Model events](#modelEvents)\n\n## Query\n\n * [all](#queryAll)\n * [each](#queryEach)\n * [first](#queryFirst)\n * [last](#queryLast)\n * [orderBy](#queryOrderBy)\n * [limit](#queryLimit)\n * [where](#queryWhere)\n * [whereIn](#queryWhereIn)\n * [count](#queryCount)\n * [min](#queryMin)\n * [max](#queryMax)\n * [sum](#querySum)\n * [deleteAll](#queryDeleteAll)\n * [updateAll](#queryUpdateAll)\n * [include](#queryInclude)\n\n## Transaction\n\n * [commit](#txCommit)\n * [rollback](#txRollback)\n\n## Results Set\n * [getById](#resultSetGetById)\n\n## Connection Pooling\n * [using](#connectionPoolingUsing)\n\n\u003ca name=\"databaseJson\"/\u003e\n# database.json\n\nIf the current working directory contains a file called database.json this file will be loaded upon requiring persist.\nThe file should follow a format like this:\n\n    {\n      \"default\": \"dev\",\n\n      \"dev\": {\n        \"driver\": \"sqlite3\",\n        \"filename\": \":memory:\"\n      },\n\n      \"test\": {\n        \"driver\": \"sqlite3\",\n        \"filename\": \":memory:\"\n      },\n\n      \"prod\": {\n        \"driver\": \"sqlite3\",\n        \"filename\": \"prod.db\",\n        \"sqlDir\": \"./prodSql\",\n        \"pooling\": {\n          \"name\": \"testPool\",\n          \"max\": 2,\n          \"min\": 1,\n          \"idleTimeoutMillis\": 30000\n        }\n      }\n    }\n\n\"default\" specifies which environment to load.\n\n# API Documentation\n\n\u003ca name=\"persist\"/\u003e\n## persist\n\n\u003ca name=\"persistEnv\" /\u003e\n### persist.env\n\nThe environment to read from the database.json file. If not set will use the value of default from the database.json.\n\n__Example__\n\n    persist.env = 'prod';\n\n\u003ca name=\"persistConnect\" /\u003e\n### persist.connect([options], callback)\n\nConnects to a database.\n\n__Arguments__\n\n * options - (optional) Options used to connect to the database. If options are not specified the default connect options are used.\n             see [database.json](#databaseJson) and [SetDefaultConnectOptions](#persistSetDefaultConnectOptions)\n  * driver - The driver to use to connect (ie sqlite3, mysql, oracle, or postgresql).\n  * db - If db is specified this parameter will be assumed to be an already open connection to the database.\n  * _other_ - see the documentation for your driver. The options hash will be passed to that driver.\n * callback(err, connection) - Callback to be called when the connection is established.\n\n__Example__\n```javascript\npersist.connect({\n  driver: 'sqlite3',\n  filename: 'test.db',\n  trace: true\n}, function(err, connection) {\n  // connnection esablished\n});\n```\n\u003ca name=\"persistDefine\" /\u003e\n### persist.define(modelName, properties, [opts]): Model\n\nDefines a model object for use in persist.\n\nThe primary key column does not need to be specified and will default to the name 'id' with the attributes dbColumnName='id',\ntype='integer'. You can override the database name using dbColumnName or setting the primaryKey attribute on any column.\n\n__Arguments__\n\n * modelName - The name of the model. This name will map to the database name.\n * properties - Hash of properties (or columns). The value of each property can simply be the type name (ie type.STRING)\n                or it can be a hash of more options.\n  * type - type of the property (ie type.STRING)\n  * defaultValue - this can be a value or a function that will be called each time this model object is created\n  * dbColumnName - the name of the database column. (default: name of the property, all lower case, seperated by '_')\n  * primaryKey - Marks this column as being the primary key column. You can have only one primary key column.\n * opts - Options for this column.\n  * tableName - The name of the table (default: modelName pluralized).\n\n__Returns__\n\n A model class.\nEvents can also be registered with model instances - see [Model Events](#modelEvents)\n\n__Example__\n```javascript\nPerson = persist.define(\"Person\", {\n  \"name\": type.STRING,\n  \"createdDate\": { type: type.DATETIME, defaultValue: function() { return self.testDate1 }, dbColumnName: 'new_date' },\n  \"lastUpdated\": { type: type.DATETIME }\n})\n```\n\u003ca name=\"persistDefineAuto\" /\u003e\n### persist.defineAuto(modelName, dbConfig, callback): Model\n\nDefines a model object for use in persist. Columns are defined by the program in this method. Uses an existing database connection to retrieve column data.\n\n__Arguments__\n\n * modelName - The name of the model. This name will map to the table name.\n * dbConfig - Hash of dbConfig. Should contain the driver, as well as the database name.\n * database - The database connection to use.\n * driver - The name of the database driver to use.\n\n__Returns__\n\n A model class.\nEvents can also be registered with model instances - see [Model Events](#modelEvents)\n\n__Example__\n```javascript\npersist.defineAuto(\"Person\",{driver:dbDriver, db:self.connection.db},function(err,model){\n  Person = model.hasMany(Phone)\n    .on('beforeSave', function (obj) {\n      obj.lastUpdated = testDate;\n    })\n    .on('afterSave', function (obj) {\n      if (!obj.updateCount) obj.updateCount = 0;\n      obj.updateCount++;\n    });\n});\n```\n\u003ca name=\"persistSetDefaultConnectOptions\"/\u003e\n### persist.setDefaultConnectOptions(options)\n\nSets the default connection options to be used on future connect calls. see [database.json](#databaseJson)\n\n__Arguments__\n * options - See [connect](#persistConnect) for the description of options\n\n__Example__\n```javascript\npersist.setDefaultConnectOptions({\n  driver: 'sqlite3',\n  filename: 'test.db',\n  trace: true});\n```\n\u003ca name=\"persistShutdown\"/\u003e\n### persist.shutdown([callback])\n\nShutdown persist. This is currently only required if you are using connection pooling. see [generic-pool](https://github.com/coopernurse/node-pool).\n\n__Arguments__\n * [callback] - Optional callback on successful shutdown.\n\n__Example__\n```javascript\npersist.shutdown(function() {\n  console.log('persist shutdown');\n});\n```\n\u003ca name=\"connection\"/\u003e\n## Connection\n\n\u003ca name=\"connectionChain\"/\u003e\n### connection.chain(chainables, callback)\n\nChains multiple statements together in order and gets the results.\n\n__Arguments__\n\n * chainables - An array of chainable queries. These can be save, updates, selects, or deletes. Each item in the array will be\n   executed, wait for the results, and then execute the next. This can also be a hash of queries in which case the results\n   will contain a hash of results where each key corresponds to a key in the results.\n * callback(err, results) - Callback called when all the items have been executed.\n\n__Example__\n```javascript\n// array chaining\nconnection.chain([\n  person3.save,\n  Person.min('age'),\n  Person.max('age'),\n  phone3.delete,\n  person2.delete,\n  Person.orderBy('name').all,\n  Phone.orderBy('number').first,\n  Phone.count,\n  Phone.deleteAll,\n  Phone.all,\n  Person.getById(1),\n  persist.runSql('SELECT * FROM Person')\n], function(err, results) {\n  // results[0] = person3\n  // results[1] = 21\n  // results[2] = 25\n  // results[3] = []\n  // results[4] = []\n  // results[5] = -- all people ordered by name\n  // results[6] = -- first phone ordered by number\n  // results[7] = 100\n  // results[8] = []\n  // results[9] = [] -- nobody left\n  // results[10] = -- the person with id 1\n  // results[11] = Results of select.\n});\n\n// mapped chaining\nconnection.chain({\n  minAge: Person.min('age'),\n  maxAge: Person.max('age')\n}, function(err, results) {\n  // results.minAge = 21\n  // results.maxAge = 25\n});\n```\n\u003ca name=\"connectionTx\"/\u003e\n### connection.tx(callback)\n\nBegins a transaction on the connection.\n\n__Arguments__\n\n * callback(err, tx) - Callback called when the transaction has started. tx is a transaction object which you can\n   call [commit](#txCommit) or [rollback](#txRollback)\n\n__Example__\n```javascript\nconnection.tx(function(err, tx) {\n  person1.save(connection, function(err) {\n    tx.commit(function(err) {\n      // person1 saved and committed to database\n    });\n  });\n});\n```\n\u003ca name=\"connectionRunSql\"/\u003e\n### connection.runSql(sql, values, callback)\n\nRuns a sql statement that does not return results (INSERT, UPDATE, etc).\n\n__Arguments__\n\n * sql - The SQL statement to run.\n * values - The values to substitute in the SQL statement. This is DB specific but typically you would use \"?\".\n * callback(err, results) - Callback called when SQL statement completes. results will contain the number of affected\n   rows or last insert id.\n\n__Example__\n```javascript\nconnection.runSql(\"UPDATE people SET age = ?\", [32], function(err, results) {\n  // people updated\n});\n```\n\u003ca name=\"connectionRunSqlAll\"/\u003e\n### connection.runSqlAll(sql, values, callback)\n\nRuns a sql statement that returns results (ie SELECT).\n\n__Arguments__\n\n * sql - The SQL statement to run.\n * values - The values to substitute in the SQL statement. This is DB specific but typically you would use \"?\".\n * callback(err, results) - Callback called when SQL statement completes. results will contain the row data.\n\n__Example__\n```javascript\nconnection.runSqlAll(\"SELECT * FROM people WHERE age = ?\", [32], function(err, people) {\n  // people contains all the people with age 32\n});\n```\n\u003ca name=\"connectionRunSqlEach\"/\u003e\n### connection.runSqlEach(sql, values, callback, doneCallback)\n\nRuns a sql statement that returns results (ie SELECT). This is different from runSqlAll in that it returns each row\nin a seperate callback.\n\n__Arguments__\n\n * sql - The SQL statement to run.\n * values - The values to substitute in the SQL statement. This is DB specific but typically you would use \"?\".\n * callback(err, row) - Callback called for each row returned.\n * doneCallback(err) - Callback called after all the rows have returned.\n\n__Example__\n```javascript\nconnection.runSqlEach(\"SELECT * FROM people WHERE age = ?\", [32], function(err, person) {\n  // a single person\n}, function(err) {\n  // all done\n});\n```\n\u003ca name=\"connectionRunSqlFromFile\"/\u003e\n\u003ca name=\"connectionRunSqlAllFromFile\"/\u003e\n\u003ca name=\"connectionRunSqlEachFromFile\"/\u003e\n### connection.runSqlFromFile(filename, values, callback)\n### connection.runSqlAllFromFile(filename, values, callback)\n### connection.runSqlEachFromFile(filename, values, callback, doneCallback)\n\nSame as [runSql](#connectionRunSql), [runSqlAll](#connectionRunSqlAll), [runSqlEach](#connectionRunSqlEach) except the first parameter is a filename of where to load the SQL from.\n\n__Example__\n```javascript\nconnection.runSqlFromFile('report.sql', [32], function(err, person) {\n  // a single person\n}, function(err) {\n  // all done\n});\n```\n\u003ca name=\"model\" /\u003e\n## Model\n\n\u003ca name=\"modelHasMany\" /\u003e\n### Model.hasMany(AssociatedModel, [options]): Model\n\nAdds a has many relationship to a model. This will automatically add a property to the associated model which links to this\nmodel. It will also define a property on instances of this model to get the releated objects - see [Associated Object Properties](#associatedObjectProperties)\n\n__Arguments__\n\n * AssociatedModel - The name of the model to associate to.\n * options - (optional) An hash of options.\n  * through - creates a many to many relationship using the value of through as the join table.\n  * name - the name of the property to expose.\n\n__Returns__\n\n The model class object suitable for chaining.\n\n__Example__\n```javascript\nPhone = persist.define(\"Phone\", {\n  \"number\": persist.String\n});\n\nPerson = persist.define(\"Person\", {\n  \"name\": persist.String\n}).hasMany(Phone);\n```\n\u003ca name=\"modelHasOne\" /\u003e\n### Model.hasOne(AssociatedModel, [options]): Model\n\nAdds a has one relationship to a model. This will automatically add a property to the associated model which links to this\nmodel. It will also define a property on instances of this model to get the releated objects - see [Associated Object Properties](#associatedObjectProperties)\n\n__Arguments__\n\n * AssociatedModel - The name of the model to associate to.\n * options - (optional) An hash of options.\n  * foreignKey - The foreign key to use for the relationship\n  * name - the name of the property to expose.\n  * createHasMany - true/false to create the other side of the relationship.\n  * hasManyName - The name of the property on the other side of the relationship.\n\n__Returns__\n\n The model class object suitable for chaining.\n\n__Example__\n```javascript\nPhone = persist.define(\"Phone\", {\n  \"number\": persist.String\n}).hasOne(Person);\n\nPerson = persist.define(\"Person\", {\n  \"name\": persist.String\n});\n```\n\u003ca name=\"modelUsing\" /\u003e\n### Model.using(connection): query\n\nGets a query object bound to a connection object.\n\n__Arguments__\n\n * connection - The connection to bind the query object to.\n\n__Returns__\n\n A new [Query](#query) object.\n\n__Example__\n```javascript\nPerson.using(connection).first(...);\n```\n\u003ca name=\"modelSave\" /\u003e\n### Model.save(connection, callback)\n\nSaves the model object to the database\n\n__Arguments__\n\n * connection - The connection to use to save the object with.\n * callback(err) - The callback to be called when the save is complete\n\n__Example__\n```javascript\nperson1.save(connection, function() {\n  // person1 saved\n});\n```\n\u003ca name=\"modelInstanceUpdate\" /\u003e\n### modelInstance.update(connection, params, callback)\n\nUpdates the model object to the database\n\n__Arguments__\n\n * connection - The connection to use to update the object with.\n * params - Object containing properties to update.\n * callback(err) - The callback to be called when the update is complete\n\n__Example__\n```javascript\nperson1.update(connection, { name: 'Tom' }, function() {\n  // person1 saved\n});\n```\n\u003ca name=\"modelUpdate\" /\u003e\n### Model.update(connection, id, params, callback)\n\nUpdates the model object specified with id to the database. This will only update the values\nspecified and will not retreive the item from the database first.\n\n__Arguments__\n\n * connection - The connection to use to update the object with.\n * id - The id of the row you would like to update.\n * params - Object containing properties to update.\n * callback(err) - The callback to be called when the update is complete\n\n__Example__\n```javascript\nPerson.update(connection, 5, { name: 'Tom' }, function() {\n  // person with id = 5 updated with name 'Tom'.\n});\n\n// or chaining\nconnection.chain([\n  Person.update(5, { name: 'Tom' })\n], function(err, results) {\n  // person with id = 5 updated with name 'Tom'.\n});\n```\n\u003ca name=\"modelDelete\" /\u003e\n### Model.delete(connection, callback)\n\nDeletes the model object from the database\n\n__Arguments__\n\n * connection - The connection to use to delete the object with.\n * callback(err) - The callback to be called when the delete is complete\n\n__Example__\n```javascript\nperson1.delete(connection, function() {\n  // person1 deleted\n});\n```\n\u003ca name=\"modelGetById\" /\u003e\n### Model.getById(connection, id, callback)\n\nGets an object from the database by id.\n\n__Arguments__\n\n * connection - The connection to use to delete the object with.\n * id - The if of the item to get.\n * callback(err, obj) - The callback to be called when the delete is complete\n\n__Example__\n```javascript\nPerson.getById(connection, 1, function(err, person) {\n  // person is the person with id equal to 1. Or null if not found\n});\n```\n\u003ca name=\"modelDefineClause\" /\u003e\n### Model.defineClause(clauseName, clauses)\n\nCreates a custom method that is a composition of clauses. `this` is set to refer to the query.\nyou're constructing.\n\n__Arguments__\n\n * clauseName - The name of the clause to be attached to the model\n * clauses - The function that describes the clause composition using a query.\n\n__Example__\n```javascript\nPerson.defineClause('clauseName', function(arg1, arg2, ...) {\n  return this.where('id \u003c ?', arg1).orderBy('id').limit(5);\n});\n\nPerson.clauseName(5).all(connection, function(err, people) {\n  // All the people with id \u003c 5, ordered by id and limited to 5\n});\n\nPerson.defineClause('clauseName2', function(connection, callback) {\n  return this\n  .where('id \u003c 5')\n  .orderBy('id')\n  .limit(5)\n  .all(connection, callback);\n});\n\nPerson.clauseName2(connection, function(err, people) {\n  // All the people with id \u003c 5, ordered by id and limited to 5\n});\n```\n\u003ca name=\"modelOnSave\" /\u003e\n### Model.onSave(obj, connection, callback)\n\nIf preset this function will be called when an update or save occures. You would typically create this method\nin your model file.\n\n__Arguments__\n\n * obj - The object or partial object, in the case of [update](#modelUpdate), being saved.\n * connection - The connection persist is currently using to do the save\n * callback() - The callback to be called when the onSave is complete\n\n__Example__\n```javascript\nPerson.onSave = function(obj, connection, callback) {\n  obj.lastUpdated = new Date();\n  callback();\n};\n```\n\u003ca name=\"modelOnLoad\" /\u003e\n### Model.onLoad(obj)\n\nIf preset this function will be called after an object is loaded from the database. You would typically\ncreate this method in your model file.\n\n__Arguments__\n\n * obj - The object that was just loaded from the database.\n * connection - The connection persist is currently using to do the save\n * callback() - The callback to be called when the onLoad is complete\n\n__Example__\n```javascript\nPerson.onLoad = function(obj, connection, callback) {\n  obj.fullName = obj.firstName + ' ' + obj.lastName;\n  callback();\n};\n```\n\u003ca name=\"modelValidate\" /\u003e\n### Model.validate(obj, callback, connection)\n\nModel validation is loosely implemented. Instead, it's left to the developers to integrate any valiation library that fits their needs.\nIf present this function will be called during a save or update operation.\n\n__Arguments__\n\n * obj - The model object\n * connection - The connection persist is currently using to do the save or update\n * callback(success, message) - The callback to be called when the validate is complete.\n  * success - False if validation failed, True otherwise\n  * message - A string containing an error message, or a custom-defined object containing vaidation information\n\n__Example__\n```javascript\nPerson = persist.define(\"Person\", {\n  \"name\": type.STRING,\n  \"age\": type.INTEGER\n};\n\n//Single message validation\nPerson.validate = function (obj, connection, callback) {\n  if (obj.name === 'bad name') {\n    return callback(false, 'You had a bad name');\n  }\n  return callback(true);\n};\n\n//Multiple message validation\nPerson.validate = function (obj, connection, callback) {\n  var errors = [];\n\n  if (obj.name === 'bad name') {\n    errors.push({name:'You had a bad name'});\n  }\n  \n  if (obj.age \u003c 0) {\n    errors.push({age:'Age must be greater than 0'});  \n  }\n  \n  if(errors.length \u003e 0) {\n    return callback(false, errors);\n  }\n  \n  return callback(true);\n};\n```\n\u003ca name=\"associatedObjectProperties\" /\u003e\n### Associated Object Properties\n\nIf you have setup an associated property using [hasMany](#modelHasMany) instances of your model will have an additional property\nwhich allows you to get the associated data. This property returns a [Query](#query) object which you can further chain to limit\nthe results.\n\n__Example__\n```javascript\nPhone = persist.define(\"Phone\", {\n  \"number\": persist.String\n});\n\nPerson = persist.define(\"Person\", {\n  \"name\": persist.String\n}).hasMany(Phone);\n\nPerson.using(connection).first(function(err, person) {\n  person.phones.orderBy('number').all(function(err, phones) {\n    // all the phones of the first person\n  });\n});\n```\n\u003ca name=\"modelEvents\" /\u003e\n### Model Events\n\nThe following events can be registered when defining a new model:\n\n * ```beforeCreate``` and ```afterCreate```: fired before/after a new object is being added to the DB\n * ```beforeUpdate``` and ```afterUpdate```: fired before/after an existing object is being updated in the DB\n * ```beforeSave``` and ```afterSave```: fired before/after an object is either created or updated.\n * ```beforeDelete``` and ```afterDelete```: fired before/after an object is removed from the DB\n\nEach event function has the signature: function(obj) where 'obj' is the model instance that fired the event.\n\n__Limitation__\n\nEvents are currently fired ONLY when invoking save/update/delete functions on model instances. So for instance, Model.update(connection,id,data) will not fire the save \u0026 update events.\n\n__Example__\n```javascript\nPhone = persist.define(\"Phone\", {\n  \"number\": persist.String,\n  \"created_at\": persist.DATETIME,\n  \"updated_at\": persist.DATETIME\n})\n.on(\"beforeCreate\", function(obj){\n  obj.created_at = new Date();\n})\n.on(\"beforeSave\", function(obj){\n  // updated when creating or updating the model instance\n  obj.updated_at = new Date();\n});\n```\n\u003ca name=\"query\" /\u003e\n## Query\n\n\u003ca name=\"queryAll\" /\u003e\n### query.all([connection], callback)\n\nGets all items from a query as a single array of items. The array returned will have additional\nmethods see [here for documentation](#resultSetMethods).\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * callback(err, items) - Callback to be called after the rows have been fetched. items is an array of model instances.\n\n__Example__\n```javascript\nPerson.all(connection, function(err, people) {\n  // all the people\n});\n```\n\u003ca name=\"queryEach\" /\u003e\n### query.each([connection], callback, doneCallback)\n\nGets items from a query calling the callback for each item returned.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * callback(err, item) - Callback to be called after each row has been fetched. item is a model instance.\n * doneCallback(err) - Callback called after all rows have been retrieved.\n\n__Example__\n```javascript\nPerson.each(connection, function(err, person) {\n  // a person\n}, function() {\n  // all done\n});\n```\n\u003ca name=\"queryFirst\" /\u003e\n### query.first([connection], callback)\n\nGets the first item from a query.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * callback(err, item) - Callback to be called after the row has been fetched. item is a model instance.\n\n__Example__\n```javascript\nPerson.first(connection, function(err, person) {\n  // gets the first person\n});\n```\n\u003ca name=\"queryLast\" /\u003e\n### query.last([connection], callback)\n\nGets the last item from a query.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * callback(err, item) - Callback to be called after the row has been fetched. item is a model instance.\n\n__Example__\n```javascript\nPerson.last(connection, function(err, person) {\n  // gets the last person\n});\n```\n\u003ca name=\"queryOrderBy\" /\u003e\n### query.orderBy(propertyName, direction): query\n\nOrders the results of a query.\n\n__Arguments__\n\n * propertyName - Name of the property to order by.\n * direction - The direction to orderBy. Can be persist.Ascending or persist.Descending.\n\n__Returns__\n\n The query object suitable for chaining.\n\n__Example__\n```javascript\nPerson.orderBy('name').all(connection, function(err, people) {\n  // all the people ordered by name\n});\n```\n\u003ca name=\"queryLimit\" /\u003e\n### query.limit(count, [offset]): query\n\nLimits the number of results of a query.\n\n__Arguments__\n\n * count - Number of items to return.\n * offset - (Optional) The number of items to skip.\n\n__Returns__\n\n The query object suitable for chaining.\n\n__Example__\n```javascript\nPerson.orderBy('name').limit(5, 5).all(connection, function(err, people) {\n  // The 5-10 people ordered by name\n});\n```\n\u003ca name=\"queryWhere\" /\u003e\n### query.where(clause, [values...]): query\n### query.where(hash): query\n\nFilters the results by a where clause.\n\n__Arguments__\n\n * clause - A clause to filter the results by.\n * values - (Optional) A single value or array of values to substitute in for '?'s in the clause.\n * hash - A hash of columns and values to match on (see example)\n\n__Returns__\n\n The query object suitable for chaining.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').all(connection, function(err, people) {\n  // All the people named 'bob'\n});\n\nPerson.where('name = ? or age = ?', ['bob', 23]).all(connection, function(err, people) {\n  // All the people named 'bob' or people with age 23\n});\n\nPerson.where({'name': 'bob', 'age': 23}).all(connection, function(err, people) {\n  // All the people named 'bob' with the age of 23\n});\n```\n\u003ca name=\"queryWhereIn\" /\u003e\n### query.whereIn(property, [values...]): query\nFilters the results by a where clause using an IN clause.\n\n__Arguments__\n * property - The property to invoke the IN clause on.\n * values - An array of values to include in the IN clause.\n\n__Returns__\n\n The query object suitable for chaining.\n\n__Example__\n```javascript\nPerson.whereIn('name', ['bob', 'alice', 'cindy']).all(connection, function(err,people) {\n  // All the people named 'bob', 'alice', or 'cindy'\n});\n\nPerson.include(\"phones\").whereIn('phones.number', ['111-2222','333-4444']).all(connection, function(err,people){\n  // All the people whose phone numbers are '111-2222' or '333-4444'\n});\n```\n\u003ca name=\"queryCount\" /\u003e\n### query.count([connection], callback)\n\nCounts the number of items that would be returned by the query.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * callback(err, count) - Callback with the count of items.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').count(connection, function(err, count) {\n  // count = the number of people with the name bob\n});\n```\n\u003ca name=\"queryMin\" /\u003e\n### query.min([connection], fieldName, callback)\n\nGets the minimum value in the query of the given field.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * fieldName - The field name of the value you would like to get the minimum for.\n * callback(err, min) - Callback with the minimum value.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').min(connection, 'age', function(err, min) {\n  // the minimum age of all bobs\n});\n```\n\u003ca name=\"queryMax\" /\u003e\n### query.max([connection], fieldName, callback)\n\nGets the maximum value in the query of the given field.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * fieldName - The field name of the value you would like to get the maximum for.\n * callback(err, min) - Callback with the maximum value.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').max(connection, 'age', function(err, min) {\n  // the maximum age of all bobs\n});\n```\n\u003ca name=\"querySum\" /\u003e\n### query.sum([connection], fieldName, callback)\n\nGets the sum of all values in the query of the given field.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * fieldName - The field name you would like to sum.\n * callback(err, sum) - Callback with the sum value.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').sum(connection, 'age', function(err, sum) {\n  // the sum of all ages whos name is bob\n});\n```\n\u003ca name=\"queryDeleteAll\" /\u003e\n### query.deleteAll([connection], callback)\n\nDeletes all the items specified by the query.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * callback(err) - Callback called upon completion.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').deleteAll(connection, function(err) {\n  // all people name 'bob' have been deleted.\n});\n```\n\u003ca name=\"queryUpdateAll\" /\u003e\n### query.updateAll([connection], data, callback)\n\nUpdates all the items specified by the query.\n\n__Arguments__\n\n * connection - (Optional) The connection to use. If this is not specified a [using](#modelUsing) statement must be specified earlier.\n * data - A hash of properties to update. Key is the property name to update. Value is the value to update the property to.\n * callback(err) - Callback called upon completion.\n\n__Example__\n```javascript\nPerson.where('name = ?', 'bob').updateAll(connection, { age: 25 }, function(err) {\n  // all people name 'bob' have their age set to 25.\n});\n```\n\u003ca name=\"queryInclude\" /\u003e\n### query.include(propertyName): query\n\nIncludes the associated data linked by (hasMany or hasMany(through)) the propertyName when retrieving data from the database.\nThis will replace obj.propertyName with an array of results as opposed to the default before which is a query.\n\nInternally 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\nand the associated table in the case of a many to many.\n\n__Arguments__\n\n * propertyName - This can be a single property name or an array of property names to include.\n\n__Example__\n```javascript\nPerson.include(\"phones\").where('name = ?', 'bob').all(connection, function(err, people) {\n  // all people named 'bob' and all their phone numbers\n  // so you can do... people[0].phones[0].number\n  // as opposed to... people[0].phones.all(function(err, phones) {});\n});\n```\n\u003ca name=\"tx\"/\u003e\n## Transaction\n\n\u003ca name=\"txCommit\"/\u003e\n### tx.commit(callback)\n\nCommits a transaction.\n\n__Arguments__\n\n * callback(err) - Callback called when the transaction has committed.\n\n__Example__\n```javascript\nconnection.tx(function(err, tx) {\n  person1.save(connection, function(err) {\n    tx.commit(function(err) {\n      // person1 saved and committed to database\n    });\n  });\n});\n```\n\u003ca name=\"txRollback\"/\u003e\n### tx.rollback(callback)\n\nRollsback a transaction.\n\n__Arguments__\n\n * callback(err) - Callback called when the transaction has rolledback.\n\n__Example__\n```javascript\nconnection.tx(function(err, tx) {\n  person1.save(connection, function(err) {\n    tx.rollback(function(err) {\n      // person1 not saved. Transaction rolledback.\n    });\n  });\n});\n```\n\u003ca name=\"resultSetMethods\"/\u003e\n## Result Set\n\n\u003ca name=\"resultSetGetById\"/\u003e\n### rs.getById(id)\n\nGets an item from the result set by id.\n\n__Arguments__\n\n * id - The id of the item to get.\n\n__Example__\n```javascript\nPerson.all(connection, function(err, people) {\n  var person2 = people.getById(2);\n});\n```\n\u003ca name=\"connectionPooling\"/\u003e\n## Connection Pooling\n\n\u003ca name=\"connectionPoolingUsing\"/\u003e\n### Using\n\nPersist uses [generic-pool](https://github.com/coopernurse/node-pool) to manage the connection pool. If you specify\n\"pooling\" in your configuration you must specify a pool name. See [generic-pool](https://github.com/coopernurse/node-pool)\nfor other options. To cleanly shutdown the connection pool you must also call persist.[shutdown](#persistShutdown).\n\nExample database.json to enable pooling:\n\n    {\n      \"default\": \"dev\",\n\n      \"dev\": {\n        \"driver\": \"sqlite3\",\n        \"filename\": \":memory:\",\n        \"pooling\": {\n          \"name\": \"myDatabasePool\"\n        }\n      }\n    }\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoeferner%2Fnode-persist","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoeferner%2Fnode-persist","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoeferner%2Fnode-persist/lists"}