LoginSignup
0
0

More than 1 year has passed since last update.

TypeOrmでカラム単位またはテーブル単位で大文字小文字の区別をさせる方法

Posted at

前提

MySQLはデフォルトだとカラムで大文字と小文字を区別しません。なので、passwordなどのカラムを作った場合

password
PASSOWRD
PassWord

のようなものが

select * from passwords where password = "PaSsWoRd"

などのクエリですべてマッチしてしまいます。これを回避するには、Collationに `utf8mb4_bin'や'ascii_bin'の設定が必要です。これをTypeOrmのEntityで設定する方法を紹介します。

カラム単位で設定

ColumnOptionsにcharsetとcollationがあるので、そちらを設定します。

import { Column, Entity } from "typeorm"

@Entity()
export class User {

  @Column({
    charset: "utf8mb4",
    collation: "utf8mb4_bin"
  })
  username!: string

  @Column({
    charset: "ascii",
    collation: "ascii_bin"
  })
  password!: string
}

collationに、{charset}_binの設定をしてやると良いです。

テーブル単位(Entity単位)で設定

EntityOptionsにはcollationの設定が無いのでEngineで代用します。

import { Column, Entity } from "typeorm"

@Entity({
  engine: "InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"
})
export class User {

  @Column()
  username!: string

  // DefaultのCharset以外にする場合は、collationの設定必要
  @Column({
    charset: "ascii",
    collation: "ascii_bin"
  })
  password!: string
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0