Created
February 27, 2025 01:03
-
-
Save mmyoji/2b110eaa3cfedaaff37025233ecb02ff to your computer and use it in GitHub Desktop.
Minimum example of Sequelize (MySQL) on Deno
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
db: | |
image: mysql:8.0 | |
command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_0900_bin | |
environment: | |
- MYSQL_ALLOW_EMPTY_PASSWORD=yes | |
- MYSQL_DATABASE=app_development | |
ports: | |
- "3306:3306" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "npm:mysql2@^3.12.0"; | |
import { | |
CreationOptional, | |
DataTypes, | |
InferAttributes, | |
InferCreationAttributes, | |
literal, | |
Model, | |
Sequelize, | |
} from "npm:sequelize@^6.37.5"; | |
const sequelize = new Sequelize({ | |
dialect: "mysql", | |
database: "app_development", | |
username: "root", | |
password: "", | |
logging: !!process.env.LOGGING, | |
port: 3306, | |
timezone: "+09:00", | |
define: { | |
charset: "utf8mb4", | |
collate: "utf8mb4_0900_bin", | |
engine: "InnoDB", | |
freezeTableName: true, | |
timestamps: false, | |
}, | |
}); | |
class UserModel extends Model< | |
InferAttributes<UserModel>, | |
InferCreationAttributes<UserModel> | |
> { | |
declare id: CreationOptional<number>; | |
declare name: string; | |
declare status: number; | |
declare createdAt: CreationOptional<Date>; | |
declare updatedAt: CreationOptional<Date>; | |
} | |
UserModel.init( | |
{ | |
id: { | |
type: DataTypes.BIGINT({ length: 20 }).UNSIGNED, | |
autoIncrement: true, | |
primaryKey: true, | |
}, | |
name: { | |
type: DataTypes.STRING(255), | |
allowNull: false, | |
}, | |
status: { | |
type: DataTypes.TINYINT({ length: 3 }).UNSIGNED, | |
allowNull: false, | |
defaultValue: 0, | |
}, | |
createdAt: { | |
type: "TIMESTAMP", | |
allowNull: false, | |
defaultValue: literal("CURRENT_TIMESTAMP"), | |
}, | |
updatedAt: { | |
type: "TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", | |
allowNull: false, | |
defaultValue: literal("CURRENT_TIMESTAMP"), | |
}, | |
}, | |
{ | |
indexes: [], | |
modelName: "users", | |
sequelize, | |
tableName: "users", | |
underscored: true, | |
} | |
); | |
/** | |
* Usage: | |
* ```sh | |
* docker compose up -d | |
* deno run main.ts | |
* ``` | |
*/ | |
(async () => { | |
await sequelize.sync({ force: true }); | |
await UserModel.create({ name: "John Doe" }); | |
const users = await UserModel.findAll(); | |
console.log(users.map((u) => u.toJSON())); | |
await sequelize.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment