0% found this document useful (0 votes)
74 views30 pages

ORMS Sequelize

This document provides an overview of Sequelize, a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It discusses how to install Sequelize, connect to a database, define models with data types, synchronize models to apply changes to the database, use logging, add timestamps to models, specify column options, work with model instances like creating, modifying and deleting them, perform queries with operators and finders.

Uploaded by

Victor Dario
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views30 pages

ORMS Sequelize

This document provides an overview of Sequelize, a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It discusses how to install Sequelize, connect to a database, define models with data types, synchronize models to apply changes to the database, use logging, add timestamps to models, specify column options, work with model instances like creating, modifying and deleting them, perform queries with operators and finders.

Uploaded by

Victor Dario
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

1

Parte 1

2
ORMs
Object-Relational Mapping

3
ORMs

4
Sequelize

"Promise-based Node.js ORM for Postgres, MySQL, MariaDB,


SQLite and Microsoft SQL Server"

La mayoría de los métodos son asíncronos por lo que devuelven promesas

Node v10+ 5
Sequelize
Installing

1 npm install --save sequelize


2 npm install --save pg pg-hstore # Postgres

Connecting

1 const { Sequelize } = require('sequelize');


2
3 // Opción 1: Connection URI
4 const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname')
5
6 // Opción 2: Parámetros separados
7 const sequelize = new Sequelize('database', 'username', 'password', {
8 host: 'localhost',
9 dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
10 });

6
Data Types

1 // TEXTO
2 DataTypes.STRING // VARCHAR(255)
3 DataTypes.STRING(1234) // VARCHAR(1234)
4 DataTypes.TEXT // TEXT
5
6 // NUMEROS
7 DataTypes.INTEGER // INTEGER
8 DataTypes.FLOAT // FLOAT
9
10 // FECHAS
11 DataTypes.DATE // TIMESTAMP WITH TIME ZONE
12 DataTypes.DATEONLY // DATE without time
13
14 // OTROS
15 DataTypes.ENUM('foo', 'bar') // An ENUM with allowed values 'foo' and 'bar'

Listado Completo

7
Model
De nition
Abstracción que representa una tabla de nuestra base de datos

1 const User = sequelize.define('User', {


2 firstName: {
3 type: DataTypes.STRING
4 },
5 lastName: {
6 type: DataTypes.STRING
7 }
8 }); 1 class User extends Model {}
2
3 User.init({
4 firstName: {
5 type: DataTypes.STRING
6 },
7 lastName: {
8 type: DataTypes.STRING
9 }
10 }, {
11 sequelize, // Connection instance
12 modelName: 'User' // Model name
13 });

User === sequelize.models.User


8
Model
Synchronization

De nir el modelo arma el esqueleto pero no aplica los cambios en la


base de datos, para eso debemos sincronizar los modelos

Model.sync(): crea la tabla si no existe o no hace nada si ya existe


Model.sync({force: true}): elimina (drop) la tabla y luego la vuelve a crear
Model.sync({alter: true}): aplica los cambios necesarios a la tabla actual para
que coincida con el modelo

1 // Un modelo a la vez
2 await Model.sync({ force: true });
3
4 // Todos los modelos juntos
5 await sequelize.sync({ force: true });

9
Sequelize
Logging

1 const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname', {


2 // Opciones:
3
4 // Default
5 logging: console.log,
6
7 // Muestra información adicional más allá de la Query SQL
8 logging: (...msg) => console.log(msg),
9
10 // Deshabilita el logging
11 logging: false,
12 });

10
Model
Automatic Timestamps

Se agregan automáticamente los campos createdAt y updatedAt que a


su vez se actualizan sólos al crear o modi car una instancia del modelo

1 sequelize.define('User', {
2 // ... (attributes)
3 }, {
4 timestamps: false 1 sequelize.define('User', {
5 }); 2 // ... (attributes)
3 }, {
4 timestamps: true,
5 createdAt: false,
6 updatedAt: 'actualizado'
7 });

11
Model
Column Options

1 class Foo extends Model {}


2 Foo.init({
3 flag: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
4 myDate: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
5 someUnique: { type: DataTypes.STRING, unique: true },
6
7 // Composite unique key.
8 uniqueOne: { type: DataTypes.STRING, unique: 'compositeIndex' },
9 uniqueTwo: { type: DataTypes.INTEGER, unique: 'compositeIndex' },
10
11
12 identifier: { type: DataTypes.STRING, primaryKey: true },
13 incrementMe: { type: DataTypes.INTEGER, autoIncrement: true },
14
15 });

