def pgexport(<EOL>database_uri,<EOL>table_name,<EOL>filename,<EOL>encoding="<STR_LIT:utf-8>",<EOL>dialect=csv.excel,<EOL>callback=None,<EOL>timeout=<NUM_LIT:0.1>,<EOL>chunk_size=<NUM_LIT>,<EOL>):
if isinstance(dialect, six.text_type):<EOL><INDENT>dialect = csv.get_dialect(dialect)<EOL><DEDENT>command = get_psql_copy_command(<EOL>database_uri=database_uri,<EOL>direction="<STR_LIT>",<EOL>encoding=encoding,<EOL>header=None,  <EOL>table_name=table_name,<EOL>dialect=dialect,<EOL>)<EOL>fobj = open_compressed(filename, mode="<STR_LIT:wb>")<EOL>try:<EOL><INDENT>process = subprocess.Popen(<EOL>shlex.split(command),<EOL>stdin=subprocess.PIPE,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>)<EOL>total_written = <NUM_LIT:0><EOL>data = process.stdout.read(chunk_size)<EOL>while data != b"<STR_LIT>":<EOL><INDENT>written = fobj.write(data)<EOL>total_written += written<EOL>if callback:<EOL><INDENT>callback(written, total_written)<EOL><DEDENT>data = process.stdout.read(chunk_size)<EOL><DEDENT>stdout, stderr = process.communicate()<EOL>if stderr != b"<STR_LIT>":<EOL><INDENT>raise RuntimeError(stderr.decode("<STR_LIT:utf-8>"))<EOL><DEDENT><DEDENT>except FileNotFoundError:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>except BrokenPipeError:<EOL><INDENT>raise RuntimeError(process.stderr.read().decode("<STR_LIT:utf-8>"))<EOL><DEDENT>return {"<STR_LIT>": total_written}<EOL>
Export data from PostgreSQL into a CSV file using the fastest method

    Required: psql command