hogehogeプログラマ

PHPer。趣味ではServerless Frameworkをメインで触ってます

MariaDB 10.2.1からレコードのデフォルト値の設定が柔軟に

https://mariadb.com/kb/en/library/create-table/#default

From MariaDB 10.2.1 you can use most functions in DEFAULT. Expressions should have parentheses around them. If you use a non deterministic function in DEFAULT then all inserts to the table will be replicated in row mode. You can even refer to earlier columns in the DEFAULT expression:

試しに以下の様なSQL文を発行してみます。

CREATE TABLE t1 (
  seq int PRIMARY KEY,
  code char(6) DEFAULT ( CONCAT("A", LPAD(seq, 5, 0)) )
)

正常終了しました。
ちなみにMariaDB 5.5.56で実行すると以下のエラーとなります。

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '( CONCAT("A", LPAD(seq, 5, 0)) )
)' at line 3

次は以下のSQLを実行してみます。

CREATE TABLE t2 (
  seq int PRIMARY KEY AUTO_INCREMENT,
  code char(6) DEFAULT ( CONCAT("A", LPAD(seq, 5, 0)) )
)

すると以下のエラーが発生してしまいました。
どうやらAUTO_INCREMENTと組み合わせて利用することは出来無いようです。

ERROR 1901 (HY000): Function or expression 'AUTO_INCREMENT' cannot be used in the DEFAULT clause of `seq`

続いては以下SQLでBLOBでもできるのか試してみます。

CREATE TABLE t3 (
  seq int PRIMARY KEY AUTO_INCREMENT,
  data blob DEFAULT ( COLUMN_CREATE("id", "1") )
)

正常に完了しました。
Dynamic Columnsも利用できるようです。(まず使わないと思いますが)

AUTO_INCREMENTと併用するとエラーとなったのは残念ですが
デフォルト値を柔軟に設定できるようになったのは便利なので利用できる場面では
ドンドン使っていきたいところです。

最近お仕事でよく利用するAmazon RDSはMariaDB 10.1なので
まだ当面利用はできませんけどね笑

http://docs.aws.amazon.com/ja_jp/AmazonRDS/latest/UserGuide/CHAP_MariaDB.html

2018/1/11追記:
RDSでMariaDB 10.2がサポートされたようです。
Amazon RDS で MariaDB 10.2 がサポート可能になりました