Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 665 lines (513 sloc) 25.158 kb
cd6c915 Simple prefetching works.
zef authored
1 persistence.js
2 ==============
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
3 `persistence.js` is a asynchronous Javascript object-relational
4 mapper library. It can be used both in the web browser and on
5 the server using [node.js](http://nodejs.org). It currently
6 supports 4 types of data stores:
7
8 * [HTML5 WebSQL database](http://dev.w3.org/html5/webdatabase/), a
9 somewhat controversial part of HTML5 that is supported in Webkit
10 browsers, specifically on mobile devices, including iPhone, Android
11 and Palm's WebOS.
12 * [Google Gears](http://gears.google.com), a browser plug-in that adds
13 a number of feature to the browser, including a in-browser database.
14 * [MySQL](http://www.mysql.com), using the
8e903cc @zefhemel Changed used mysql connector
zefhemel authored
15 [node-mysql](http://github.com/felixge/node-mysql), node.js module
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
16 on the server.
17 * In-memory, as a fallback. Keeps the database in memory and is cleaned
18 upon a page refresh (or server restart).
19
20 There is also an experimental support for [Qt 4.7 Declarative UI
21 framework
22 (QML)](http://doc.trolltech.org/4.7-snapshot/declarativeui.html) which
23 is an extension to JavaScript.
1b2c013 @zefhemel Documentation tweaks to accomodate for server environments.
zefhemel authored
24
25 For browser use, `persistence.js` has no dependencies on any other
26 frameworks, other than the Google Gears [initialization
27 script](http://code.google.com/apis/gears/gears_init.js), in case you
28 want to enable Gears support.
cd6c915 Simple prefetching works.
zef authored
29
3d5d3f0 @zefhemel Fixes to node blogging example, and description of plug-ins added to
zefhemel authored
30 Plug-ins
31 --------
32
33 There are a few `persistence.js` plug-ins available that add functionality:
34
35 * `persistence.search.js`, adds simple full-text search capabilities,
36 see `docs/search.md` for more information.
37 * `persistence.migrations.js`, supports data migrations (changes to
38 the database schema), see `docs/migrations.md` for more information.
39 * `persistence.sync.js`, supports database synchronization with a
40 remote server, see `docs/sync.md` for more information.
04897b2 @rsaccon more jquery integration documentation
rsaccon authored
41 * `jquery.persistence.js`, adds jQuery integration, including
42 jQuery-mobile ajax request interception and re-routing to persistencejs,
43 see `docs/jquery.md` for more information and `demo/jquerymobile` for a
44 simple demo.
3d5d3f0 @zefhemel Fixes to node blogging example, and description of plug-ins added to
zefhemel authored
45
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
46 A Brief Intro to Async Programming
47 ----------------------------------
bf2edb5 More info on asynchronous programming
Zef Hemel authored
48
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
49 In browsers, Javascript and the web page's rendering engine share
50 a single thread. The result of this is that only one thing can happen
51 at a time. If a database query would be performed _synchronously_,
52 like in many other programming environments like Java and PHP the
53 browser would freeze from the moment the query was issued until the
54 results came back. Therefore, many APIs in Javascript are defined as
55 _asynchronous_ APIs, which mean that they do not block when an
56 "expensive" computation is performed, but instead provide the call
57 with a function that will be invoked once the result is known. In the
58 meantime, the browser can perform other duties.
bf2edb5 More info on asynchronous programming
Zef Hemel authored
59
60 For instance, a synchronous database call call would look as follows:
61
62 var results = db.query("SELECT * FROM Table");
63 for(...) { ... }
64
65 The execution of the first statement could take half a second, during
66 which the browser doesn't do anything else. By contrast, the
67 asynchronous version looks as follows:
68
69 db.query("SELECT * FROM Table", function(results) {
70 for(...) { ... }
71 });
72
73 Note that there will be a delay between the `db.query` call and the
74 result being available and that while the database is processing the
75 query, the execution of the Javascript continues. To make this clear,
76 consider the following program:
77
78 db.query("SELECT * FROM Table", function(results) {
79 console.log("hello");
80 });
81 console.log("world");
82
83 Although one could assume this would print "hello", followed by
84 "world", the result will likely be that "world" is printed before
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
85 "hello", because "hello" is only printed when the results from the
bf2edb5 More info on asynchronous programming
Zef Hemel authored
86 query are available. This is a tricky thing about asynchronous
87 programming that a Javascript developer will have to get used to.
88
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
89 Using persistence.js in the browser
90 ===================================
91
14f8aac Working on the readme
Zef Hemel authored
92 Browser support
93 ---------------
94
95 * Modern webkit browsers (Google Chrome and Safari)
96 * Firefox (through Google Gears)
792501e @zefhemel Working on selectJSON, refactoring some code.
zefhemel authored
97 * Android browser (tested on 1.6 and 2.x)
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
98 * iPhone browser (iPhone OS 3+)
06e6304 Added WebOS to supported platforms.
Zef Hemel authored
99 * Palm WebOS (tested on 1.4.0)
cd6c915 Simple prefetching works.
zef authored
100
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
101 (The following is being worked on:)
14f8aac Working on the readme
Zef Hemel authored
102 Internet Explorer is likely not supported (untested) because it
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
103 lacks `__defineGetter__` and `__defineSetter__` support, which
104 `persistence.js` uses heavily. This may change in IE 8.
14f8aac Working on the readme
Zef Hemel authored
105
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
106 Setting up
107 ----------
108
109 To use `persistence.js` you need to clone the git repository:
110
111 git clone git://github.com/zefhemel/persistencejs.git
112
559e75c @zefhemel Doc update
zefhemel authored
113 To use it you need to copy `lib/persistence.js` to your web directory,
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
114 as well as any data stores you want to use. Note that the `mysql` and
115 `websql` stores both depend on the `sql` store. A typical setup
559e75c @zefhemel Doc update
zefhemel authored
116 requires you to copy at least `lib/persistence.js`,
117 `lib/persistence.store.sql.js` and `lib/persistence.store.websql.js` to your
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
118 web directory. You can then load them as follows:
119
120 <script src="persistence.js" type="application/javascript"></script>
121 <script src="persistence.store.sql.js" type="application/javascript"></script>
122 <script src="persistence.store.websql.js" type="application/javascript"></script>
123
14f8aac Working on the readme
Zef Hemel authored
124
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
125 Setup your database
126 -------------------
cd6c915 Simple prefetching works.
zef authored
127
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
128 You need to explicitly configure the data store you want to use,
129 configuration of the data store is store-specific. The WebSQL store
130 (which includes Google Gears support) is configured as follows:
131
132 persistence.store.websql.config(persistence, 'yourdbname', 'A database description', 5 * 1024 * 1024);
133
134 The first argument is always supposed to be `persistence`. The second
135 in your database name (it will create it if it does not already exist,
136 the third is a description for you database, the last argument is the
137 maximum size of your database in bytes (5MB in this example).
138
139 If you're using the in-memory store, you can configure it as follows:
140
141 persistence.store.memory.config(persistence);
14f8aac Working on the readme
Zef Hemel authored
142
143 Schema definition
144 -----------------
145
146 A data model is declared using `persistence.define`. The following two
147 definitions define a `Task` and `Category` entity with a few simple
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
148 properties. The property types are based on [SQLite
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
149 types](http://www.sqlite.org/datatype3.html), specifically supported
150 types are (but any SQLite type is supported):
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
151
152 * `TEXT`: for textual data
153 * `INT`: for numeric values
154 * `BOOL`: for boolean values (`true` or `false`)
c65213f Added Fabio's Date type to documentation.
Zef Hemel authored
155 * `DATE`: for date/time value (with precision of 1 second)
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
156 * `JSON`: a special type that can be used to store arbitrary
157 [JSON](http://www.json.org) data. Note that this data can not be used
1e94adf Some more JSON property examples + minified version.
Zef Hemel authored
158 to filter or sort in any sensible way. If internal changes are made to a `JSON`
159 property, `persistence.js` may not register them. Therefore, a manual
160 call to `anObj.markDirty('jsonPropertyName')` is required before calling
161 `persistence.flush`.
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
162
163 Example use:
cd6c915 Simple prefetching works.
zef authored
164
73724ff Added .add and .remove methods to QueryCollections.
zef authored
165 var Task = persistence.define('Task', {
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
166 name: "TEXT",
167 description: "TEXT",
168 done: "BOOL"
cd6c915 Simple prefetching works.
zef authored
169 });
170
73724ff Added .add and .remove methods to QueryCollections.
zef authored
171 var Category = persistence.define('Category', {
1e94adf Some more JSON property examples + minified version.
Zef Hemel authored
172 name: "TEXT",
173 metaData: "JSON"
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
174 });
175
176 var Tag = persistence.define('Task', {
177 name: "TEXT"
cd6c915 Simple prefetching works.
zef authored
178 });
179
14f8aac Working on the readme
Zef Hemel authored
180 The returned values are constructor functions and can be used to
181 create new instances of these entities later:
cd6c915 Simple prefetching works.
zef authored
182
183
14f8aac Working on the readme
Zef Hemel authored
184 Relationships between entities are defined using the constructor
185 function's `hasMany` call:
cd6c915 Simple prefetching works.
zef authored
186
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
187 // This defines a one-to-many relationship:
73724ff Added .add and .remove methods to QueryCollections.
zef authored
188 Category.hasMany('tasks', Task, 'category');
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
189 // These two definitions define a many-to-many relationship
190 Task.hasMany('tags', Tag, 'tasks');
191 Tag.hasMany('tasks', Task, 'tags');
cd6c915 Simple prefetching works.
zef authored
192
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
193 The first statement defines a `tasks` relationship on category objects
194 containing a `QueryCollection` (see the section on query collections
195 later) of `Task`s, it also defines an inverse relationship on `Task`
196 objects with the name `category`. The last two statements define a
197 many-to-many relationships between `Task` and `Tag`. `Task` gets a
198 `tags` property (a `QueryCollection`) containing all its tags and vice
199 versa, `Tag` gets a `tasks` property containing all of its tasks.
cd6c915 Simple prefetching works.
zef authored
200
14f8aac Working on the readme
Zef Hemel authored
201 The defined entity definitions are synchronized (activated) with the
202 database using a `persistence.schemaSync` call, which takes a callback
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
203 function (with a newly created transaction as an argument), that is called
14f8aac Working on the readme
Zef Hemel authored
204 when the schema synchronization has completed, the callback is
205 optional.
cd6c915 Simple prefetching works.
zef authored
206
207 persistence.schemaSync();
73724ff Added .add and .remove methods to QueryCollections.
zef authored
208 // or
14f8aac Working on the readme
Zef Hemel authored
209 persistence.schemaSync(function(tx) {
210 // tx is the transaction object of the transaction that was
211 // automatically started
212 });
cd6c915 Simple prefetching works.
zef authored
213
eae6f59 @fgrehm Finishing up documentation
fgrehm authored
214 There is also a migrations plugin you can check out, documentation can be found
58183c9 @fgrehm Fixing link to migrations documentation
fgrehm authored
215 in [persistence.migrations.docs.md](migrations/persistence.migrations.docs.md) file.
eae6f59 @fgrehm Finishing up documentation
fgrehm authored
216
71f97d7 first pass on mixins
Bruno Jouhier authored
217 Mix-ins
218 -------
219
220 You can also define mix-ins and apply them to entities of the model.
221
09d43e0 @zefhemel Documentation update
zefhemel authored
222 A mix-in definition is similar to an entity definition, except using
223 `defineMixin` rather than just `define`. For example:
71f97d7 first pass on mixins
Bruno Jouhier authored
224
b0353cb finished first pass on many to many support for mixins - basic tests pas...
Bruno Jouhier authored
225 var Annotatable = persistence.defineMixin('Annotatable', {
71f97d7 first pass on mixins
Bruno Jouhier authored
226 lastAnnotated: "DATE"
b0353cb finished first pass on many to many support for mixins - basic tests pas...
Bruno Jouhier authored
227 });
71f97d7 first pass on mixins
Bruno Jouhier authored
228
229 You can define relationships between mix-in and entities. For example:
230
231 // A normal entity
232 var Note = persistence.define('Note', {
233 text: "TEXT"
234 });
235
236 // relationship between a mix-in and a normal entity
237 Annotatable.hasMany('notes', Note, 'annotated');
238
239 Once you have defined a mix-in, you can apply it to any entity of your model,
240 with the `Entity.is(mixin)` method. For example:
241
b1ca96e fixed typo in readme
Bruno Jouhier authored
242 Project.is(Annotatable);
243 Task.is(Annotatable);
71f97d7 first pass on mixins
Bruno Jouhier authored
244
245 Now, your `Project` and `Task` entities have an additional `lastAnnotated` property.
246 They also have a one to many relationship called `notes` to the `Note` entity.
b0353cb finished first pass on many to many support for mixins - basic tests pas...
Bruno Jouhier authored
247 And you can also traverse the reverse relationship from a `Note` to its `annotated` object.
71f97d7 first pass on mixins
Bruno Jouhier authored
248
249 Note that `annotated` is a polymorphic relationship as it may yield either a `Project`
250 or a `Task` (or any other entity which is `Annotatable').
de89d62 documented the fact that prefetch is not allowed on mixins
Bruno Jouhier authored
251
b0353cb finished first pass on many to many support for mixins - basic tests pas...
Bruno Jouhier authored
252 Note: Prefetch is not allowed (yet) on a relationship that targets a mixin. In the example above
de89d62 documented the fact that prefetch is not allowed on mixins
Bruno Jouhier authored
253 you cannot prefetch the `annotated` relationship when querying the `Note` entity.
71f97d7 first pass on mixins
Bruno Jouhier authored
254
255 Notes: this feature is very experimental at this stage. It needs more testing.
8db0de9 @zefhemel Doc typo fix
zefhemel authored
256 Support for "is a" relationships (classical inheritance) is also in the works.
71f97d7 first pass on mixins
Bruno Jouhier authored
257
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
258 Creating and manipulating objects
259 ---------------------------------
260
261 New objects can be instantiated with the constructor functions.
262 Optionally, an object with initial property values can be passed as
263 well, or the properties may be set later:
264
265 var task = new Task();
266 var category = new Category({name: "My category"});
1e94adf Some more JSON property examples + minified version.
Zef Hemel authored
267 category.metaData = {rating: 5};
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
268 var tag = new Tag();
269 tag.name = "work";
270
271 Many-to-one relationships are accessed using their specified name, e.g.:
272 task.category = category;
273
274 One-to-many and many-to-many relationships are access and manipulated
275 through the `QueryCollection` API that will be discussed later:
276
277 task.tags.add(tag);
278 tasks.tags.remove(tag)l
279 tasks.tags.list(tx, function(allTags) { console.log(allTags); });
280
4941cd3 Added support for object removal (via `persistence.remove`).
Zef Hemel authored
281 Persisting/removing objects
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
282 ---------------------------
cd6c915 Simple prefetching works.
zef authored
283
14f8aac Working on the readme
Zef Hemel authored
284 Similar to [hibernate](http://www.hibernate.org), `persistence.js`
285 uses a tracking mechanism to determine which objects' changes have to
286 be persisted to the datase. All objects retrieved from the database
287 are automatically tracked for changes. New entities can be tracked to
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
288 be persisted using the `persistence.add` function:
cd6c915 Simple prefetching works.
zef authored
289
c37c40d Formatted readme slightly
Zef Hemel authored
290 var c = new Category({name: "Main category"});
291 persistence.add(c);
292 for ( var i = 0; i < 5; i++) {
293 var t = new Task();
294 t.name = 'Task ' + i;
295 t.done = i % 2 == 0;
296 t.category = c;
297 persistence.add(t);
298 }
cd6c915 Simple prefetching works.
zef authored
299
4941cd3 Added support for object removal (via `persistence.remove`).
Zef Hemel authored
300 Objects can also be removed from the database:
301
302 persistence.remove(c);
303
14f8aac Working on the readme
Zef Hemel authored
304 All changes made to tracked objects can be flushed to the database by
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
305 using `persistence.flush`, which takes a transaction object and
306 callback function as arguments. A new transaction can be started using
e38fbe0 Got rid of redundancy in readme.
Zef Hemel authored
307 `persistence.transaction`:
cd6c915 Simple prefetching works.
zef authored
308
309 persistence.transaction(function(tx) {
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
310 persistence.flush(tx, function() {
311 alert('Done flushing!');
312 });
313 });
14f8aac Working on the readme
Zef Hemel authored
314
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
315 For convenience, it is also possible to not specify a transaction or
316 callback, in that case a new transaction will be started
317 automatically. For instance:
14f8aac Working on the readme
Zef Hemel authored
318
319 persistence.flush();
320 // or, with callback
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
321 persistence.flush(function() {
14f8aac Working on the readme
Zef Hemel authored
322 alert('Done flushing');
323 });
324
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
325 Note that when no callback is defined, the flushing still happens
326 asynchronously.
14f8aac Working on the readme
Zef Hemel authored
327
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
328 __Important__: Changes and new objects will not be persisted until you
329 explicitly call `persistence.flush()`. The exception to this rule is
e38fbe0 Got rid of redundancy in readme.
Zef Hemel authored
330 using the `list(...)` method on a database `QueryCollection`, which also
331 flushes first, although this behavior may change in the future.
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
332
d61084e persistence.sync.js now keeps track of changes to all entities in
Zef Hemel authored
333 Dumping and restoring data
792501e @zefhemel Working on selectJSON, refactoring some code.
zefhemel authored
334 --------------------------
335
336 The library supports two kinds of dumping and restoring data.
ef3606a A simple database dump function. Restore will come soon.
Zef Hemel authored
337
338 `persistence.dump` can be used to create an object containing a full
339 dump of a database. Naturally, it is adviced to only do this with
340 smaller databases. Example:
341
342 persistence.dump(tx, [Task, Category], function(dump) {
343 console.log(dump);
344 });
345
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
346 The `tx` is left out, a new transaction will be started for the
347 operation. If the second argument is left out, `dump` defaults
348 to dumping _all_ defined entities.
ef3606a A simple database dump function. Restore will come soon.
Zef Hemel authored
349
350 The dump format is:
351
352 {"entity-name": [list of instances],
353 ...}
354
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
355 `persistence.load` is used to restore the dump produced by
356 `persistence.dump`. Usage:
357
358 persistence.load(tx, dumpObj, function() {
359 alert('Dump restored!');
360 });
361
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
362 The `tx` argument can be left out to automatically start a new
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
363 transaction. Note that `persistence.load` does not empty the database
364 first, it simply attempts to add all objects to the database. If
365 objects with, e.g. the same ID already exist, this will fail.
ef3606a A simple database dump function. Restore will come soon.
Zef Hemel authored
366
d61084e persistence.sync.js now keeps track of changes to all entities in
Zef Hemel authored
367 Similarly, `persistence.loadFromJson` and `persistence.dumpToJson`
368 respectively load and dump all the database's data as JSON strings.
369
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
370 Entity constructor functions
371 ----------------------------
372
373 The constructor function returned by a `persistence.define` call
374 cannot only be used to instantiate new objects, it also has some
375 useful methods of its own:
376
377 * `EntityName.all([session])` returns a query collection containing
378 all
379 persisted instances of that object. The `session` argument is
380 optional and only required when `persistence.js` is used in
381 multi-session mode.
382 * `EntityName.load([session], [tx], id, callback)` loads an particular
383 object from the database by id or returns `null` if it has not been
384 found.
385 * `EntityName.findBy([session], [tx], property, value, callback)` searches
386 for a particular object based on a property value (this is assumed to
387 be unique), the callback function is called with the found object or
388 `null` if it has not been found.
389
390 And of course the methods to define relationships to other entities:
391
392 * `EntityName.hasMany(property, Entity, inverseProperty)` defines a
393 1:N or N:M relationship (depending on the inverse property)
394 * `EntityName.hasOne(property, Entity)` defines a 1:1 or N:1
395 relationship
396
d714e0d @zefhemel Added `selectJSON` method to entity objects, see README.md for
zefhemel authored
397
398 Entity objects
399 --------------
400
401 Entity instances also have a few predefined properties and methods you
402 should be aware of:
403
404 * `obj.id`, contains the identifier of your entity, this is a
405 automatically generated (approximation of a) UUID. You should
406 never write to this property.
407 * `obj.fetch(prop, callback)`, if an object has a `hasOne`
408 relationship to another which has not yet been fetched from the
409 database (e.g. when `prefetch` wasn't used), you can fetch in manually
410 using `fetch`. When the property object is retrieved the callback function
411 is invoked with the result, the result is also cached in the entity
412 object itself.
413 * `obj.selectJSON([tx], propertySpec, callback)`, sometime you need to extract
4c18f83 @zefhemel Another README fix...
zefhemel authored
414 a subset of data from an entity. You for instance need to post a
415 JSON representation of your entity, but do not want to include all
416 properties. `selectJSON` allows you to do that. The `propertySpec`
417 arguments expects an array with property names. Some examples:
d714e0d @zefhemel Added `selectJSON` method to entity objects, see README.md for
zefhemel authored
418 * `['id', 'name']`, will return an object with the id and name property of this entity
419 * `['*']`, will return an object with all the properties of this entity, not recursive
420 * `['project.name']`, will return an object with a project property which has a name
11dedaf @zefhemel README fixes
zefhemel authored
421 property containing the project name (hasOne relationship)
d714e0d @zefhemel Added `selectJSON` method to entity objects, see README.md for
zefhemel authored
422 * `['project.[id, name]']`, will return an object with a project property which has an
11dedaf @zefhemel README fixes
zefhemel authored
423 id and name property containing the project name (hasOne relationship)
d714e0d @zefhemel Added `selectJSON` method to entity objects, see README.md for
zefhemel authored
424 * `['tags.name']`, will return an object with an array `tags` property containing
11dedaf @zefhemel README fixes
zefhemel authored
425 objects each with a single property: name
d714e0d @zefhemel Added `selectJSON` method to entity objects, see README.md for
zefhemel authored
426
427
14f8aac Working on the readme
Zef Hemel authored
428 Query collections
429 -----------------
430
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
431 A core concept of `persistence.js` is the `QueryCollection`. A
14f8aac Working on the readme
Zef Hemel authored
432 `QueryCollection` represents a (sometimes) virtual collection that can
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
433 be filtered, ordered or paginated. `QueryCollection`s are somewhate
434 inspired by [Google AppEngine's Query
435 class](http://code.google.com/appengine/docs/python/datastore/queryclass.html).
14f8aac Working on the readme
Zef Hemel authored
436 A `QueryCollection` has the following methods:
437
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
438 * `filter(property, operator, value)`
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
439 Returns a new `QueryCollection` that adds a filter, filtering a
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
440 certain property based on an operator and value. Supported operators
80824fe @zefhemel Introduced bug fixes, and new 'not in' operator.
zefhemel authored
441 are '=', '!=', '<', '<=', '>', '>=', 'in' and 'not in'. Example:
442 `.filter('done', '=', true)`
3843c74 @zefhemel Added or filters, usage (example in test/test.persistence.js):
zefhemel authored
443 * `or(filter)`
444 Returns a new `QueryCollection` that contains items either matching
445 the filters specified before calling `or`, or the filter represented
446 in the argument. The `filter` argument is of a `Filter` type, there
447 are three types of filters:
448 - `persistence.PropertyFilter`, which filters on properties (internally called when `filter(...)` is used.
449 Example: `new persistence.PropertyFilter('done', '=', true)`
450 - `persistence.AndFilter`, which is passed two filter objects as arguments, both of which should be true.
451 Example: `new persistence.AndFilter(new persistence.PropertyFilter('done', '=', true), new persistence.PropertyFilter('archived', '=', true))`
452 - `persistence.OrFilter`, which is passed two filter objects as arguments, one of which should be true.
453 Example: `new persistence.OrFilter(new persistence.PropertyFilter('done', '=', true), new persistence.PropertyFilter('archived', '=', true))`
454 * `and(filter)`
455 same as `or(filter)` except that both conditions should hold for items to be in the collection.
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
456 * `order(property, ascending)`
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
457 Returns a new `QueryCollection` that will order its results by the
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
458 property specified in either an ascending (ascending === true) or
459 descending (ascending === false) order.
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
460 * `limit(n)`
461 Returns a new `QueryCollection` that limits the size of the result
462 set to `n` items. Useful for pagination.
463 * `skip(n)`
464 Returns a new `QueryCollection` that skips the first `n` results.
465 Useful for pagination.
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
466 * `prefetch(rel)`
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
467 Returns a new `QueryCollection` that prefetches entities linked
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
468 through relationship `rel`, note that this only works for one-to-one
469 and many-to-one relationships.
a9fa189 @zefhemel Added `count` call to query collections. Fixed a little bug in
zefhemel authored
470 * `add(obj)`
471 Adds object `obj` to the collection.
472 * `remove(obj)`
473 Removes object `obj` from the collection.
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
474 * `list([tx], callback)`
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
475 Asynchronously fetches the results matching the formulated query.
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
476 Once retrieved, the callback function is invoked with an array of
477 entity objects as argument.
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
478 * `each([tx], eachCallback)`
9520607 Basic implementation of LocalQueryCollection, only supports filtering
Zef Hemel authored
479 Asynchronously fetches the results matching the formulated query.
480 Once retrieved, the `eachCallback` function is invoked on each
481 element of the result objects.
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
482 * `forEach([tx], eachCallback)`
483 Alias for `each`
484 * `one([tx], callback)`
a2c07b5 @zefhemel Added `destroyAll` method to DbQueryCollections to remove all the items
zefhemel authored
485 Asynchronously fetches the first element of the collection, or `null` if none.
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
486 * `destroyAll([tx], callback)`
a2c07b5 @zefhemel Added `destroyAll` method to DbQueryCollections to remove all the items
zefhemel authored
487 Asynchronously removes all the items in the collection. __Important__: this does
488 not only remove the items from the collection, but removes the items themselves!
e2d2c10 @zefhemel IMPORTANT: Minor breaking changes!
zefhemel authored
489 * `count([tx], callback)`
a9fa189 @zefhemel Added `count` call to query collections. Fixed a little bug in
zefhemel authored
490 Asynchronously counts the number of items in the collection. The arguments passed
491 to the `callback` function is the number of items.
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
492
493 Query collections are returned by:
494
495 * `EntityName.all()`, e.g. `Task.all()`
496 * one-to-many and many-to-many relationships, e.g. `task.tags`
497
498 Example:
cd6c915 Simple prefetching works.
zef authored
499
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
500 var allTasks = Task.all().filter("done", '=', true).prefetch("category").order("name", false).limit(10);
cd6c915 Simple prefetching works.
zef authored
501
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
502 allTasks.list(null, function (results) {
503 results.forEach(function (r) {
504 console.log(r.name)
505 window.task = r;
cd6c915 Simple prefetching works.
zef authored
506 });
507 });
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
508
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
509 Using persistence.js on the server
510 ==================================
511
dd1c7c4 @zefhemel Set-up library to be used a node library installable via npm. In fact,
zefhemel authored
512 Installing `persistence.js` on node is easy using [npm](http://npmjs.org):
513
514 npm install persistencejs
515
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
516 Sadly the node.js server environment requires slight changes to
517 `persistence.js` to make it work with multiple database connections:
518
519 * A `Session` object needs to be passed as an extra argument to
520 certain method calls, typically as a first argument.
521 * Methods previously called on the `persistence` object itself are now
522 called on the `Session` object.
523
524 An example `node.js` application is included in `test/node-blog.js`.
525
526 Setup
527 -----
528 You need to `require` two modules, the `persistence.js` library itself
dd1c7c4 @zefhemel Set-up library to be used a node library installable via npm. In fact,
zefhemel authored
529 and the MySQL backend module.
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
530
dd1c7c4 @zefhemel Set-up library to be used a node library installable via npm. In fact,
zefhemel authored
531 var persistence = require('persistencejs/persistence').persistence;
532 var persistenceStore = require('persistencejs/persistence.store.mysql');
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
533
534 Then, you configure the database settings to use:
535
8d922e1 @zefhemel Added port argument to documentation as well
zefhemel authored
536 persistenceStore.config(persistence, 'localhost', 3306, 'dbname', 'username', 'password');
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
537
538 Subsequently, for every connection you handle (assuming you're
539 building a sever), you call the `persistenceStore.getSession()`
540 method:
541
542 var session = persistenceBackend.getSession();
543
544 This session is what you pass around, typically together with a
545 transaction object. Note that currently you can only have one
546 transaction open per session and transactions cannot be nested.
547
548 session.transaction(function(tx) {
549 ...
550 });
551
96f2a57 documented commit/rollback feature
Bruno Jouhier authored
552 Commit and Rollback
553 -------------------
554
555 `persistence.js` works in autocommit mode by default.
556
557 You can override this behavior and enable explicit commit and rollback
558 by passing true as first argument to `persistence.transaction`.
559 You can then use the following two methods to control the transaction:
560
561 * `transaction.commit(session, callback)` commits the changes.
562 * `transaction.rollback(session, callback)` rollbacks the changes.
563
564 Typical code will look like:
565
566 session.transaction(true, function(tx) {
567 // create/update/delete objects
568 modifyThings(session, tx, function(err, result) {
569 if (err) {
570 // something went wrong
571 tx.rollback(session, function() {
572 console.log('changes have been rolled back: ' + ex.message);
573 });
574 }
575 else {
576 // success
577 tx.commit(session, function() {
578 console.log('changes have been committed: ' result);
579 });
580 });
581 });
582
583 Explicit commit and rollback is only supported on MySQL (server side)
584 for now.
585
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
586 Defining your data model
587 ------------------------
588
589 Defining your data model is done in exactly the same way as regular `persistence.js`:
590
591 var Task = persistence.define('Task', {
592 name: "TEXT",
593 description: "TEXT",
594 done: "BOOL"
595 });
596
597 A `schemaSync` is typically performed as follows:
598
599 session.schemaSync(tx, function() {
600 ...
601 });
602
603 Creating and manipulating objects
604 ---------------------------------
605
606 Creating and manipulating objects is done much the same way as with
607 regular `persistence.js`, except that in the entity's constructor you
608 need to reference the `Session` again:
609
610 var t = new Task(session);
611 ...
612 session.add(t);
613
614 session.flush(tx, function() {
615 ...
616 });
617
618 Query collections
b07a858 Moved issues to the issue tracker.
Zef Hemel authored
619 -----------------
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
620
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
621 Query collections work the same way as in regular `persistence.js`
622 with the exception of the `Entity.all()` method that now also requires
623 a `Session` to be passed to it:
624
625 Task.all(session).filter('done', '=', true).list(tx, function(tasks) {
626 ...
627 });
628
629 Closing the session
630 -------------------
631
632 After usage, you need to close your session:
633
634 session.close();
635
636 Bugs and Contributions
637 ======================
638
127d79b Rewrote parts of readme. Added documentation for supported property
Zef Hemel authored
639 If you find a bug, please [report it](http://yellowgrass.org/project/persistence.js).
c65213f Added Fabio's Date type to documentation.
Zef Hemel authored
640 or fork the project, fix the problem and send me a pull request. For
b07a858 Moved issues to the issue tracker.
Zef Hemel authored
641 a list of planned features and open issues, have a look at the [issue
b5cd840 Changed location of issue tracker.
Zef Hemel authored
642 tracker](http://yellowgrass.org/project/persistence.js).
033f67a Added .limit(n) and .skip(n) support.
Zef Hemel authored
643
0302c86 Added link to Google Group
Zef Hemel authored
644 For support and discussion, please join the [persistence.js Google
645 Group](http://groups.google.com/group/persistencejs).
646
0e32d43 @zefhemel Added AUTHORS file
zefhemel authored
647 Thanks goes to the people listed in `AUTHORS` for their contributions.
c65213f Added Fabio's Date type to documentation.
Zef Hemel authored
648
cda1de2 @zefhemel Added link to the persistence.js GWT wrapper.
zefhemel authored
649 If you use [GWT](http://code.google.com/webtoolkit/) (the Google Web
650 Toolkit), be sure to have a look at [Dennis Z. Jiang's GWT persistence.js
651 wrapper](http://github.com/dennisjzh/gwt-persistence).
652
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
653 License
4537c59 @zefhemel Rewrite and fixes to the README
zefhemel authored
654 =======
90ea29b Extended README + license. Preparing for initial release.
Zef Hemel authored
655
656 This work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
cb16171 Added flattr link
Zef Hemel authored
657
658 Support this work
3d5d3f0 @zefhemel Fixes to node blogging example, and description of plug-ins added to
zefhemel authored
659 -----------------
cb16171 Added flattr link
Zef Hemel authored
660
661 You can support this project by flattering it:
662
663 <a href="http://flattr.com/thing/2510/persistence-js" target="_blank">
664 <img src="http://api.flattr.com/button/button-static-50x60.png" title="Flattr this" border="0" /></a>
Something went wrong with that request. Please try again.