检查输入字符串是否符合数据库排序规则
Check if input string conforms with DB collation
由于我们的电子邮件服务的限制,我们拥有的是带有电子邮件字段的 table - 排序规则 latin1_swedish_ci
。
这个 table 在新用户到达时检查他是否已经订阅。
用户在其电子邮件中使用的字符对于此特定排序规则无效。以hsıasdf@test.com
为例
Would it be possible to determine before saving if a string will
adhere to the collation rules of database?
Is it possible for me to check before any DB trigger to
save/create/find; if an entry with this particular email will
agree with the collation? Some regex maybe?
在 Ruby 中,您可以使用 String#encode
来测试常见编码之间的字符串转换。
然而,这对您没有帮助,因为您想要测试 MySQL 特定的排序规则。
你可以做的是使用 transaction:
User.transaction do
if User.create!(email: 'hsıasdf@test.com')
puts "yup its valid"
raise ActiveRecord::Rollback
end
end
不过效果不是很好。如果您希望它在保存之前 运行,您可以使用自定义验证。
如果可能,我会使用 MySQL 标准 utf
和 utf8_general_ci
并仅在需要与电子邮件系统交互的应用程序边界进行转换。使用非 UTF-8 编码会给您带来很多麻烦,并且在很长一段时间内可能会非常有害 运行 例如,如果更改了错误的电子邮件系统。
您可以select即时整理:
SELECT users.email COLLATE latin1_swedish_ci AS users.collated_email
FROM users
RoR: application_controller.rb
def configure_charsets
response.headers["Content-Type"] = "text/html; charset=utf-8"
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute 'SET NAMES UTF8'
end end
您应该使用 utf8(或 utf8mb4),而不是非常有限的 latin1(仅处理西欧)。
ALTER TABLE user_subscriptions
CONVERT TO utf8;
(其他表同上)。
你的标题说的是检查。但我认为,当您使用相同的 CHARACTER SET
获得所有内容时,就不需要任何 'checking'.
试试下面的方法 query.It 可能对你有帮助。
select * from user_subscription where email=cast('hsıasdf@test.com' as char CHARSET latin1);
由于我们的电子邮件服务的限制,我们拥有的是带有电子邮件字段的 table - 排序规则 latin1_swedish_ci
。
这个 table 在新用户到达时检查他是否已经订阅。
用户在其电子邮件中使用的字符对于此特定排序规则无效。以hsıasdf@test.com
Would it be possible to determine before saving if a string will adhere to the collation rules of database?
Is it possible for me to check before any DB trigger to save/create/find; if an entry with this particular email will agree with the collation? Some regex maybe?
在 Ruby 中,您可以使用 String#encode
来测试常见编码之间的字符串转换。
然而,这对您没有帮助,因为您想要测试 MySQL 特定的排序规则。
你可以做的是使用 transaction:
User.transaction do
if User.create!(email: 'hsıasdf@test.com')
puts "yup its valid"
raise ActiveRecord::Rollback
end
end
不过效果不是很好。如果您希望它在保存之前 运行,您可以使用自定义验证。
如果可能,我会使用 MySQL 标准 utf
和 utf8_general_ci
并仅在需要与电子邮件系统交互的应用程序边界进行转换。使用非 UTF-8 编码会给您带来很多麻烦,并且在很长一段时间内可能会非常有害 运行 例如,如果更改了错误的电子邮件系统。
您可以select即时整理:
SELECT users.email COLLATE latin1_swedish_ci AS users.collated_email
FROM users
RoR: application_controller.rb
def configure_charsets
response.headers["Content-Type"] = "text/html; charset=utf-8"
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute 'SET NAMES UTF8'
end end
您应该使用 utf8(或 utf8mb4),而不是非常有限的 latin1(仅处理西欧)。
ALTER TABLE user_subscriptions
CONVERT TO utf8;
(其他表同上)。
你的标题说的是检查。但我认为,当您使用相同的 CHARACTER SET
获得所有内容时,就不需要任何 'checking'.
试试下面的方法 query.It 可能对你有帮助。
select * from user_subscription where email=cast('hsıasdf@test.com' as char CHARSET latin1);