def pgimport(<EOL>filename,<EOL>database_uri,<EOL>table_name,<EOL>encoding="<STR_LIT:utf-8>",<EOL>dialect=None,<EOL>create_table=True,<EOL>schema=None,<EOL>callback=None,<EOL>timeout=<NUM_LIT:0.1>,<EOL>chunk_size=<NUM_LIT>,<EOL>max_samples=<NUM_LIT>,<EOL>):
fobj = open_compressed(filename, mode="<STR_LIT:r>", encoding=encoding)<EOL>sample = fobj.read(chunk_size)<EOL>if dialect is None:  <EOL><INDENT>dialect = rows.plugins.csv.discover_dialect(<EOL>sample.encode(encoding), encoding=encoding<EOL>)<EOL><DEDENT>elif isinstance(dialect, six.text_type):<EOL><INDENT>dialect = csv.get_dialect(dialect)<EOL><DEDENT>if schema is None:<EOL><INDENT>reader = csv.reader(io.StringIO(sample), dialect=dialect)<EOL>field_names = [slug(field_name) for field_name in next(reader)]<EOL><DEDENT>else:<EOL><INDENT>field_names = list(schema.keys())<EOL><DEDENT>if create_table:<EOL><INDENT>if schema is None:<EOL><INDENT>data = [<EOL>dict(zip(field_names, row))<EOL>for row in itertools.islice(reader, max_samples)<EOL>]<EOL>table = rows.import_from_dicts(data)<EOL>field_types = [table.fields[field_name] for field_name in field_names]<EOL><DEDENT>else:<EOL><INDENT>field_types = list(schema.values())<EOL><DEDENT>columns = [<EOL>"<STR_LIT>".format(name, POSTGRESQL_TYPES.get(type_, DEFAULT_POSTGRESQL_TYPE))<EOL>for name, type_ in zip(field_names, field_types)<EOL>]<EOL>create_table = SQL_CREATE_TABLE.format(<EOL>table_name=table_name, field_types="<STR_LIT:U+002CU+0020>".join(columns)<EOL>)<EOL>execute_command(get_psql_command(create_table, database_uri=database_uri))<EOL><DEDENT>command = get_psql_copy_command(<EOL>database_uri=database_uri,<EOL>dialect=dialect,<EOL>direction="<STR_LIT>",<EOL>encoding=encoding,<EOL>header=field_names,<EOL>table_name=table_name,<EOL>)<EOL>rows_imported, error = <NUM_LIT:0>, None<EOL>fobj = open_compressed(filename, mode="<STR_LIT:rb>")<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>data = fobj.read(chunk_size)<EOL>total_written = <NUM_LIT:0><EOL>while data != b"<STR_LIT>":<EOL><INDENT>written = process.stdin.write(data)<EOL>total_written += written<EOL>if callback:<EOL><INDENT>callback(written, total_written)<EOL><DEDENT>data = fobj.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>rows_imported = int(stdout.replace(b"<STR_LIT>", b"<STR_LIT>").strip())<EOL><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, "<STR_LIT>": rows_imported}<EOL>
Import data from CSV into PostgreSQL using the fastest method

    Required: psql command