Javascript - Intermediate
Notions of databases
Notions of Node.js
SELECT * FROM Users WHERE id = 4
user = Users.find(4);
Entirely written in JavaScript
Can be used with Node.js
$ npm install sequelize
$ npm install mysql
var Sequelize = require("sequelize");
var sequelize = new Sequelize('db', 'username'[, 'password'] [,'options']);
// You can also specify a non-default host/port
var sequelize = new Sequelize('database', 'username', 'password', {
host: "my.server",
port: 12345
});
var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname'[, 'options']);
var Book = sequelize.define('Book', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
publication: Sequelize.DATE
});
// Allow null, default value
flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true}
// Unique values
someUnique: {type: Sequelize.STRING, unique: true}
// Primary Key
id: { type: Sequelize.INTEGER, primaryKey: true}
// autoIncrement
increment: { type: Sequelize.INTEGER, autoIncrement: true }
// comments - only for MySQL and PG
hasComment: { type: Sequelize.INTEGER, comment: "Comment!" }
Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT
Sequelize.INTEGER // INTEGER
Sequelize.BIGINT(11) // BIGINT(11)
Sequelize.FLOAT(11, 12) // FLOAT(11,12)
Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)
Sequelize.DATE // DATETIME for mysql/sqlite; TIMESTAMP
// WTZ Postgres
Sequelize.BOOLEAN // TINYINT(1)
Sequelize.ENUM('value 1', 'value 2') // ENUM
Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only
Sequelize.BLOB('tiny') // Other options are medium and long
Sequelize.UUID // UUID for PostgreSQL and SQLite,
// CHAR(36) BINARY for MySQL
var Book = sequelize.define('Book', {
title: {
type : Sequelize.STRING,
get : function() {
return "Book title"
},
set : function(value) { /*...*/}
}
});
var Book = sequelize.define('Book', {
title:Sequelize.STRING
}
},
{
getterMethods : {
title : function() {/* Return a value */}
},
setterMethods : {
title : function(v) { /*...*/ }
}
});
Helpers
function() {
return this.getDataValue('title');
}
function(title) {
return this.setDataValue('title', title.toString().toLowerCase());
}
var Book= sequelize.define('Book', {
title: {
type: Sequelize.STRING,
validate: {
isAlphanumeric: true,
notEmpty: true
}
}
});
var Contact = Sequelize.define('Contact', {
name: { type: Sequelize.STRING },
address1: { type: Sequelize.STRING },
address2: { type: Sequelize.STRING },
,
}, {
validate: {
atLeastOneAddress: function() {
if ((this.address1 === "") && (this.address2 === "")) {
throw new Error('Require at least one address');
}
}
}
})
is: /^[a-z]+$/i, // RegExp
not: ["[a-z]",'i'], // will not allow letters
isEmail: true, // checks for email format (foo@bar.com)
isUrl: true, // checks for url format (http://foo.com)
isAlpha: true, // will only allow letters
isNumeric: true // will only allow numbers
isInt: true, // checks for valid integers
isFloat: true, // checks for valid floating point numbers
isNull: true, // only allows null
len: [2,10], // allow values with length between 2 and 10
isDate: true, // only allow date strings
isAfter: "2011-11-05", // allow date strings after a specific date
isBefore: "2011-11-05", // allow date strings before a specific date
max: 23, // only allow values <= 23
min: 23, // only allow values >= 23
isCreditCard: true, // check for valid credit card numbers
isEven: function(value) {
if(parseInt(value) % 2 != 0) {
throw new Error('Only even values are allowed!')
}
}
isInt: {
msg: "Must be an integer number of pennies"
}
// search for a known id
Project.find(123).success(function(project) {});
// search for attributes
Project.find({ where: {title: 'aProject'} }).success(function(project) {});
// only select some attributes and rename one
Project.find({
where: {title: 'aProject'},
attributes: ['id', ['name', 'title']]
}).success(function(project) {});
User.findOrCreate(
{ username: 'tbonfim' },
{ fullname: 'Thiago Bonfim' })
.success(function(user, created) {});
Project.findAndCountAll({
where: ["title LIKE 'NodeJS%'"]
})
.success(function(result) {
/* result.count and result.rows */
});
Project.findAll().success(function(projects) {
// returns all instances of projects
});
// Using where
Project.findAll({
where: {
id: {
gt: 6, // id > 6 gte: 6 // id >= 6
lt: 1, // id < 1 lte: 1, // id <= 1
ne: 20, // id != 20
between: [6, 10], // BETWEEN 6 AND 10
nbetween: [11, 15] // NOT BETWEEN 11 AND 15
}
}
});
Project.count([where]).success(function(c) {});
Project.max('Column', [where]).success(function(max) {});
Project.min('Column', [where]).success(function(min) {});
Project.sum('Column', [where]).success(function(sum) {});
var Task = sequelize.define('Project', {
title: Sequelize.STRING,
rating: { type: Sequelize.STRING, defaultValue: 3 }
});
var task = Task.build({title: 'very important task'});
Task.create({
title: 'Task 1',
description: 'A hard task',
deadline: new Date() })
.success(function(task) {});
User.create({ username:'tbonfim', isAdmin:true}, [ 'username' ]) .success(function(user) { // only the attribute 'username' will be set});
task.title = 'Another title';
task.save().success(function() {});
task.title = 'Another title';
task.description = 'Very easy task';
task.save(['title']).success(function() {
// will only save title
});
task.updateAttributes({
title: 'Another title'
}, [<attributes to save>]).success(function() {});
task.destroy().success(function() { });
Task.destroy({ subject: 'programming'})
.success(function(affectedRows){});
Task.bulkCreate([
{subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'}
]).success(function() {});
Task.update(
{status: 'inactive'}, // set status = 'inactive'
{subject: 'programming'} // where subject = 'programming'
).success(function(affectedRows) {});
var User = sequelize.define('User', {/* ... */});
var Project = sequelize.define('Project', {/* ... */});
// One-way associations, from Project to User
Project.hasOne(User);
// To get the association working from User to Project, we need to do this:
User.belongsTo(Project);
var User = sequelize.define('User', {/* ... */});
var Project = sequelize.define('Project', {/* ... */});
Project.hasMany(User, {as: 'Workers'});
Project.hasMany(User, { as: 'Workers' });
User.hasMany(Project);
Project.hasMany(User, {through: 'project_has_users'});
User.hasMany(Project, {through: 'project_has_users'});
UserProjects = sequelize.define('UserProjects', {status: DataTypes.STRING});
User.hasMany(Project, { through: UserProjects });
Project.hasMany(User, { through: UserProjects });
// many associations project.getTasks().success(function(associatedTasks) {}); project.setTasks(tasks).success(function(associatedTasks) {});
// one associations project.getTask().success(function(associatedTasks) {}); project.setTask(task).success(function(associatedTasks) {}); // add/ remove project.removeTask(task).success(function() {}); project.addTask(task).success(function() {}); // checking associations project.hasUser(u).success(function(result){// result will be true or false});
beforeBulkCreate(daos, fields, fn)/ afterBulkCreate(daos, fields, fn)
beforeBulkDestroy(daos, fields, fn)/ afterBulkDestory(daos, fields, fn)
beforeBulkUpdate(daos, fields, fn)/ afterBulkUpdate(daos, fields, fn)
beforeCreate(dao, fn)/ afterCreate(dao, fn)
beforeDestroy(dao, fn)/ afterDestroy(dao, fn)
beforeUpdate(dao, fn)/ afterUpdate(dao, fn)
beforeValidate(dao, fn)/afterValidate(dao, fn)
var User = sequelize.define('User', { username: DataTypes.STRING }, {
hooks: { beforeValidate: function(user, fn) { /* fn(null, user); */ } } }); // another way to add a hook User.hook('beforeValidate', function(user, fn) { /* fn(null, user); */ });
sequelize.query('query', [, model], [, options], [, replacements])
.success(function(rows) {});
Project.sync()
.success(function(){})
.error(function(error){});
Project.sync({force: true}); // drop the table if exists and then create
Project.drop();
// Instead of synchronizing all of your models, you can use Sequelize to just
// synchronize your database once:
sequelize.sync()
.success(function(){})
.error(function(error){});
sequelize.sync({force: true});
sequelize.drop();