{"_id":"persistencejs","_rev":"25-438cdb45d4599d00c75a882078f96527","name":"persistencejs","dist-tags":{"latest":"0.3.0"},"versions":{"0.2.0":{"name":"persistencejs","version":"0.2.0","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"dependencies":{"mysql":">=0.1.27-12"},"_id":"persistencejs@0.2.0","engines":{"node":"*"},"_nodeSupported":true,"_npmVersion":"0.2.7-2","_nodeVersion":"v0.3.1-pre","dist":{"tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.2.0.tgz","shasum":"46fda83db9c3d974c1744a28143145294ebed7e3","integrity":"sha512-OxiWS47b41YZ0VZQTy0gXhq8cR0frWjoMguM7hPv96kZk8FKC/HLqENKNHfc+um38K6ed1iSK8PtOeUNNMhtFA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDOCFJ+AmcElkAry+KCYzW605LafUo280Ji1DvlZM1zGgIgFaVh6xlS/6pxoOb71pQ+l6h5IUCxFvrVFRLmyPb4OrA="}]}},"0.2.1":{"name":"persistencejs","version":"0.2.1","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"dependencies":{"mysql":">=0.1.27-12"},"_id":"persistencejs@0.2.1","engines":{"node":"*"},"_nodeSupported":true,"_npmVersion":"0.2.7-2","_nodeVersion":"v0.3.1-pre","dist":{"tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.2.1.tgz","shasum":"76ef5a271065a541806ab790c434c2ae41084d98","integrity":"sha512-IeCKSbfMhx/tFg8u3QlfFGvMEXOVxU41Cwx867/kmLWZiM3fe1nck3r0cmK9IxkamqMCwqgT7J5+4RzdLqCitw==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIElzRa6B4hs2RipIiecB3RXZlAj3xAsKFAKKYm6RWt0xAiAOogry0CoEp4Rl6pbVxHORj/VWJb0jyC6kQvXP0ORLkQ=="}]}},"0.2.2":{"name":"persistencejs","version":"0.2.2","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"dependencies":{"mysql":">=0.7.0"},"_id":"persistencejs@0.2.2","engines":{"node":"*"},"_nodeSupported":true,"_npmVersion":"0.2.7-2","_nodeVersion":"v0.3.1-pre","dist":{"tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.2.2.tgz","shasum":"d2fc5b6021f8db8170549f738f7f38cda3b29574","integrity":"sha512-krNiGgFZ/k2n0DU+ccY83YMIOEx1HWyHquN6MIBgtcGp9d8DqJQ9QSYkyy6hd7LsFSVWbG1+EHaor26nN8VnXg==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDkRiimmD7YckjTvTLifs3FYLMBVOPc4rICaJZaFuZDsQIgbH1iw1gXAIGHMdm+e4RJtFlwJ2ufJXHi7vMzitaDTm0="}]}},"0.2.3":{"name":"persistencejs","version":"0.2.3","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"dependencies":{"mysql":">=0.7.0"},"_id":"persistencejs@0.2.3","engines":{"node":"*"},"_nodeSupported":true,"_npmVersion":"0.2.12-1","_nodeVersion":"v0.3.1","dist":{"shasum":"a6f313d91000519e3778367428a62ab3f9145759","tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.2.3.tgz","integrity":"sha512-BaCassXobOrjFztR9D5RN20g6eeZomSSKtR//6Jm/IFxt+f8sx6Wr2m3+tEaQuYjS+KY5sL4v8b3exhNCNWl/g==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBh/671QJmdCWVoHOy54MQYrp7rjKZDQeAye2BbchhYkAiEA/tPPCJ1OXtKA5UTEDVQWvw3EnDDS+60NlewgdvLIqek="}]}},"0.2.4":{"name":"persistencejs","version":"0.2.4","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"dependencies":{"mysql":">=0.7.0"},"_id":"persistencejs@0.2.4","engines":{"node":"*"},"_engineSupported":true,"_npmVersion":"0.2.15","_nodeVersion":"v0.2.6","modules":{"persistence.big.js":"lib/persistence.big.js","persistence.jquery.js":"lib/persistence.jquery.js","persistence.jquery.mobile.js":"lib/persistence.jquery.mobile.js","persistence.js":"lib/persistence.js","persistence.migrations.js":"lib/persistence.migrations.js","persistence.pool.js":"lib/persistence.pool.js","persistence.search.js":"lib/persistence.search.js","persistence.store.memory.js":"lib/persistence.store.memory.js","persistence.store.mysql.js":"lib/persistence.store.mysql.js","persistence.store.sql.js":"lib/persistence.store.sql.js","persistence.store.websql.js":"lib/persistence.store.websql.js","persistence.sync.js":"lib/persistence.sync.js","persistence.sync.js.copy":"lib/persistence.sync.js.copy","persistence.sync.server.js":"lib/persistence.sync.server.js"},"files":[""],"_defaultsLoaded":true,"dist":{"shasum":"d922a041137b4d2f742bbe42d54fb42bb11df9fe","tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.2.4.tgz","integrity":"sha512-jR90qCipGK2wzfZtP44WVY+BCm7KWTR5POJuEGCbSNVRAFxof5/OhlYMpyQReUHbyxNW3bxE4cSJCCBqcby6Dw==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDJvWWAkpwGchspeX/KD30Qi6kv4OblAxOxvlZiHhdskgIgaXwyZheIFvI1zoa7tnw9d5fQOkNI7cHD8ZCKdbPaKls="}]}},"0.2.5":{"name":"persistencejs","version":"0.2.5","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"dependencies":{"mysql":">=0.7.0","sqlite":">=1.0.2"},"_id":"persistencejs@0.2.5","engines":{"node":"*"},"_engineSupported":true,"_npmVersion":"0.2.16","_nodeVersion":"v0.2.6","modules":{"persistence.browser.c.js":"lib/persistence.browser.c.js","persistence.browser.js":"lib/persistence.browser.js","persistence.browser.u.js":"lib/persistence.browser.u.js","persistence.jquery.js":"lib/persistence.jquery.js","persistence.jquery.mobile.js":"lib/persistence.jquery.mobile.js","persistence.js":"lib/persistence.js","persistence.migrations.js":"lib/persistence.migrations.js","persistence.pool.js":"lib/persistence.pool.js","persistence.search.js":"lib/persistence.search.js","persistence.store.appengine.js":"lib/persistence.store.appengine.js","persistence.store.config.js":"lib/persistence.store.config.js","persistence.store.memory.js":"lib/persistence.store.memory.js","persistence.store.mysql.js":"lib/persistence.store.mysql.js","persistence.store.sql.js":"lib/persistence.store.sql.js","persistence.store.sqlite.js":"lib/persistence.store.sqlite.js","persistence.store.websql.js":"lib/persistence.store.websql.js","persistence.sync.js":"lib/persistence.sync.js","persistence.sync.server.js":"lib/persistence.sync.server.js"},"files":[""],"_defaultsLoaded":true,"dist":{"shasum":"f69a32f1f694aa190f43e8913fc9d33dde0ca460","tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.2.5.tgz","integrity":"sha512-I1SenT6M4y/YLCZj7RWbCRQQuCQa2BbCiTFX6NCYT4XkvqHV6Xn9YDzdOrjKeDmcDkuES45PVW3tj3/ElJmPQw==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCEPRXW4Plx9u3rqygV0YKgih8w7PviyZ+vRn6vsaD2GQIgQNxQe813C8McNvu/8zv2bBHec1kVwuH7Zc3YJ5ZPomk="}]}},"0.3.0":{"name":"persistencejs","version":"0.3.0","engine":"node >=0.2.0","author":{"name":"Zef Hemel"},"directories":{"lib":"./lib"},"contributors":[{"name":"Zef Hemel","email":"zef@zef.me"},{"name":"Fabio Rehm","email":"fgrehm@gmail.com"},{"name":"Lukas Berns"},{"name":"Roberto Saccon","email":"rsaccon@gmail.com"},{"name":"Wilker Lúcio","email":"wilkerlucio@gmail.com"},{"name":"Bruno Jouhier","email":"bjouhier@gmail.com"},{"name":"Robin Wenglewski","email":"robin@wenglewski.de"},{"name":"Matthias Hochgatterer","email":"matthias.hochgatterer@gmail.com"},{"name":"Chris Chua","email":"chris.sirhc@gmail.com"},{"name":"Mike Smullin","email":"mike@smullindesign.com"},{"name":"Masahiro Hayashi","email":"hayashi.masahiro@gmail.com"},{"name":"Mick Staugaard","email":"mick@staugaard.com"},{"name":"Shane Tomlinson","email":"set117@gmail.com"},{"name":"Eugene Ware","email":"eugene.ware@nextharbour.com"}],"readme":"persistence.js\n==============\n`persistence.js` is a asynchronous Javascript object-relational\nmapper library. It can be used both in the web browser and on\nthe server using [node.js](http://nodejs.org). It currently\nsupports 4 types of data stores:\n\n* [HTML5 WebSQL database](http://dev.w3.org/html5/webdatabase/), a\n  somewhat controversial part of HTML5 that is supported in Webkit\n  browsers, specifically on mobile devices, including iPhone, Android\n  and Palm's WebOS. \n* [Google Gears](http://gears.google.com), a browser plug-in that adds\n  a number of feature to the browser, including a in-browser database.\n* [MySQL](http://www.mysql.com), using the\n  [node-mysql](http://github.com/felixge/node-mysql), node.js module\n  on the server.\n* In-memory, as a fallback. Keeps the database in memory and is\n  cleaned upon a page refresh (or server restart), unless saved to\n  [localStorage](http://dev.w3.org/html5/webstorage/).\n\nThere is also an experimental support for [Qt 4.7 Declarative UI\nframework\n(QML)](http://doc.trolltech.org/4.7-snapshot/declarativeui.html) which\nis an extension to JavaScript.\n\nFor browser use, `persistence.js` has no dependencies on any other\nframeworks, other than the Google Gears [initialization\nscript](http://code.google.com/apis/gears/gears_init.js), in case you\nwant to enable Gears support.\n\nPlug-ins\n--------\n\nThere are a few `persistence.js` plug-ins available that add functionality:\n\n* `persistence.search.js`, adds simple full-text search capabilities,\n  see `docs/search.md` for more information.\n* `persistence.migrations.js`, supports data migrations (changes to\n  the database schema), see `docs/migrations.md` for more information.\n* `persistence.sync.js`, supports database synchronization with a\n  remote server, see `docs/sync.md` for more information.\n* `jquery.persistence.js`, adds jQuery integration, including \n  jQuery-mobile ajax request interception and re-routing to persistencejs,\n  see `docs/jquery.md` for more information and `demo/jquerymobile` for a \n  simple demo.\n\nA Brief Intro to Async Programming\n----------------------------------\n\nIn browsers, Javascript and the web page's rendering engine share\na single thread. The result of this is that only one thing can happen\nat a time. If a database query would be performed _synchronously_,\nlike in many other programming environments like Java and PHP the\nbrowser would freeze from the moment the query was issued until the\nresults came back. Therefore, many APIs in Javascript are defined as\n_asynchronous_ APIs, which mean that they do not block when an\n\"expensive\" computation is performed, but instead provide the call\nwith a function that will be invoked once the result is known. In the\nmeantime, the browser can perform other duties.\n\nFor instance, a synchronous database call call would look as follows:\n\n    var results = db.query(\"SELECT * FROM Table\");\n    for(...) { ... }\n\nThe execution of the first statement could take half a second, during\nwhich the browser doesn't do anything else. By contrast, the\nasynchronous version looks as follows:\n\n    db.query(\"SELECT * FROM Table\", function(results) {\n      for(...) { ... }\n    });\n\nNote that there will be a delay between the `db.query` call and the\nresult being available and that while the database is processing the\nquery, the execution of the Javascript continues. To make this clear,\nconsider the following program:\n    \n    db.query(\"SELECT * FROM Table\", function(results) {\n      console.log(\"hello\");\n    });\n    console.log(\"world\");\n\nAlthough one could assume this would print \"hello\", followed by\n\"world\", the result will likely be that \"world\" is printed before\n\"hello\", because \"hello\" is only printed when the results from the\nquery are available. This is a tricky thing about asynchronous\nprogramming that a Javascript developer will have to get used to.\n\nUsing persistence.js in the browser\n===================================\n\nBrowser support\n---------------\n\n* Modern webkit browsers (Google Chrome and Safari)\n* Firefox (through Google Gears)\n* Opera\n* Android browser (tested on 1.6 and 2.x)\n* iPhone browser (iPhone OS 3+)\n* Palm WebOS (tested on 1.4.0)\n* Other browsers supporting `localStorage` (e.g. Firefox)\n\n(The following is being worked on:)\nInternet Explorer is likely not supported (untested) because it\nlacks `__defineGetter__` and `__defineSetter__` support, which\n`persistence.js` uses heavily. This may change in IE 9.\n\nSetting up\n----------\n\nTo use `persistence.js` you need to clone the git repository:\n\n    git clone git://github.com/zefhemel/persistencejs.git\n\nTo use it you need to copy `lib/persistence.js` to your web directory,\nas well as any data stores you want to use. Note that the `mysql` and\n`websql` stores both depend on the `sql` store. A typical setup\nrequires you to copy at least `lib/persistence.js`,\n`lib/persistence.store.sql.js` and `lib/persistence.store.websql.js` to your\nweb directory. You can then load them as follows:\n\n    <script src=\"persistence.js\" type=\"application/javascript\"></script>\n    <script src=\"persistence.store.sql.js\" type=\"application/javascript\"></script>\n    <script src=\"persistence.store.websql.js\" type=\"application/javascript\"></script>\n\nIf you want to use the in-memory store (in combination with\n`localStorage`) you also need the `persistence.store.memory.js`\nincluded.\n\n\nSetup your database\n-------------------\n\nYou need to explicitly configure the data store you want to use,\nconfiguration of the data store is store-specific. The WebSQL store\n(which includes Google Gears support) is configured as follows:\n\n    persistence.store.websql.config(persistence, 'yourdbname', 'A database description', 5 * 1024 * 1024);\n\nThe first argument is always supposed to be `persistence`. The second\nin your database name (it will create it if it does not already exist,\nthe third is a description for you database, the last argument is the\nmaximum size of your database in bytes (5MB in this example).\n\nThe in-memory store\n---------------------------------------\n\nThe in-memory store is offered as a fallback for browsers that do not\nsupport any of the other supported stores (e.g. WebSQL or Gears). In\nprincipal, it only keeps data in memory, which means that navigating\naway from the page (including a reload or tab close) will result in\nthe loss of all data.\n\nA way around this is using the `persistence.saveToLocalStorage` and\n`persistence.loadFromLocalStorage` functions that can save the entire\ndatabase to the [localStorage](http://dev.w3.org/html5/webstorage/), which\nis persisted indefinitely (similar to WebSQL).\n\nIf you're going to use the in-memory store, you can configure it as follows:\n\n    persistence.store.memory.config(persistence);\n\nThen, if desired, current data can be loaded from the localStorage using:\n\n    persistence.loadFromLocalStorage(function() {\n      alert(\"All data loaded!\");\n    });\n\nAnd saved using:\n\n    persistence.saveToLocalStorage(function() {\n      alert(\"All data saved!\");\n    });\n\nDrawbacks of the in-memory store:\n\n* Performance: All actions that are typically performed by a database\n  (sorting, filtering), are now all performed in-memory using\n  Javascript.\n* Limited database size: Loading and saving requires serialization of\n  all data from and to JSON, which gets more expensive as your dataset\n  grows. Most browsers have a maximum size of 5MB for `localStorage`.\n* Synchronous behavior: Although the API is asynchronous, all\n  persistence actions will be performed synchronously on the main\n  Javascript thread, which may make the browser less responsive.\n\nSchema definition\n-----------------\n\nA data model is declared using `persistence.define`. The following two\ndefinitions define a `Task` and `Category` entity with a few simple\nproperties. The property types are based on [SQLite\ntypes](http://www.sqlite.org/datatype3.html), specifically supported\ntypes are (but any SQLite type is supported):\n\n* `TEXT`: for textual data \n* `INT`: for numeric values\n* `BOOL`: for boolean values (`true` or `false`)\n* `DATE`: for date/time value (with precision of 1 second)\n* `JSON`: a special type that can be used to store arbitrary\n  [JSON](http://www.json.org) data. Note that this data can not be used\n  to filter or sort in any sensible way. If internal changes are made to a `JSON`\n  property, `persistence.js` may not register them. Therefore, a manual\n  call to `anObj.markDirty('jsonPropertyName')` is required before calling\n  `persistence.flush`.\n\nExample use:\n    \n    var Task = persistence.define('Task', {\n      name: \"TEXT\",\n      description: \"TEXT\",\n      done: \"BOOL\"\n    });\n\n    var Category = persistence.define('Category', {\n      name: \"TEXT\",\n      metaData: \"JSON\"\n    });\n\n    var Tag = persistence.define('Tag', {\n      name: \"TEXT\"\n    });\n\nThe returned values are constructor functions and can be used to\ncreate new instances of these entities later.\n\nIt is possible to create indexes on one or more columns using\n`EntityName.index`, for instance:\n\n    Task.index('done');\n    Task.index(['done', 'name']);\n\nThese indexes can also be used to impose unique constraints :\n\n    Task.index(['done', 'name'],{unique:true});\n\nRelationships between entities are defined using the constructor\nfunction's `hasMany` call:\n\n    // This defines a one-to-many relationship:\n    Category.hasMany('tasks', Task, 'category');\n    // These two definitions define a many-to-many relationship\n    Task.hasMany('tags', Tag, 'tasks');\n    Tag.hasMany('tasks', Task, 'tags');\n        \nThe first statement defines a `tasks` relationship on category objects\ncontaining a `QueryCollection` (see the section on query collections\nlater) of `Task`s, it also defines an inverse relationship on `Task`\nobjects with the name `category`. The last two statements define a\nmany-to-many relationships between `Task` and `Tag`. `Task` gets a\n`tags` property (a `QueryCollection`) containing all its tags and vice\nversa, `Tag` gets a `tasks` property containing all of its tasks.\n\nThe defined entity definitions are synchronized (activated) with the\ndatabase using a `persistence.schemaSync` call, which takes a callback\nfunction (with a newly created transaction as an argument), that is called\nwhen the schema synchronization has completed, the callback is\noptional.\n\n    persistence.schemaSync();\n    // or\n    persistence.schemaSync(function(tx) { \n      // tx is the transaction object of the transaction that was\n      // automatically started\n    });\n\nThere is also a migrations plugin you can check out, documentation can be found\nin [persistence.migrations.docs.md](migrations/persistence.migrations.docs.md) file.\n\nMix-ins\n-------\n\nYou can also define mix-ins and apply them to entities of the model. \n\nA mix-in definition is similar to an entity definition, except using\n`defineMixin` rather than just `define`. For example:\n\n    var Annotatable = persistence.defineMixin('Annotatable', {\n      lastAnnotated: \"DATE\"\n    });\n\nYou can define relationships between mix-in and entities. For example:\n\n    // A normal entity\n    var Note = persistence.define('Note', {\n      text: \"TEXT\"\n    });\n  \n    // relationship between a mix-in and a normal entity\n    Annotatable.hasMany('notes', Note, 'annotated');\n\nOnce you have defined a mix-in, you can apply it to any entity of your model, \nwith the `Entity.is(mixin)` method. For example:\n\n    Project.is(Annotatable);\n    Task.is(Annotatable);\n    \nNow, your `Project` and `Task` entities have an additional `lastAnnotated` property.\nThey also have a one to many relationship called `notes` to the `Note` entity. \nAnd you can also traverse the reverse relationship from a `Note` to its `annotated` object.\n\nNote that `annotated` is a polymorphic relationship as it may yield either a `Project` \nor a `Task` (or any other entity which is `Annotatable').\n\nNote: Prefetch is not allowed (yet) on a relationship that targets a mixin. In the example above\nyou cannot prefetch the `annotated` relationship when querying the `Note` entity.\n    \nNotes: this feature is very experimental at this stage. It needs more testing.\n  Support for \"is a\" relationships (classical inheritance) is also in the works.\n\nCreating and manipulating objects\n---------------------------------\n\nNew objects can be instantiated with the constructor functions.\nOptionally, an object with initial property values can be passed as\nwell, or the properties may be set later:\n\n    var task = new Task();\n    var category = new Category({name: \"My category\"});\n    category.metaData = {rating: 5};\n    var tag = new Tag();\n    tag.name = \"work\";\n\nMany-to-one relationships are accessed using their specified name, e.g.:\n    task.category = category;\n\nOne-to-many and many-to-many relationships are access and manipulated\nthrough the `QueryCollection` API that will be discussed later:\n\n    task.tags.add(tag);\n    tasks.tags.remove(tag);\n    tasks.tags.list(tx, function(allTags) { console.log(allTags); });\n\nPersisting/removing objects\n---------------------------\n\nSimilar to [hibernate](http://www.hibernate.org), `persistence.js`\nuses a tracking mechanism to determine which objects' changes have to\nbe persisted to the database. All objects retrieved from the database\nare automatically tracked for changes. New entities can be tracked to\nbe persisted using the `persistence.add` function:\n        \n    var c = new Category({name: \"Main category\"});\n    persistence.add(c);\n    for ( var i = 0; i < 5; i++) {\n      var t = new Task();\n      t.name = 'Task ' + i;\n      t.done = i % 2 == 0;\n      t.category = c;\n      persistence.add(t);\n    }\n\nObjects can also be removed from the database:\n\n    persistence.remove(c);\n\nAll changes made to tracked objects can be flushed to the database by\nusing `persistence.flush`, which takes a transaction object and\ncallback function as arguments. A new transaction can be started using\n`persistence.transaction`:\n    \n    persistence.transaction(function(tx) {\n      persistence.flush(tx, function() {\n        alert('Done flushing!');\n      });\n    });\n\nFor convenience, it is also possible to not specify a transaction or\ncallback, in that case a new transaction will be started\nautomatically. For instance:\n\n    persistence.flush();\n    // or, with callback\n    persistence.flush(function() {\n      alert('Done flushing');\n    });\n\nNote that when no callback is defined, the flushing still happens\nasynchronously.\n\n__Important__: Changes and new objects will not be persisted until you\nexplicitly call `persistence.flush()`. The exception to this rule is\nusing the `list(...)` method on a database `QueryCollection`, which also\nflushes first, although this behavior may change in the future. \n\nDumping and restoring data\n--------------------------\n\nThe library supports two kinds of dumping and restoring data.\n\n`persistence.dump` can be used to create an object containing a full\ndump of a database. Naturally, it is adviced to only do this with\nsmaller databases. Example:\n\n    persistence.dump(tx, [Task, Category], function(dump) {\n      console.log(dump);\n    });\n\nThe `tx` is left out, a new transaction will be started for the\noperation. If the second argument is left out, `dump` defaults\nto dumping _all_ defined entities.\n\nThe dump format is:\n    \n    {\"entity-name\": [list of instances],\n     ...}\n\n`persistence.load` is used to restore the dump produced by\n`persistence.dump`. Usage:\n\n    persistence.load(tx, dumpObj, function() {\n      alert('Dump restored!');\n    });\n\nThe `tx` argument can be left out to automatically start a new\ntransaction. Note that `persistence.load` does not empty the database\nfirst, it simply attempts to add all objects to the database. If\nobjects with, e.g. the same ID already exist, this will fail.\n\nSimilarly, `persistence.loadFromJson` and `persistence.dumpToJson`\nrespectively load and dump all the database's data as JSON strings.\n\nEntity constructor functions\n----------------------------\n\nThe constructor function returned by a `persistence.define` call\ncannot only be used to instantiate new objects, it also has some\nuseful methods of its own:\n\n* `EntityName.all([session])` returns a query collection containing\nall\n  persisted instances of that object. The `session` argument is\n  optional and only required when `persistence.js` is used in\n  multi-session mode.\n* `EntityName.load([session], [tx], id, callback)` loads an particular\n  object from the database by id or returns `null` if it has not been\n  found.\n* `EntityName.findBy([session], [tx], property, value, callback)` searches\n  for a particular object based on a property value (this is assumed to\n  be unique), the callback function is called with the found object or\n  `null` if it has not been found.\n* `EntityName.index([col1, col2, ..., colN], options)` creates an index on a column\n  of a combination of columns, for faster searching. If options.unique is true,\n  the index will impose a unique constraint on the values of the columns.\n\nAnd of course the methods to define relationships to other entities:\n\n* `EntityName.hasMany(property, Entity, inverseProperty)` defines a\n  1:N or N:M relationship (depending on the inverse property)\n* `EntityName.hasOne(property, Entity)` defines a 1:1 or N:1\n  relationship\n\n\nEntity objects\n--------------\n\nEntity instances also have a few predefined properties and methods you\nshould be aware of:\n\n* `obj.id`, contains the identifier of your entity, this is a\n  automatically generated (approximation of a) UUID. You should\n  never write to this property.\n* `obj.fetch(prop, callback)`, if an object has a `hasOne`\n   relationship to another which has not yet been fetched from the\n   database (e.g. when `prefetch` wasn't used), you can fetch in manually\n   using `fetch`. When the property object is retrieved the callback function\n   is invoked with the result, the result is also cached in the entity\n   object itself.\n* `obj.selectJSON([tx], propertySpec, callback)`, sometime you need to extract\n  a subset of data from an entity. You for instance need to post a\n  JSON representation of your entity, but do not want to include all\n  properties. `selectJSON` allows you to do that. The `propertySpec`\n  arguments expects an array with property names. Some examples:\n   * `['id', 'name']`, will return an object with the id and name property of this entity\n   * `['*']`, will return an object with all the properties of this entity, not recursive\n   * `['project.name']`, will return an object with a project property which has a name \n     property containing the project name (hasOne relationship)\n   * `['project.[id, name]']`, will return an object with a project property which has an\n     id and name property containing the project name (hasOne relationship)\n   * `['tags.name']`, will return an object with an array `tags` property containing \n     objects each with a single property: name\n       \n\nQuery collections\n-----------------\n\nA core concept of `persistence.js` is the `QueryCollection`. A\n`QueryCollection` represents a (sometimes) virtual collection that can\nbe filtered, ordered or paginated. `QueryCollection`s are somewhate\ninspired by [Google AppEngine's Query\nclass](http://code.google.com/appengine/docs/python/datastore/queryclass.html).\nA `QueryCollection` has the following methods:\n\n* `filter(property, operator, value)`  \n  Returns a new `QueryCollection` that adds a filter, filtering a\n  certain property based on an operator and value. Supported operators\n  are '=', '!=', '<', '<=', '>', '>=', 'in' and 'not in'. Example:\n  `.filter('done', '=', true)`\n* `or(filter)`  \n  Returns a new `QueryCollection` that contains items either matching\n  the filters specified before calling `or`, or the filter represented\n  in the argument. The `filter` argument is of a `Filter` type, there\n  are three types of filters:\n  - `persistence.PropertyFilter`, which filters on properties (internally called when `filter(...)` is used.  \n    Example: `new persistence.PropertyFilter('done', '=', true)`\n  - `persistence.AndFilter`, which is passed two filter objects as arguments, both of which should be true.\n    Example: `new persistence.AndFilter(new persistence.PropertyFilter('done', '=', true), new persistence.PropertyFilter('archived', '=', true))`\n  - `persistence.OrFilter`, which is passed two filter objects as arguments, one of which should be true.\n    Example: `new persistence.OrFilter(new persistence.PropertyFilter('done', '=', true), new persistence.PropertyFilter('archived', '=', true))`\n* `and(filter)`  \n  same as `or(filter)` except that both conditions should hold for items to be in the collection. \n* `order(property, ascending)`  \n  Returns a new `QueryCollection` that will order its results by the\n  property specified in either an ascending (ascending === true) or\n  descending (ascending === false) order.\n* `limit(n)`  \n  Returns a new `QueryCollection` that limits the size of the result\n  set to `n` items. Useful for pagination.\n* `skip(n)`  \n  Returns a new `QueryCollection` that skips the first `n` results.\n  Useful for pagination.\n* `prefetch(rel)`  \n  Returns a new `QueryCollection` that prefetches entities linked\n  through relationship `rel`, note that this only works for one-to-one\n  and many-to-one relationships.\n* `add(obj)`  \n  Adds object `obj` to the collection.\n* `remove(obj)`  \n  Removes object `obj` from the collection.\n* `list([tx], callback)`  \n  Asynchronously fetches the results matching the formulated query.\n  Once retrieved, the callback function is invoked with an array of\n  entity objects as argument.\n* `each([tx], eachCallback)`  \n  Asynchronously fetches the results matching the formulated query.\n  Once retrieved, the `eachCallback` function is invoked on each\n  element of the result objects.\n* `forEach([tx], eachCallback)`  \n  Alias for `each`\n* `one([tx], callback)`\n  Asynchronously fetches the first element of the collection, or `null` if none.\n* `destroyAll([tx], callback)`\n  Asynchronously removes all the items in the collection. __Important__: this does\n  not only remove the items from the collection, but removes the items themselves!\n* `count([tx], callback)`\n  Asynchronously counts the number of items in the collection. The arguments passed\n  to the `callback` function is the number of items.\n\nQuery collections are returned by:\n\n* `EntityName.all()`, e.g. `Task.all()`\n* one-to-many and many-to-many relationships, e.g. `task.tags`\n\nExample:\n\n    var allTasks = Task.all().filter(\"done\", '=', true).prefetch(\"category\").order(\"name\", false).limit(10);\n        \n    allTasks.list(null, function (results) {\n        results.forEach(function (r) {\n            console.log(r.name)\n            window.task = r;\n        });\n    });\n\nUsing persistence.js on the server\n==================================\n\nInstalling `persistence.js` on node is easy using [npm](http://npmjs.org):\n\n    npm install persistencejs\n\nSadly the node.js server environment requires slight changes to\n`persistence.js` to make it work with multiple database connections:\n\n* A `Session` object needs to be passed as an extra argument to\n  certain method calls, typically as a first argument.\n* Methods previously called on the `persistence` object itself are now\n  called on the `Session` object.\n\nAn example `node.js` application is included in `test/node-blog.js`. \n\nSetup\n-----\nYou need to `require` two modules, the `persistence.js` library itself\nand the MySQL backend module.\n\n    var persistence = require('persistencejs');\n    var persistenceStore = persistence.StoreConfig.init(persistence, { adaptor: 'mysql' });\n\nThen, you configure the database settings to use:\n\n    persistenceStore.config(persistence, 'localhost', 3306, 'dbname', 'username', 'password');\n\nSubsequently, for every connection you handle (assuming you're\nbuilding a sever), you call the `persistenceStore.getSession()`\nmethod:\n\n    var session = persistenceStore.getSession();\n\nThis session is what you pass around, typically together with a\ntransaction object. Note that currently you can only have one\ntransaction open per session and transactions cannot be nested.\n\n    session.transaction(function(tx) {\n      ...\n    });\n\nCommit and Rollback\n-------------------\n\n`persistence.js` works in autocommit mode by default. \n\nYou can override this behavior and enable explicit commit and rollback \nby passing true as first argument to `persistence.transaction`. \nYou can then use the following two methods to control the transaction:\n\n* `transaction.commit(session, callback)` commits the changes.\n* `transaction.rollback(session, callback)` rollbacks the changes.\n\nTypical code will look like:\n \n    session.transaction(true, function(tx) {\n      // create/update/delete objects\n      modifyThings(session, tx, function(err, result) {\n        if (err) {\n          // something went wrong\n          tx.rollback(session, function() {\n            console.log('changes have been rolled back: ' + ex.message);\n          });\n        }\n        else {\n          // success\n          tx.commit(session, function() {\n            console.log('changes have been committed: ' result);\n        });\n      });\n    });\n\nExplicit commit and rollback is only supported on MySQL (server side) \nfor now.\n\nDefining your data model\n------------------------\n\nDefining your data model is done in exactly the same way as regular `persistence.js`:\n\n    var Task = persistence.define('Task', {\n      name: \"TEXT\",\n      description: \"TEXT\",\n      done: \"BOOL\"\n    });\n\nA `schemaSync` is typically performed as follows:\n\n    session.schemaSync(tx, function() {\n      ...\n    });\n\nCreating and manipulating objects\n---------------------------------\n\nCreating and manipulating objects is done much the same way as with\nregular `persistence.js`, except that in the entity's constructor you\nneed to reference the `Session` again:\n\n    var t = new Task(session);\n    ...\n    session.add(t);\n\n    session.flush(tx, function() {\n      ...\n    });\n\nQuery collections\n-----------------\n\nQuery collections work the same way as in regular `persistence.js`\nwith the exception of the `Entity.all()` method that now also requires\na `Session` to be passed to it:\n\n    Task.all(session).filter('done', '=', true).list(tx, function(tasks) {\n      ...\n    });\n\nClosing the session\n-------------------\n\nAfter usage, you need to close your session:\n\n    session.close();\n\nBugs and Contributions\n======================\n\nIf you find a bug, please [report\nit](https://github.com/zefhemel/persistencejs/issues).  or fork the\nproject, fix the problem and send me a pull request. For a list of\nplanned features and open issues, have a look at the [issue\ntracker](https://github.com/zefhemel/persistencejs/issues).\n\nFor support and discussion, please join the [persistence.js Google\nGroup](http://groups.google.com/group/persistencejs).\n\nThanks goes to the people listed in `AUTHORS` for their contributions.\n\nIf you use [GWT](http://code.google.com/webtoolkit/) (the Google Web\nToolkit), be sure to have a look at [Dennis Z. Jiang's GWT persistence.js\nwrapper](http://github.com/dennisjzh/GwtMobile-Persistence)\n\nLicense\n=======\n\nThis work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License).\n\nSupport this work\n-----------------\n\nYou can support this project by flattering it:\n\n<a href=\"http://flattr.com/thing/2510/persistence-js\" target=\"_blank\">\n<img src=\"http://api.flattr.com/button/button-static-50x60.png\" title=\"Flattr this\" border=\"0\" /></a>\n","readmeFilename":"README.md","_id":"persistencejs@0.3.0","description":"persistence.js ============== `persistence.js` is a asynchronous Javascript object-relational mapper library. It can be used both in the web browser and on the server using [node.js](http://nodejs.org). It currently supports 4 types of data stores:","dist":{"shasum":"dfb637f29402176a18ebb01d63a4251af6caea73","tarball":"https://registry.npmjs.org/persistencejs/-/persistencejs-0.3.0.tgz","integrity":"sha512-633a6KLRO+VW3PgqrJdIvVVSAr+qomVoolZdfLNL0/9gdLnq+ToZfhDE+h8OSuaC/wTdCSerm74b+/bshYJNKA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAk3QaxaCw7Te/S4XfojxvFkwl+cw+/Y/hu8iI2Qm3vIAiAAp5K5Bg0BJ5wqqTQqyAusP8VllsGf1kNexKV72VBPvw=="}]},"_from":".","_npmVersion":"1.2.17","_npmUser":{"name":"zef","email":"zef@c9.io"},"maintainers":[{"name":"zef","email":"zef@zef.me"}]}},"maintainers":[{"name":"zef","email":"zef@zef.me"}],"author":{"name":"Zef Hemel"},"time":{"modified":"2022-06-23T18:54:06.278Z","created":"2010-12-29T08:42:20.712Z","0.2.0":"2010-12-29T08:42:20.712Z","0.2.1":"2010-12-29T08:42:20.712Z","0.2.2":"2010-12-29T08:42:20.712Z","0.2.3":"2010-12-29T08:42:20.712Z","0.2.4":"2010-12-29T08:42:20.712Z","0.2.5":"2011-02-10T10:46:20.402Z","0.3.0":"2013-06-24T05:45:35.443Z"},"description":"persistence.js ============== `persistence.js` is a asynchronous Javascript object-relational mapper library. It can be used both in the web browser and on the server using [node.js](http://nodejs.org). It currently supports 4 types of data stores:"}