Google Gears ORM v0.1

UPDATE:a new version is here.

So after more than a month since i released a proof of concept of a ORM for Google Gears,i am happy to release the first(official) version of GearsORM .

This is a complete rewrite of the code,this version support relations(both many to one and many to many with automatic table creation),easy loading and saving objects from JSON,real foreign keys(SQLite doesn`t support them) using triggers and many more stuff.

Since i am a big fan of examples i will try to show the new api by a example(the code is fully documented,but i still don`t have a official documentation).

for this example we will make a blog like system(Post,Comment and Tag models).
let define the models first:

var Post = new GearsORM.Model({
	name:"Post",
	fields:
	{
		title:new GearsORM.Fields.String({maxLength:256}),
		body:new GearsORM.Fields.String({maxLength:5000}),
		tags:new GearsORM.Fields.ManyToMany({related:"Tag"}),
		comments:new GearsORM.Fields.ManyToOne({
                                                 related:"Comment"})
	}
});
var Comment = new GearsORM.Model({
	name:"Comment",
	fields:
	{
		name:new GearsORM.Fields.String({maxLength:50}),
		email:new GearsORM.Fields.String({maxLength:75}),
		body:new GearsORM.Fields.String({maxLength:1000}),
		post:new GearsORM.Fields.OneToMany({
                     related:"Post",onDeleteCascade:true})
	}
});
var Tag = new GearsORM.Model({
	name:"Tag",
	fields:
	{
		name:new GearsORM.Fields.String({maxLength:25}),
		posts:new GearsORM.Fields.ManyToMany({related:"Post"})	
	}
});

now we have three models: Post,Comment and Tag.
a model have a function used to create the table for the model,if the table already exist nothing will happen.
so my recommendation is to put the calls to createTable right after models definition,like this:

Tag.createTable();
Post.createTable();
Comment.createTable();