12
Instances
Representa un objeto con la estructura de nida en el modelo que va a
mapearse con una la de la tabla asociada

1 const jane = User.build({ name: "Jane" });


2 await jane.save();

1 const jane = await User.create({ name: "Jane" });

13
Instances
Modi cations

1 const jane = await User.create({ name: "Jane" });


2 jane.name = "Ada";
3 await jane.save();

1 const jane = await User.create({ name: "Jane" });


2 await jane.destroy();

El método save esta optimizado para sólo actualizar los campos


que efectivamente fueron modi cados. Si se invoca sin ningún
cambio ni siquiera ejecutará una query

1 const jane = await User.create({ name: "Jane" });


2 console.log(jane); // Mal! (En principio para lo que queremos)
3 console.log(jane.toJSON()); // Bien!

14
Queries
SELECT

1 // SELECT * FROM ...


2 const instancias = await Model.findAll();
3
4 // SELECT foo, bar FROM ...
5 Model.findAll({
6 attributes: ['foo', 'bar']
7 });
8
9 // SELECT foo, bar as baz FROM ...
10 Model.findAll({
11 attributes: ['foo', ['bar', 'baz']]
12 });
13
14 // Exclude some attribute
15 Model.findAll({
16 attributes: { exclude: ['baz'] }
17 });

1 const instances = Model.findAll({


2 where: {
3 clothe: 'orange'
4 status: 'good'
5 }
6 });

15
Queries
Finders

1 const instance = await Model.findByPk(4); // null si no lo encuentra

1 const instance = await Model.findOne({


2 where: { name: 'Goku' }
3 }); // null si no lo encuentra

1 const [instance, created] = await Model.findOrCreate({


2 where: { name: 'Goku' },
3 defaults: {
4 gender: 'M',
5 race: 'Saiyan'
6 }
7 });

ndOrCreate busca si existe un registro según las condiciones de búsqueda y


si no encuentra ninguno procede a crear uno nuevo. Luego retorna la instancia
creada o encontrada y un booleano indicando cual de los dos caminos tomó
16
Parte 2

17
Queries
Operators

