【问题标题】:Migration to convert array of string to integer迁移以将字符串数组转换为整数
【发布时间】:2018-01-08 10:55:27
【问题描述】:

将字符串的data_type数组的列template_id转换为整数的迁移是什么?

例子:

一行具有值为 ["2"] 的 template_id。我希望它是 2。

template_id 的所有值在数组中都有一个元素。

【问题讨论】:

    标签: ruby-on-rails postgresql migration


    【解决方案1】:

    我会推荐以下方法来做到这一点

    1. 使用数据类型int 创建一个新字段temp_template_id
    2. template_id 的所有值插入temp_template_id
    3. 删除列template_id
    4. 将列 temp_template_id 重命名为 template_id

    一个。 rails g 迁移 AddTempTemplateDataToTableName

    def change
      add_column :table_name, :temp_template_id, :integer
    end
    

    b. rails g migration RenameColumnTemptemplateID

    def self.up
      # Script to fill column `temp_template_id` from 'template_id'
      remove_column :table_name, :template_id
      rename_column :table_name, :temp_template_id, :template_id
    end
    
    def self.down      
      rename_column :table_name, :template_id, :temp_template_id
      add_column :table_name, :template_id, :array, :default => []
      # Script to fill column `template_id` from 'temp_template_id'
    end
    

    【讨论】:

      【解决方案2】:

      SQL 迁移就像using n[1] 一样简单:

      t=# create table t3(n int[]);
      CREATE TABLE
      t=# insert into t3 select array[2];
      INSERT 0 1
      t=# select * from t3;
        n
      -----
       {2}
      (1 row)
      
      t=# alter table t3 alter COLUMN n type int using n[1];
      ALTER TABLE
      t=# select * from t3;
       n
      ---
       2
      (1 row)
      

      如果你的数组不是int[],你需要避免双重转换

      错误:无法转换列“template_id”的 USING 子句的结果 自动输入整数 提示:您可能需要添加显式 演员表。

      alter table t3 alter COLUMN n type int using n[1]::text::int;
      

      应该做的伎俩,这里的例子:

      t=# create table t3(n text[]);
      CREATE TABLE
      t=# insert into t3 select array[2];
      INSERT 0 1
      t=# select * from t3;
        n
      -----
       {2}
      (1 row)
      
      t=# alter table t3 alter COLUMN n type int using n[1]::text::int;
      ALTER TABLE
      t=# select * from t3;
       n
      ---
       2
      (1 row)
      

      【讨论】:

      • 错误:无法将列“template_id”的 USING 子句的结果自动转换为整数 提示:您可能需要添加显式转换。这里 template_id 是'n'
      • 尝试在我的 asnwer 中添加::text::int
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      相关资源
      最近更新 更多