光滑3.1.1不创建唯一约束

时间:2016-02-23 04:18:15

标签: mysql scala database-schema slick-3.0

我有简单的用户表,其中id设置为自动增量,并且username在表格中设置为唯一。

class Users (tag: Tag) extends Table[User](tag, "Users") {

  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def username = column[String]("username", NotNull)
  def email = column[String]("email")
  def passwordHash = column[String]("password_hash")
  def createdAt = column[Long]("created_at")
  def updatedAt = column[Long]("updated_at")
  def lastLoggedInAt = column[Long]("last_logged_in_at")

  override def * = (id.?, username, email, passwordHash, createdAt, updatedAt, lastLoggedInAt) <> (User.tupled, User.unapply)

  def idxUsername = index("idx_username", username, unique = true)
}

但是当使用光滑(db.run(users.schema.create))创建表时,不会在数据库上创建唯一索引idx_username

以下是架构users.schema.createStatements.foreach(println)的创建语句:

create table `Users` (`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,`username` TEXT NOT NULL,`email` TEXT NOT NULL,`password_hash` TEXT NOT NULL,`created_at` BIGINT NOT NULL,`updated_at` BIGINT NOT NULL,`last_logged_in_at` BIGINT NOT NULL)
create unique index `idx_username` on `Users` (`username`,`email`)

用户表索引的数据库查询

mysql> SHOW INDEX FROM Users;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| users |          0 | PRIMARY  |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)

在执行DDL函数时,我是否遗漏了创建唯一约束的内容?

1 个答案:

答案 0 :(得分:5)

TEXT列不能用作UNIQUE。如果你试试,

db.run(users.schema.create).onFailure{
  case x => println("error " + x)
}

它会打印,

  

错误com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:BLOB / TEXT列'用户名'在密钥规范中使用,没有密钥长度

作为解决方法,您可以指定类型和长度,

def username = column[String]("username", O.SqlType("VARCHAR(65535)"))