The Sequelize library provides easy access to a MySQL database by mapping database entries to objects and vice versa. To put it in a nutshell... it's an ORM (Object-Relational-Mapper). The library is written entirely in JavaScript and can be used in the Node.JS environment.
The Sequelize library provides easy access to a MySQL database by mapping database entries to objects and vice versa. To put it in a nutshell... it's an ORM (Object-Relational-Mapper). The library is written entirely in JavaScript and can be used in the Node.JS environment.
## Installation ##
## Features ##
Sequelize will have a Kiwi package in future. For now, you can install it via NPM or just download the code from the git repository and require _sequelize.js_:
- Schema definition
- Schema synchronization/dropping
- Easy definition of class/instance methods
- Instance saving/updating/dropping
- Asynchronous library
- Associations
- Importing definitions from single files
# npm:
## Documentation, Examples and Updates ##
npm install sequelize
var Sequelize = require("sequelize").Sequelize
# checkout:
You can find the documentation and announcements of updates on the [project's website](http://www.sequelizejs.com).
cd <path/to/lib>
If you want to know about latest development and releases, follow me on [Twitter](http://twitter.com/sdepold).
git clone git://github.com/sdepold/sequelize.git
Also make sure to take a look at the examples in the repository. The website will contain them soon, as well.
var Sequelize = require(__dirname + "/lib/sequelize/lib/sequelize/Sequelize").Sequelize
\ No newline at end of file
This will make the class Sequelize available.
## Basic Mapping ##
To get the ball rollin' you first have to create an instance of _Sequelize_. Use it the following way:
var sequelize = new Sequelize('database', 'username', 'password')
This will save the passed database credentials and provide all further methods.
To define mappings between a class (_Stop telling me that JavaScript don't know classes. Name it however you want to!_) and a table use the _define_ method:
var Project = sequelize.define('Project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
var Task = sequelize.define('Task', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
deadline: Sequelize.DATE
})
Sequelize currently supports the following datatypes:
Sequelize.STRING ===> VARCHAR(255)
Sequelize.TEXT ===> TEXT
Sequelize.INTEGER ===> INT
Sequelize.DATE ===> DATETIME
Sequelize.BOOLEAN ===> TINYINT(1)
You can also store your model definitions in a single file using the _import_ method:
// app.js
var Project = sequelize.import(__dirname + "/path/to/models/Project").Project
Choose the name of the exported function the way you want. It doesn't matter at all. You can also specify multiple models in one file. The _import_ method will return a hash, which stores the result of _sequelize.define_ under the key _Project_.
## Creation and deletion of class tables ##
As you are able to specify an objects _skeleton_, the next step is to push it to a database:
// create my nice tables:
Project.sync(callback)
Task.sync(callback)
// drop the tables:
Project.drop(callback)
Task.drop(callback)
// with error handling:
Project.[sync|drop](function(table, error) {
if(error) // oooh, did you entered wrong database credentials?
else // ok ... everything is nice!
})
Because synchronizing and dropping all of your tables might be a lot of line to write, you can also let Sequelize do the work for you:
// create all tables... now!
sequelize.sync(callback)
// and drop it!
sequelize.drop(callback)
// with error handling:
sequelize.[sync|drop](function(errors) {
if(errors.length > 0) // whooops
else // woot woot
})
## Creating and working with instances ##
In order to create instances of defined classes just do it as follows:
var project = new Project({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
})
var task = new Task({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
})
To save it in the database use the _save_ method and pass a callback to it, if needed:
project.save(function() {
// my nice callback stuff
})
task.save(function() {
// some other stuff
})
new Task({ title: 'foo', description: 'bar', deadline: new Date()}).save(function(anotherTask) {
// you can now access the currently saved task with the variable _anotherTask_... nice!
})
Now lets change some values and save changes to the database... There are two ways to do that:
// way 1
task.title = 'a very different title now'
task.save(function(){})
// way 2
task.updateAttributes({
title: 'a very different title now'
}, function(){})
## Expanding models ##
Sequelize allows you to pass custom class and instance methods. Just do the following:
var Foo = sequelize.define('Foo', { /* attributes */}, {
classMethods: {
method1: function(){ return 'smth' }
},
instanceMethods: {
method2: function() { return 'foo' }
}
})
// ==>
Foo.method1()
new Foo({}).method2()
## Chain queries ##
Because you will want to save several items at once and just go on after all of them are saved, Sequelize provides a handy helper for that:
Sequelize.chainQueries([
// push your items + method calls here
], function() {
// and here do some callback stuff
})
And a real example:
Sequelize.chainQueries([
{save: project}, {save: task}
], function() {
// woot! saved.
})
You can also pass params to the method... and of course you can also call other methods with a callback:
Sequelize.chainQueries([
{ methodWithParams: project, params: [1,2,3] }
], function() {
// the method call will equal: project.methodWithParams(1,2,3, callback)
})
## Associations ##
With Sequelize you can also specify associations between multiple classes. Doing so will help you to easily access and set those associated objects. The library therefore provides for each defined class the method _belongsTo_, _hasOne_ and _hasMany_:
Project.hasMany("tasks", Task)
Task.belongsTo("project", Project)
Because Sequelize is doing a lot of magic, you have to call Sequelize#sync *after* setting the associations! Doing so will allows you the following:
For hasOne its basically the same as with belongsTo:
Task.hasOne('author', Author)
Task.setAuthor(anAuthor)
In order to specify many-to-many associations you can use the following syntax:
Project.hasMany('members', Member)
Member.hasMany('projects', Project)
This will create a table named according to the table names of Project and Member (= ProjectsMembers) which just stores the id of a project and a member. Don't forget to call the sync method of the sequelize instance.
## Finding some objects ##
OK... you can define classes and associations. You can save them. You would probably like to get them from the database again :) Easy:
Project.find(123, function(project) {
// project will be an instance of Project and stores the content of the table entry with id 123
// if such an entry is not defined you will get null