我希望将数据库转储导入到新数据库,该数据库没有旧数据库所拥有的所有列。
因此,要忽略/删除这些列,我的想法是编辑dump.sql。
如何在ruby中读取和编辑sql文件?
所创建的转储:
pg_dump --data-only old_database > dump_data_12_3_2019.sql;使用:
在sql文件中:
COPY public.images (id, file, created_at, updated_at, rotation) FROM stdin;
255 31265d7843.JPG 2018-11-15 09:05:43.37898 2018-11-15 09:05:43.37898 0
256 78e834e4e7.JPG 2018-11-15 09:05:43.571389 2018-11-15 09:05:43.571389 0
257 7b6662659b.JPG 2018-11-15 09:05:44.275989 2018-11-15 09:05:44.275989 0
215 6fe307f4b5.jpg 2018-10-15 11:08:59.42583 2018-10-15 11:12:25.284024 0标题以复制开始,列名在( )中,数据在下面,分隔符的空间在下面。
如何删除列旋转和他的数据?
发布于 2019-03-12 15:55:57
您必须“更新”原始sql文件,方法是删除这些列(在新DB中不可用)和这些列的数据。
只需逐行读取,根据您的逻辑修改它,并写入其他文件。考虑一些行是列信息,而另一些是数据。
path = '/tmp/source'
temp_file = Tempfile.new('output')
begin
File.open(path, 'r') do |file|
file.each_line do |line|
# change the line according your logic
temp_file.puts new_line
end
end
temp_file.close
ensure
temp_file.close
temp_file.unlink
end之后,可以使用pg commands还原目标文件。
psql -U <username> -d <dbname> -1 -f <filename>.sql或
pg_restore -U <username> -d <dbname> -1 <filename>.dump发布于 2019-03-12 15:07:47
您需要打开文件(1)、单独的命令(2),然后执行一些操作来编辑SQL代码(3),最后运行它(4)。
contents = File.read('path/to/file.sql') # (1) If the file is huge, do not read it whole, but line by line
commands = contents.split(';') # (2) probably you'll need something more clever (hint: regex) because of the ; character in the data
commands.each do |command|
stripped_command = strip_some_columns(command) # (3)
ActiveRecord::Base.connection.execute(stripped_command) # (4)
endhttps://stackoverflow.com/questions/55123395
复制相似问题