-def execute_file(conn, fname):
- """ Read an SQL file and run its contents against the given connection.
+from .connection import get_pg_env
+from ..errors import UsageError
+
+LOG = logging.getLogger()
+
+def _pipe_to_proc(proc, fdesc):
+ chunk = fdesc.read(2048)
+ while chunk and proc.poll() is None:
+ try:
+ proc.stdin.write(chunk)
+ except BrokenPipeError as exc:
+ raise UsageError("Failed to execute SQL file.") from exc
+ chunk = fdesc.read(2048)
+
+ return len(chunk)
+
+def execute_file(dsn, fname, ignore_errors=False, pre_code=None, post_code=None):
+ """ Read an SQL file and run its contents against the given database
+ using psql. Use `pre_code` and `post_code` to run extra commands
+ before or after executing the file. The commands are run within the
+ same session, so they may be used to wrap the file execution in a
+ transaction.