MariaDB(MySQL)での767byte問題を解決する


概要

Laravelの決済周りのテーブルを作成しようとしたときに、以下のようなエラーで失敗しました。

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;
  max key length is 767 bytes (SQL: alter table `users` add index `users_stripe_id_ind
  ex`(`stripe_id`))

MySQLでは767バイト以上のカラムに対してはインデックスを貼れないようです。

対処法

1. インデックスの制限をあげる

my.confを書き換えることで、制限をあげることができます。

  • my.confの配置場所を探す
$ mysql --help | grep my.cnf
  • 設定を追記
my.conf
[mysqld]
innodb_large_prefix
innodb_file_per_table=1
innodb_file_format=Barracuda
  • 設定されているか確認
> SHOW GLOBAL VARIABLES LIKE 'innodb_file%';
+--------------------------+-----------+
| Variable_name            | Value     |
+--------------------------+-----------+
| innodb_file_format       | Barracuda |
| innodb_file_format_check | ON        |
| innodb_file_format_max   | Antelope  |
| innodb_file_per_table    | ON        |
+--------------------------+-----------+
4 rows in set (0.01 sec)

> SHOW GLOBAL VARIABLES LIKE 'innodb_large%';
+---------------------+-------+
| Variable_name       | Value |
+---------------------+-------+
| innodb_large_prefix | ON    |
+---------------------+-------+
1 row in set (0.00 sec)

2. MariaDBのバージョンをあげる

MariaDBのバージョンが10.1以下の場合、my.confの設定だけでは不十分で、10.2以上にあげる必要があります。

バージョンアップに関してはこちらの記事でまとめたので、必要であれば参考にしていただけると幸いです。

参考