시퀄라이즈는 SQL문을 자바스크립트 프로젝트 내에서 자바스크립트 객체로 작성할 수 있습니다. 

그렇지만, 시퀄라이즈 자체의 SQL과 다른 문법이 존재하기 때문에 이것도 익히는데 시간이 걸릴 것 같습니다.

또한, SQL문 데이터베이스를 다룰 백엔드 개발자라면 필수로 배우고 알아둬야하기 때문에 어떤 것을 쓰는게 맞을지 모르겠습니다.

하여튼 Sequelize 문법을 알아보겠습니다. 위에 SQL을 적어 해당 SQL문이 시퀄라이즈로 작성할때 어떻게 바뀌는지 보겠습니다.

 

먼저, 가장 간단한 CRUD부터 익혀보겠습니다. 

 

1) 생성하기(INSERT) 

INSERT INTO users (name,age,married,comment) VALUES ('JANG', 24, 0, '코멘트~');

 

User.create({ // Promise 방식 

name: 'JANG',

age:24,

married: false,

comment: '코멘트~'

});

 

2) 조회하기(SELECT)

// 모든 컬럼을 전부 가지고 오기.

SELECT * FROM users;

 

User.findAll():

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

// 일부 컬럼만 전부 가지고 오기.

SELECT name, married FROM users;

 

User.findAll({

attributes: ['name','married'],

});

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

[WHERE절 추가]

 

SELECT * FROM users WHERE authorId = 2

 

User.findAll({

 where: { authorId: 2 }

});  

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

SELECT * FROM users WHERE authorId = 12 AND status = 'active';

 

User.findAll({

 where: {

  authorId: 12,

  status: 'active'

   }

});

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Op라는 연산자가 존재한다. 이것으로 조건문등의 조건을 정할 수 있다.

 

Op.eq --> SELECT * FROM users WHERE authorId = 2와 동일하다.

const { Op } = require("sequelize");
User.findAll({
  where: {
    authorId: {
      [Op.eq]: 2
    }
  }
});

Op.and --> 위 SELECT * FROM users WHERE authorId = 12 AND status = 'active'; 와 동일해짐.

const { Op } = require("sequelize");
User.findAll({
  where: {
    [Op.and]: [
      { authorId: 12 },
      { status: 'active' }
    ]
  }
});

Op.or --> SELECT * FROM users WHERE authorId = 12 OR authorId = 13; 을 표현할 수 있다.

const { Op } = require("sequelize");
User.findAll({
  where: {
    [Op.or]: [
      { authorId: 12 },
      { authorId: 13 }
    ]
  }
});

위와 같이 동일한 필드를 조건문으로 찾을 경우, 구조를 바꿔서 좀 더 읽기 쉽게 바꿀 수 있다.

 

DELETE FROM post WHERE authorId = 12 OR authorId = 13;

const { Op } = require("sequelize");
Post.destroy({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});

그 외 엄청나게 많은 종류의 연산자를 제공한다.

너무 많고해서 복붙해 넣었다. 이런게 있구나만 보고 넘어가자.

const { Op } = require("sequelize");
User.findAll({
  where: {
    [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
    [Op.or]: [{ a: 5 }, { b: 6 }],             // (a = 5) OR (b = 6)
    someAttribute: {
      // Basics
      [Op.eq]: 3,                              // = 3
      [Op.ne]: 20,                             // != 20
      [Op.is]: null,                           // IS NULL
      [Op.not]: true,                          // IS NOT TRUE
      [Op.or]: [5, 6],                         // (someAttribute = 5) OR (someAttribute = 6)

      // Using dialect specific column identifiers (PG in the following example):
      [Op.col]: 'user.organization_id',        // = "user"."organization_id"

      // Number comparisons
      [Op.gt]: 6,                              // > 6
      [Op.gte]: 6,                             // >= 6
      [Op.lt]: 10,                             // < 10
      [Op.lte]: 10,                            // <= 10
      [Op.between]: [6, 10],                   // BETWEEN 6 AND 10
      [Op.notBetween]: [11, 15],               // NOT BETWEEN 11 AND 15

      // Other operators

      [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)

      [Op.in]: [1, 2],                         // IN [1, 2]
      [Op.notIn]: [1, 2],                      // NOT IN [1, 2]

      [Op.like]: '%hat',                       // LIKE '%hat'
      [Op.notLike]: '%hat',                    // NOT LIKE '%hat'
      [Op.startsWith]: 'hat',                  // LIKE 'hat%'
      [Op.endsWith]: 'hat',                    // LIKE '%hat'
      [Op.substring]: 'hat',                   // LIKE '%hat%'
      [Op.iLike]: '%hat',                      // ILIKE '%hat' (case insensitive) (PG only)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (PG only)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (PG only)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (PG only)

      [Op.any]: [2, 3],                        // ANY ARRAY[2, 3]::INTEGER (PG only)

      // In Postgres, Op.like/Op.iLike/Op.notLike can be combined to Op.any:
      [Op.like]: { [Op.any]: ['cat', 'hat'] }  // LIKE ANY ARRAY['cat', 'hat']

      // There are more postgres-only range operators, see below
    }
  }
});

 

Posted by sungho88
,

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

 

라고 공식 홈페이지 첫 화면에 나와있습니다... 영알못인 저는 구글 번역기에 넣어보겠습니다.

 

Sequelize는 Postgres, MySQL, MariaDB, SQLite 및 Microsoft SQL Server를위한 Promise 기반 Node.js ORM입니다.

견고한 트랜잭션 지원, 관계, eager 및 lazy로드, 읽기 복제 등을 제공합니다.

 

ORM = Object Relational Mappings

 

뭔 말인지 모르겠지만, 쉽게 말해 Sequelize는 Node.js에서 DB 서버를 생성할 수 있도록 해주는 것 같습니다.

 

Sequelize 설치

 

npm 또는 yarn을 이용해서 설치할 수 있습니다.

 

npm install sequelize (yarn add sequelize)

 

database 연결하기

 

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

const sequelize = new Sequelize('database', 'username', 'password', etc_config);

 

[Sequelize 특징]

Sequelize에서 제공하는 대부분의 메서드는 비동기식이므로 Promise를 반환합니다.

그러므로, Promise API (예 : then, catch, finally 사용)를 즉시 사용할 수 있습니다.

Posted by sungho88
,