This will insure that all the tables exist(but this doesn't insure that the table definition is correct,in case that the table already exist).
Now that we have everything configured(in terms of models and tables) we can start to insert some data.
For example to create a tag:

var testTag = new Tag();
testTag.name = "TestTag";
testTag.save();

This will create a new Tag object,set its name and save it to the database(this happen when you call the save method of the Tag instance).
there is a shorter way to create a instance and set its values,you do it like this:

var testTag = new Tag({name:"TestTag"}).save();

Now for relations:

var myTestPost = new Post({
  title:"my test post",
  body:"my test post body"
}).save();
myTestPost.tags.add(testTag);

This will create a new post and add a relation to testTag.
myTestPost.tags is a ManyToMany relation field,which have these methods:

  • add - create a relation between the object to other object(in our case between myTestPost and testTag)
  • remove - remove a relation between the object to other object
  • select - return a ResultIterator,can be filtered using a where expression like this: myTestPost.tags.select("Tag.name <> 'NotPublish'")

select anywhere in GearsORM return a ResultIterator which is a helper class to iterate over the results of a select.
ResultIterator define these methods:

  • next - return the next object in the ResultSet as a instance of the model,return false when there is no more objects,this close the ResultSet when there is no more objects(if you don`t finish iterate the ResultSet you should call close method.
  • close - close the ResultSet return false always.
  • each - like Ruby(or most of the JavaScript frameworks) each function,get a function which is called for each object in the ResultSet,also get a second optional object used to bind the function. this functions also auto close the ResultSet when it finish iterating it.
  • getOne - return the first object in the result set and close it.
  • toArray - return a array of the objects in the ResultSet and close it.

a model(in our example Post,Tag and Comment) define these methods:

  • select - preform a SELECT on the model,get a two optional parameters:whereExpression and params.
    whereExpression - is a SQL where clasue like "Post.title CONTAINS 'test'" or using bind parameters(recommended) "Post.title CONTAINS ?".
    params - a array of objects used as bind parameters.
  • remove - preform a DELETE on the model get the same parameters as select
  • createTable - create the table for the model,for example: Post.createTable()
  • dropTable - drop the table for the model,for example: Post.dropTable()
  • createTriggers - create the triggers for the model,for example: Post.createTriggers() this is called by createTable
  • dropTriggers - drop the triggers for the model,for example: Post.dropTriggers() this is called by dropTable
  • load - load objects(or one object) from a array to the database,if the second parameter is true the objects will be saved to the database,in both cases return array of model instances made from the objects

this is just a glimpse of the api,for more info go to GearsORM homepage(there is no documentation yet but stay tuned).
a simple demo here,packed version of the source here and trac view of code here

30 Comments

  1. Mark Holton Jul 16

    Very exciting to see this. Many thanks. Can I get the unpacked source? I love what you presented in your example, but this is something I'd really like to get familiarity with, and since there is no documentation up yet, it would be nice to be able to look at the unpacked source to see what additional methods, etc are there with your ORM.

  2. atesti Jul 16

    Hello Uriel. I'm interesting in your project, because I want to implement a brige between your ORM and GWT. Are you from Argentina?

  3. Uriel Katz Jul 16

    @mark:go to the project homepage(there is a link in the post) and there is a link to the source code(browser view of svn),i will expose the svn later on.
    @atesti:i am originally from Buenos Aires,Argentina,how did you know? :)
    anyways i will be in Argentina in about a week or two,contact me by email(contact tab in this page) and i will see how can i help you.

  4. Mark Holton Jul 16

    Many thanks, Uriel cheers, -Mark

  5. atesti Jul 16

    Yo también soy argentino :) Me dí cuenta por el blog que linkeaste porque tiene todas las noticias de la copa américa (mejor cambiemos de tema, jajaja) Te cuento que hace poco implementé un mapeador de JSON hacia Java para utilizar dentro de GWT ( te podés fijar acá http://code.google.com/p/gwt-jsonizer/ ), y actualmente estoy reimplementandolo por completo para dar soporte a las diferentes variantes de JSON. Con la nueva implementacion que estoy desarrollando, no me sería muy dificil crear una extensión para que trabaje en conjunto con tu ORM. Por ahora no decidí una fecha de release porque estoy lidiando con algunos conceptos clave, pero apenas lo tenga listo te voy a avisar. Básicamente, lo que tengo en mente es transformar automaticamente un objeto java en un objeto JSON y persistirlo con tu libreria. Te felicito por el trabajo que hiciste! ;)

  6. atesti Jul 16

    I'm sorry for the language. I'm not a good english speaker ;)

  7. John Jul 18

    Hello from Russia! Nice project! I try to use and found some bugs - look ticket at your trac: http://labs.urielkatz.com/report/1 Can you publish svn link on GearsORM trunc???

  8. Uriel Katz Jul 18

    i will publish it soon as i get the documentation done.
    thx for the bug report will be fixed soon.

  9. John Jul 18

    i was done function for creating of triggers after all tables and it be able to create triggers for m2m_ tables.

  10. Eric Abouaf Jul 23

    Hi ! Nice work. Except I just ran into the "for in" javascript issue (see http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ ), since I use json.js that extends Object.prototype with "toJSONString" function. To correct this, I just added "if( fields.hasOwnProperty(fieldName) ) {" ligne 18 of GearsORM.Sql.js This will require a code review, since it must appear quite a lot in the source code... Do you plan using setters and getters ? (http://ejohn.org/blog/javascript-getters-and-setters/) I'd like to have this feature so we can check if the object has local modifications before saving it. BTW: which javascript packer do you use ?

  11. Eric Abouaf Jul 23

    I patched the 3 files for the bug "for in" (see above), which you can find at : http://www.neyric.com/~neyric/GearsORM/ I didn't run the tests (yet...)

  12. Uriel Katz Jul 23

    nice work,but extending Object.prototype is a big no-no.

  13. Les Jul 23

    I still have my reservations about this (none to do with Google, but more to do with the cross cutting concerns between client and server) but I must say I'm impressed that you've used Python and django for your blog. Most people would have used Word Press; Not that there is anything wrong with PHP; It's just WP is pretty crap, isn't it... Some people even believe that they've got a full blown CMS using WP!! Ouch. Best regards,

  14. Uriel Katz Jul 23

    thx,about the blog it took time to get it to this stage,i also need to add alot of stuff but i really like having stuff that i wrote the code for,since it is way eaiser to customise it,this blog is 100% cached by memcached,so with a vps like mine i can get 600req/sec(tested with ab) which is pretty amazing :)

  15. Justin Meyer Aug 11

    Have you checked out TrimJunction? Steve yen has basically created JavaScript on Rails. He's also got it working with Gears. You might be able to work with him to get something amazing going.

  16. Uriel Katz Aug 11

    i saw TrimJunction only after i created GearsORM,even that Junction have a ORM i prefer to have a standalone ORM than a full blown MVC framework,but if the creator of TrimJunction want to work on a version togther i will be more than happy to merge them.

  17. Joey Novak Nov 27

    Awesome library. Thanks so much for releasing this. --Joey

  18. jackbo May 13

    Oilpaintingnow.com specializes in oil painting,original oil paintings,oil painting reproductions.Find thousands of hand-painted oil paintings on canvas and oil painting art reproductionsVisit Our Website

  19. carpinteyrodaq May 30

    I like www.urielkatz.com, i about i will loosely transpire b nautical tack turn tail from soon.

  20. Jackbo Jun 15

    Wholesale Coogi Jeans,Evisu Jeans,G-Star Jeans for men. Buy cheap mens Jeans with Free shipping from URclothing.com,the Mens Jeans is very fashion.http://www.urclothing.com.Visit Our Website

  21. UrawerSesE Oct 4

    Ocean Drive Luxury Hotel with On-Site SpaEnds at Midnight Tonight! $59: OCEAN DRIVE ALL-SUITE RESORT!October Rates From $79 | Book Early and Save! hotel . Don't know which hotel to book ? Click here for assistance! Ghana Hotels , Accra Hotels, Busua Hotels , Cape Coast Hotels with huge discount on market research,software,survey,online. Template Library Resort Hotel Survey, Survey includes customer satisfaction with the Front Desk, Guest Services,

  22. aim Oct 26

    The lesson is an object-relational mapper (ORM) for PHP, which is above a layer of abstraction powerful database (DBAL). It provides transparent persistence of objects PHP. Web Listings

  23. Web Listings Oct 26

    The lesson is an object-relational mapper (ORM) for PHP, which is above a layer of abstraction powerful database (DBAL). It provides transparent persistence of objects PHP.

  24. Calculette Pret Immobilier Oct 26

    Accra Hotels, Busua Hotels, Cape Coast Hotels huge discounts on market research, software, reports, on-line. Model Library Hotel Resort Survey Survey includes customer satisfaction Bank, Services,

  25. Calculette Pret Immobilier Oct 26

    Accra Hotels, Busua Hotels, Cape Coast Hotels huge discounts on market research, software, reports, on-line. Model Library Hotel Resort Survey Survey includes customer satisfaction Bank, Services,

  26. MeganStrandsWAE Nov 18

    100000 quality hotels , bed and breakfasts and rental accommodation. Book today, pay on departure. 22 Sep 2009 Inoqo is a new Twitter-based hotel booking engine that claims to provide a win-win solution for recession-hit hoteliers and travelers who The evening will start with drinks in the Tower Brasserie at 7.30pm followed by dinner in the hotel restaurant, ( chance to check out Cuisine and Service ) things get worse, in the morning Barbara & Jo are have a neck and shoulder massage, this will be after a Full English Breakfast .....of course.

  27. karmani Nov 24

    I am really impressed by this blog. I have always found it informative and updated karmani

  28. karmani Nov 24

    I am really impressed by this blog. I have always found it informative and updated karmani

  29. karmani Nov 24

    I am really impressed by this blog. I have always found it informative and updated karmani

  30. MaryTenderLOS Nov 28

    We have looked at the wonderful range of toys available this year and picked out what we believe are the top 10. Hip baby or girl shoes, depending on her age of course, will pull her outfit together in a stylish way. The discs slide easily into the magazine for loading and the magazine snaps firmly into place when inserted into active or storage openings.