mysql – Slick 3.1.1没有创建唯一约束
作者:互联网
我有一个简单的用户表,其中id设置为自动增量,并且用户名也可以在表中设置为唯一.
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)
}
但是当使用slick(db.run(users.schema.create))创建表时,不会在数据库上创建唯一索引idx_username
以下是schema users.schema.createStatements.foreach(println)的create语句:
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功能时,我是否遗漏了创建唯一约束的内容?
解决方法:
TEXT列不能用作UNIQUE.如果你试试,
db.run(users.schema.create).onFailure{
case x => println("error " + x)
}
它会打印,
error com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: BLOB/TEXT column ‘username’ used in key specification without a key length
作为一种解决方法,您可以指定类型和长度,
def username = column[String]("username", O.SqlType("VARCHAR(65535)"))
标签:slick-3-0,scala,mysql,database-schema 来源: https://codeday.me/bug/20190829/1760003.html