Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for psycopg3 #183

Open
isratmir opened this issue Mar 5, 2024 · 2 comments
Open

Support for psycopg3 #183

isratmir opened this issue Mar 5, 2024 · 2 comments

Comments

@isratmir
Copy link

isratmir commented Mar 5, 2024

Is there a plan to add support for https://www.psycopg.org/psycopg3/docs/index.html?

@palewire
Copy link
Owner

palewire commented Mar 6, 2024

I can't say I've thought about it before. Do you know what kind of changes that might require?

@DeeeeLAN
Copy link

DeeeeLAN commented Dec 5, 2024

The most notable change I faced was the removal of copy_expert. Here is a psql_insert_copy method for uploading a pandas dataframe to the database which I updated for psycopg3. Hopefully it helps.

'''
Alternative to_sql() *method* for DBs that support COPY FROM
'''
import csv
from io import StringIO

def psql_insert_copy(table, conn, keys, data_iter):
	"""
	Execute SQL statement inserting data

	Parameters
	----------
	table : pandas.io.sql.SQLTable
	conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
	keys : list of str
		Column names
	data_iter : Iterable that iterates the values to be inserted
	"""
	# gets a DBAPI connection that can provide a cursor
	dbapi_conn = conn.connection
	with dbapi_conn.cursor() as cur:
		s_buf = StringIO()
		writer = csv.writer(s_buf)
		writer.writerows(data_iter)
		s_buf.seek(0)

		columns = ', '.join([f'"{k}"' for k in keys])
		if table.schema:
			table_name = f'{table.schema}.{table.name}'
		else:
			table_name = table.name

		sql = f'COPY {table_name} ({columns}) FROM STDIN WITH CSV'

		with cur.copy(sql) as copy:
			while data := s_buf.read(10240):
				copy.write(data)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants