問(wèn)題發(fā)現(xiàn)
今天在跑migrate,代碼如下:
class CreateReconciliationOrderItems < ActiveRecord::Migration[5.1]
def change
create_table :reconciliation_order_items do |t|
t.string :kind
t.string :month
t.text :content
t.string :status
t.string :type
t.references :reconciliation
t.references :reconciliation_result_set
t.string :internal_source_type
t.string :internal_source_id
t.timestamps null: false
end
end
end
數(shù)據(jù)庫(kù)報(bào)了一個(gè)錯(cuò)誤:
(0.3ms) SELECT pg_try_advisory_lock(5675054488983918780)
(1.4ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Migrating to CreateReconciliationOrderItems (20180116061824)
(0.2ms) BEGIN
== 20180116061824 CreateReconciliationOrderItems: migrating ===================
-- create_table(:reconciliation_order_items)
(21.0ms) CREATE TABLE "reconciliation_order_items" ("id" bigserial primary key, "kind" character varying, "month" character varying, "content" text, "status" character varying, "type" character varying, "reconciliation_id" bigint, "reconciliation_result_set_id" bigint, "internal_source_type" character varying, "internal_source_id" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
(1.0ms) CREATE INDEX "index_reconciliation_order_items_on_reconciliation_id" ON "reconciliation_order_items" ("reconciliation_id")
(1.6ms) ROLLBACK
(0.3ms) SELECT pg_advisory_unlock(5675054488983918780)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
Index name 'index_reconciliation_order_items_on_reconciliation_result_set_id' on table 'reconciliation_order_items' is too long; the limit is 63 characters
重點(diǎn)是在最后一句
Index name 'index_reconciliation_order_items_on_reconciliation_result_set_id' on table 'reconciliation_order_items' is too long; the limit is 63 characters
剛開(kāi)始我并不知道這個(gè)問(wèn)題的所在饶火。只當(dāng)是版本上周升級(jí)rails5的遺留問(wèn)題,并且這個(gè)migrate在線上環(huán)境已經(jīng)跑過(guò)了,問(wèn)題不是特別大,也就每當(dāng)回事。等閑下來(lái)之后查了一下資料艘蹋,網(wǎng)上又很完善的介紹。
pg數(shù)據(jù)庫(kù)文檔中有說(shuō):
The system uses no more than NAMEDATALEN-1 bytes of an identifier; longer names can be written in commands, but they will be truncated. By default, NAMEDATALEN is 64 so the maximum identifier length is 63 bytes. If this limit is problematic, it can be raised by changing the NAMEDATALEN constant in src/include/pg_config_manual.h.
大概意思就是SQL標(biāo)識(shí)符與關(guān)鍵字不能超過(guò)64個(gè)字節(jié)票灰。因此女阀,我們只能創(chuàng)建64-1個(gè)字節(jié),也就是63個(gè)字節(jié)屑迂。為此浸策,rails中有相應(yīng)指明name的方法。
代碼如下
t.references :reconciliation_result_set, index: { name: 'index_on_reconciliation_result_set_id'}
你可以在migrate中直接聲明name的名字惹盼,也可以使用
add_index :reconciliation_order_items, : reconciliation_result_set_id, name: 'index_on_reconciliation_result_set_id'
就是不使用默認(rèn)的聲明名稱庸汗,自定義符合要求的聲明名稱即可。