aimdevel’s blog

勉強したことを書きます

TypeScript+SequelizeでSQLiteを使う

概要

vscode拡張機能でデータベースを使いたくなったため、TypeScriptからデータベースを使えるSequelizeを試してみた。 使用したデータベースはSQLiteで、以下のページを参考に作業した。

Getting Started | Sequelize

インストール

$ apt update
$ apt install sqlite3
$ npm install --save sequelize
$ npm install --save sqlite3

TypeScriptでdb操作

データベース接続

手順の通りに作成する。

import { Model, DataTypes, Sequelize } from 'sequelize';

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: '/path/to/database.sqlite'
});

try {
  sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

Modelの定義

データベースのテーブル構造を定義する。

// define Model
class User extends Model {
  declare id: number; // this is ok! The 'declare' keyword ensures this field will not be emitted by TypeScript.
  declare name: string;
}

User.init({
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING
  }
}, { sequelize });

データを追加する。

Modelの定義で作成したUserを使用してデータを追加する。

// insert
(async () => {
  await User.sync();
  const user = await User.create({ name: "taro" });
  const user2 = await User.create({ name: "jiro" });
})();

データを取り出す

Userのデータをすべて取り出す。

// select
(async () => {
  await User.sync();
  const users = await User.findAll();
  users.map(tmp=> console.log(tmp.id + ":" + tmp.name));
})();

まとめ

Sequelizeを試した。
今回は単純なデータの格納と読み出しだけを行ったが、Sequelizeを使えばデータベース操作は簡単に行えるように感じた。
TypeScriptでデータベースが使用できるようになったので、目的は達成。