How Postgresql COPY TO STDIN With CSV do on conflic do update?

In this SO post, there are two answers that -combined together- provide a nice solution for successfully using ON CONFLICT. The example below, uses ON CONFLICT DO NOTHING;: BEGIN; CREATE TEMP TABLE tmp_table (LIKE main_table INCLUDING DEFAULTS) ON COMMIT DROP; COPY tmp_table FROM ‘full/file/name/here’; INSERT INTO main_table SELECT * FROM tmp_table ON CONFLICT DO NOTHING; … Read more

Use binary COPY table FROM with psycopg2

Here is the binary equivalent of COPY FROM for Python 3: from io import BytesIO from struct import pack import psycopg2 # Two rows of data; “id” is not in the upstream data source # Columns: node, ts, val1, val2 data = [(23253, 342, -15.336734, 2494627.949375), (23256, 348, 43.23524, 2494827.949375)] conn = psycopg2.connect(“dbname=mydb user=postgres”) curs … Read more

Insert Python Dictionary using Psycopg2

from psycopg2.extensions import AsIs song = { ‘title’: ‘song 1’, ‘artist’: ‘artist 1’ } columns = song.keys() values = [song[column] for column in columns] insert_statement=”insert into song_table (%s) values %s” # cursor.execute(insert_statement, (AsIs(‘,’.join(columns)), tuple(values))) print cursor.mogrify(insert_statement, (AsIs(‘,’.join(columns)), tuple(values))) Prints: insert into song_table (artist,title) values (‘artist 1’, ‘song 1’) Psycopg adapts a tuple to a record … Read more

Mac + virtualenv + pip + postgresql = Error: pg_config executable not found

On the Mac, if you’re using Postgres.app, the pg_config file is in your /Applications/Postgres.app/Contents/Versions/<current_version>/bin directory. That’ll need to be added to your system path to fix this error, like this: export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/<current_version>/bin So for example, if the current Postgres.app version is 9.5, this export line would be: export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.5/bin With more recent versions of the … Read more