gpt4 book ai didi

ruby-on-rails - PostgreSQL 无法将类型 json 转换为字符 varying[]

转载 作者:行者123 更新时间:2023-11-29 13:47:08 30 4
gpt4 key购买 nike

在我的 Rails 5.0.5 应用中,我需要将 json 列转换为 string, array: true

我的 json 列中的值如下:

[ "200px-RR5219-0015R.png", "2017_03_25_2235.doc", "137555.jpg" ]

我试过这个迁移:

class ChangeTaskAttachmentsTypeToString < ActiveRecord::Migration[5.0]
def change
change_column :tasks, :attachments, :string, array: true
end
end

得到这个错误:

ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  column "attachments" cannot be cast automatically to type character varying[]
HINT: You might need to specify "USING attachments::character varying[]".
: ALTER TABLE "tasks" ALTER COLUMN "attachments" TYPE character varying[]

然后我编辑了迁移:

class ChangeTaskAttachmentsTypeToString < ActiveRecord::Migration[5.0]
def change
change_column :tasks, :attachments, 'character varying[] USING attachments::character varying[]'
end
end

最后得到这个错误:

PG::CannotCoerce: ERROR:  cannot cast type json to character varying[]
: ALTER TABLE "tasks" ALTER COLUMN "attachments" TYPE character varying[] USING attachments::character varying[]

我该如何进行迁移?

最佳答案

我猜数组元素是文件名。如果是这样,那么您可以删除所有字符 []" 和空格并将结果拆分为数组,如下所示:

with my_table(attachments) as (
values
('[ "200px-RR5219-0015R.png", "2017_03_25_2235.doc", "137555.jpg" ]'::json)
)
select string_to_array(translate(attachments::text, '[] "', ''), ',')::varchar[]
from my_table;

string_to_array
---------------------------------------------------------
{200px-RR5219-0015R.png,2017_03_25_2235.doc,137555.jpg}
(1 row)

所以使用:

... USING string_to_array(translate(attachments::text, '[] "', ''), ',')::varchar[]

更正式(和通用)的解决方案需要自定义函数,例如:

create or replace function json_to_text_array(json)
returns text[] language sql immutable as $$
select array_agg(value)
from json_array_elements_text($1)
$$;

可以用在

alter table tasks alter column attachments type text[] 
using json_to_text_array(attachments);

请注意,我使用 text[] 作为 Postgres 更自然的选择,但如果需要,您可以将其替换为 varchar[]

Db<>fiddle. 中测试它

关于ruby-on-rails - PostgreSQL 无法将类型 json 转换为字符 varying[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503111/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com