1 const { Op } = require("sequelize");
2 Model.findAll({
3 where: {
4 [Op.and]: [{ a: 5 }, { b: 6 }], // (a = 5) AND (b = 6)
5 [Op.or]: [{ a: 5 }, { b: 6 }], // (a = 5) OR (b = 6)
6 someAttribute: {
7 // Basics
8 [Op.eq]: 3, // = 3
9 [Op.ne]: 20, // != 20
10 [Op.is]: null, // IS NULL
11 [Op.not]: true, // IS NOT TRUE
12
13 // Number comparisons
14 [Op.gt]: 6, // > 6
15 [Op.lt]: 10, // < 10
16 [Op.between]: [6, 10], // BETWEEN 6 AND 10
17 [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
18
19 // Other operators
20 [Op.in]: [1, 2], // IN [1, 2]
21 [Op.notIn]: [1, 2], // NOT IN [1, 2]
22
23 ...
24 }
25 }
26 });
Listado Completo

18
Queries
UPDATE

1 // UPDATE table
2 // SET transformation = 'SS1'
3 // WHERE name = 'Goku'
4
5 await User.update({ transformation: 'SS1' }, {
6 where: {
7 name: 'Goku'
8 }
9 });

Actualizará todas las instancias que coincidan con la claúsula where


indicada. Si no se coloca ninguna condición actualizará todos los registros

19
Queries
DELETE

1 // DELETE FROM table


2 // WHERE race = 'Android'
3
4 await Model.destroy({
5 where: {
6 race: 'Android'
7 }
8 });
9
10 // Truncate
11 await Model.destroy({
12 truncate: true
13 });

Borrará todas las instancias que coincidan con la claúsula where indicada. Si
no se coloca ninguna condición borrará todos los registros

¿TRUNCATE = DESTROY? Truncate no acepta condiciones y elimina todos los


registros de una mientras que destroy va revisando registro a registro
20
Getters

1 const instance = sequelize.define('model', {


2 attribute: {
3 type: DataTypes.STRING,
4 get() {
5 const rawValue = this.getDataValue(attribute);
6 return rawValue ? rawValue.toUpperCase() : null;
7 }
8 }
9 });

Se llama de forma automática cuando se intenta acceder al atributo

El valor NO se va a modi car en la base de datos

this.attribute generaría un loop in nito (Si accedemos a otro attributo que


no sea donde estamos de niendo el getter funcionaria ok el this)

21
Setters

1 const User = sequelize.define('user', {


2 password: {
3 type: DataTypes.STRING,
4 set(value) {
5 this.setDataValue('password', hash(this.username + value));
6 }
7 }
8 });

Se llama de forma automática previo al almacenamiento de los


datos en la base de datos

22
Virtual Fields

1 const User = sequelize.define('user', {


2 firstName: DataTypes.TEXT,
3 lastName: DataTypes.TEXT,
4 fullName: {
5 type: DataTypes.VIRTUAL,
6 get() {
7 return `${this.firstName} ${this.lastName}`;
8 },
9 set(value) {
10 throw new Error('Do not try to set the `fullName` value!');
11 }
12 }
13 });

El valor NO se va a guardar en la base de datos

23
Validators

1 sequelize.define('foo', {
2 bar: {
3 type: DataTypes.STRING,
4 validate: {
5 is: /^[a-z]+$/i,
6 isEmail: true,
7 isUrl: true,
8 isAlpha: true,
9 isAlphanumeric: true,
10 isNumeric: true,
11 isLowercase: true,
12 notNull: true,
13 notEmpty: true,
14 equals: 'specific value',
15 contains: 'foo',
16 isIn: [['foo', 'bar']],
17 notContains: 'bar',
18 len: [2,10],
19 isAfter: "2011-11-05",
20 max: 23,
21
22 // Custom validators:
23 isEven(value) {
24 if (parseInt(value) % 2 !== 0) {
25 throw new Error('Only even values are allowed!');
26 }
27 }
28 }
29 }
30 });
Listado Completo
24
Associations

One-To-One 1 Foo.hasOne(Bar);
2 Bar.belongsTo(Foo);

One-To-Many 1 Team.hasMany(Player);
2 Player.belongsTo(Team);

Many-To-Many 1 Movie.belongsToMany(Actor, { through: 'ActorMovies' });


2 Actor.belongsToMany(Movie, { through: 'ActorMovies' });

25
Mixins

Foo.hasOne(Bar)
1 fooInstance.getBar()
2 fooInstance.setBar()
Foo.belongsTo(Bar) 3 fooInstance.createBar()

1 fooInstance.getBars()
2 fooInstance.countBars()
3 fooInstance.hasBar()
4 fooInstance.hasBars()
Foo.hasMany(Bar) 5
6
fooInstance.setBars()
fooInstance.addBar()
7 fooInstance.addBars()
8 fooInstance.removeBar()
9 fooInstance.removeBars()
10 fooInstance.createBar()

26
Mixins

Foo.belongsToMany(Bar, {through: Baz})

1 fooInstance.getBars()
2 fooInstance.countBars()
3 fooInstance.hasBar()
4 fooInstance.hasBars()
5 fooInstance.setBars()
6 fooInstance.addBar()
7 fooInstance.addBars()
8 fooInstance.removeBar()
9 fooInstance.removeBars()
10 fooInstance.createBar()

27
Fetching Associations
Lazy Loading

1 const awesomeCaptain = await Captain.findOne({


2 where: {
3 name: "Jack Sparrow"
4 }
5 });
6
7 console.log('Name:', awesomeCaptain.name);
8 console.log('Skill Level:', awesomeCaptain.skillLevel);
9
10 const hisShip = await awesomeCaptain.getShip();
11
12 console.log('Ship Name:', hisShip.name);
13 console.log('Amount of Sails:', hisShip.amountOfSails);

28
Fetching Associations
Eager Loading

1 const awesomeCaptain = await Captain.findOne({


2 where: {
3 name: "Jack Sparrow"
4 },
5 include: Ship
6 });
7
8 console.log('Name:', awesomeCaptain.name);
9 console.log('Skill Level:', awesomeCaptain.skillLevel);
10 console.log('Ship Name:', awesomeCaptain.ship.name);
11 console.log('Amount of Sails:', awesomeCaptain.ship.amountOfSails);

29
Hooks
Lifecycle Events

1 (1)
2 beforeValidate(instance, options)
3
4 [... validation happens ...]
5
6 (2)
7 afterValidate(instance, options)
8 validationFailed(instance, options, error)
9 (3)
10 beforeCreate(instance, options)
11 beforeDestroy(instance, options)
12 beforeUpdate(instance, options)
13
14 [... creation/update/destruction happens ...]
15
16 (4)
17 afterCreate(instance, options)
18 afterDestroy(instance, options)
19 afterUpdate(instance, options)

1 User.beforeCreate((user, options) => {


2 const hashedPassword = hashPassword(user.password);
3 user.password = hashedPassword;
4 });

30

You might also like