Help us learn about your current experience with the documentation. Take the survey.
创建枚举
创建新的枚举时,应使用数据库类型 SMALLINT。
SMALLINT 类型的大小为 2 字节,对于枚举来说已经足够。
这有助于节省数据库空间。
要使用此类型,请在创建该列的迁移中添加 limit: 2。
示例:
def change
add_column :ci_job_artifacts, :file_format, :integer, limit: 2
end所有的键/值对都应在 FOSS 中定义
摘要:如果一个模型也属于 FOSS,那么所有的枚举都需要在 FOSS 中定义。
class Model < ApplicationRecord
enum platform: {
aws: 0,
gcp: 1 # EE-only
}
end当您向 enum 添加新的键/值对,并且它是 EE 特有的时,您可能会想按以下方式组织 enum:
# Define `failure_reason` enum in `Pipeline` model:
class Pipeline < ApplicationRecord
enum failure_reason: Enums::Pipeline.failure_reasons
end# Define key/value pairs that used in FOSS and EE:
module Enums
module Pipeline
def self.failure_reasons
{ unknown_failure: 0, config_error: 1 }
end
end
end
Enums::Pipeline.prepend_mod_with('Enums::Pipeline')# Define key/value pairs that used in EE only:
module EE
module Enums
module Pipeline
override :failure_reasons
def failure_reasons
super.merge(job_activity_limit_exceeded: 2)
end
end
end
end虽然这种方法可行,但它有几个缺点:
- 有人在 EE 中定义的键/值对可能与在 FOSS 中定义的值冲突。
例如,在
EE::Enums::Pipeline中定义job_activity_limit_exceeded: 1。 - 当这种情况发生时,该功能的工作方式会完全不同。
例如,我们无法确定
failure_reason是config_error还是job_activity_limit_exceeded。 - 当这种情况发生时,我们必须发布一个数据库迁移来修复数据完整性,但如果您无法恢复原始值,这可能是不可能的。
此外,您可能会通过在 EE 模块的值中设置一个偏移量来观察解决此问题的方法。
例如,此示例将 1000 设置为偏移量:
module EE
module Enums
module Pipeline
override :failure_reasons
def failure_reasons
super.merge(job_activity_limit_exceeded: 1_000, size_limit_exceeded: 1_001)
end
end
end
end这看起来像一个可行的变通方法,然而,这种方法也有一些缺点:
- 功能可能会从 EE 移动到 FOSS,反之亦然。因此,未来偏移量可能会在 FOSS 和 EE 之间混合。
例如,当您将
job_activity_limit_exceeded移动到 FOSS 时,您会看到{ unknown_failure: 0, config_error: 1, job_activity_limit_exceeded: 1_000 }。 - 用于
enum的整数列很可能被创建为SMALLINT。 因此,您需要注意偏移量不能超过 2 字节整数的最大值。
总之,您应该在 FOSS 中定义所有的键/值对。 例如,在上述情况下,您可以编写以下代码:
class Pipeline < ApplicationRecord
enum failure_reason: {
unknown_failure: 0,
config_error: 1,
job_activity_limit_exceeded: 2
}
end在空隙中添加新值
合并一些 EE 和 FOSS 枚举后,这两组值之间可能存在一个空隙:
module Enums
module Ci
module CommitStatus
def self.failure_reasons
{
# ...
data_integrity_failure: 12,
forward_deployment_failure: 13,
insufficient_bridge_permissions: 1_001,
downstream_bridge_project_not_found: 1_002,
# ...
}
end
end
end
end要添加新值,您应该先填补这个空隙。
在上面的示例中,添加 14 而不是 1_003:
{
# ...
data_integrity_failure: 12,
forward_deployment_failure: 13,
a_new_value: 14,
insufficient_bridge_permissions: 1_001,
downstream_bridge_project_not_found: 1_002,
# ...
}