Guest User

Untitled

a guest
Nov 15th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. require 'pg'
  2.  
  3. # $ docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=password -d postgres:9.6
  4.  
  5. conn = PG.connect(host: 'localhost', port: 5432, user: 'postgres', password: 'password', dbname: 'postgres')
  6.  
  7. conn.exec <<SQL
  8. drop table if exists test_copy_to;
  9. create table test_copy_to (str varchar);
  10. insert into test_copy_to (str) values ('Ä');
  11. SQL
  12.  
  13. dec = PG::TextDecoder::CopyRow.new
  14. conn.copy_data('COPY (select * from test_copy_to) TO STDOUT', dec) do
  15. while row = conn.get_copy_data
  16. puts ['(1)', row[0].inspect, row[0][0].inspect, row[0].encoding].join("\t")
  17. end
  18. end
  19.  
  20. dec = PG::TextDecoder::CopyRow.new(type_map: PG::TypeMapByColumn.new([PG::TextDecoder::String.new]))
  21. conn.copy_data('COPY (select * from test_copy_to) TO STDOUT', dec) do
  22. while row = conn.get_copy_data
  23. puts ['(2)', row[0].inspect, row[0][0].inspect, row[0].encoding].join("\t")
  24. end
  25. end
  26.  
  27. dec = PG::TextDecoder::CopyRow.new(type_map: PG::TypeMapByColumn.new([PG::TextDecoder::Bytea.new]))
  28. conn.copy_data('COPY (select * from test_copy_to) TO STDOUT', dec) do
  29. while row = conn.get_copy_data
  30. puts ['(3)', row[0].inspect, row[0][0].inspect, row[0].encoding].join("\t")
  31.  
  32. str = row[0].force_encoding('utf-8')
  33. puts ['(4)', str.inspect, str[0].inspect, str.encoding].join("\t")
  34. end
  35. end
  36.  
  37. conn.copy_data('COPY (select * from test_copy_to) TO STDOUT CSV') do
  38. while row = conn.get_copy_data
  39. row = row.chomp
  40.  
  41. puts ['(5)', row.inspect, row[0].inspect, row.encoding].join("\t")
  42. str = row.force_encoding('utf-8')
  43. puts ['(6)', str[0].inspect, str.inspect, str.encoding].join("\t")
  44. end
  45. end
  46.  
  47. str = conn.exec('select * from test_copy_to').getvalue(0, 0)
  48. puts ['(7)', str.inspect, str[0].inspect, str.encoding].join("\t")
  49.  
  50. __END__
  51. ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]
  52.  
  53. (1) "Ä" "\xC3" UTF-8
  54. (2) "Ä" "\xC3" UTF-8
  55. (3) "\xC3\x84" "\xC3" ASCII-8BIT
  56. (4) "Ä" "Ä" UTF-8
  57. (5) "\xC3\x84" "\xC3" ASCII-8BIT
  58. (6) "Ä" "Ä" UTF-8
  59. (7) "Ä" "Ä" UTF-8
Add Comment
Please, Sign In to add comment