Guest User

Untitled

a guest
Jun 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. def pgsql_copy(session,tablename,string_buffer,direction="from"):
  2. """
  3. Args:
  4. session: a SA session that with a started transaction.
  5. tablename: the table to write into
  6. string_buffer: handle to a filelike, with seek set to 0
  7. direction: from|to, which way it should go.
  8. sele
  9. Returns:
  10. True on success, raises on errror
  11.  
  12. Note:
  13. 1. This isn't really containable in a session, given pgcopy.
  14. 2. If you want to use a selectable in 'to' copying,
  15. wrap it in parens as shown in example below.
  16. 3. 'from' means from string_buffer to db
  17. 'to' is from db to string_buffer
  18.  
  19. example:
  20.  
  21. ## hack: selectables for 'to' need to be wrapped in parens...
  22. # psql_copy(session, "(select 1)", buf, 'to') # does....
  23. # > COPY (select 1) TO STDOUT WITH DELIMITER E'\t';
  24. """
  25. if direction not in ('from','to'):
  26. raise ValueError("direction must be one of: from|to")
  27.  
  28. if direction == 'from':
  29. SQL = '''COPY %(tablename)s FROM STDIN USING DELIMITERS E'\t' ''' \
  30. % (dict(tablename=tablename))
  31. else:
  32. SQL = '''COPY %(tablename)s TO STDOUT WITH DELIMITER E'\t';''' \
  33. % (dict(tablename=tablename))
  34. connection = session.connection()
  35. # We need the raw psycopg-cursor, hidden deep within SA's abstractions.
  36. cursor = connection.connection.cursor().cursor
  37. cursor.copy_expert(SQL, string_buffer)
  38. return True
Add Comment
Please, Sign In to add comment