Easy workaround without fancy magic
This was a quick and easy workaround for me.
Simply apply a RegEx to the generated SQL to add in whatever statements you want.
import io
import pandas as pd
# Get the SQL that would be generated by the create table statement
create_table_sql = pd.io.sql.get_schema(df, tmp_table_name)
# Replace the `CREATE TABLE` part of the generated statement with
# whatever you need.
create_tmp_table_sql = re.sub(
"^(CREATE TABLE)?",
"CREATE TEMP TABLE",
create_table_sql
)
Then, you can use it like this:
# Write to the database in a transaction (psycopg2)
with conn.cursor() as cur:
cur.execute(create_tmp_table_sql)
output = io.StringIO()
df.to_csv(output, sep="\t", header=False, index=False, na_rep="NULL")
output.seek(0)
cur.copy_from(output, tmp_table_name, null="NULL")
Credit to Aseem for a fast
way to write to Postgres.