Issue using positional parameters in sql script, using pg8000 - python

I have the following SQL query:
query_string = "SELECT sum(unmatched), " \
"TIMESTAMP WITH TIME ZONE 'epoch' + INTERVAL '1 second' * " \
"round(extract('epoch' from time_window) / {}) * {} as time_window " \
"FROM aggregate_counts WHERE reconciliation_name = %s " \
"GROUP BY round(extract('epoch' from time_window) / {})".format(interval_sec, interval_sec, interval_sec)
cur.execute(query_string, (reconciliation_name))
It works fine unless I want to avoid using string replacement for "interval_sec" and use positional parameters instead, like I have for other parameters. Problem is, if I do that:
query_string = "SELECT sum(unmatched), " \
"TIMESTAMP WITH TIME ZONE 'epoch' + INTERVAL '1 second' * " \
"round(extract('epoch' from time_window) / %s) * %s as time_window " \
"FROM aggregate_counts WHERE reconciliation_name = %s " \
"GROUP BY round(extract('epoch' from time_window) / %s)"
cur.execute(query_string, (interval_sec, interval_sec, reconciliation_name, interval_sec))
I get the following error:
Error handler middleware caught the following exception: {'S':
'ERROR', 'V': 'ERROR', 'C': '42803', 'M': 'column
"aggregate_counts.time_window" must appear in the GROUP BY clause or
be used in an aggregate function', 'P': '177', 'F': 'parse_agg.c',
'L': '1344', 'R': 'check_ungrouped_columns_walker'}
File
File "pg8000/core.py", line 1829, in execute
ps = cache['ps'][key]
KeyError: ("SELECT sum(unmatched), TIMESTAMP WITH TIME ZONE 'epoch' + INTERVAL '1 second' * round(extract('epoch' from time_window) / %s) * %s as time_window FROM aggregate_counts WHERE reconciliation_name = %s GROUP BY round(extract('epoch' from time_window) / %s)", ((701, 1, ), (701, 1, ), (705, 0, .text_out at 0x10c58cea0>)))
Can positional parameters only be used in comparisons (=, >=, < etc...)?

So it's basically not possible to have this. Reason being the %s in select clause will get converted to let's say, $x positional argument, and the %s in group by will get converted to $y (x and y being the respective positions.) Now postgres has no way of knowing that after resolving, these two will be the same. Hence it assumes that "aggregate_counts.time_window" is not present in GROUP BY. I understand it's not the perfect explanation, but this is kind of what is happening.

Related

Invalid Identifier programming error in snowflake

I am running the following query in snowflake and it runs fine.
set id ='TEST_TABLE1';
set time_s = '2021-03-31 06:52:51+00:00';
merge into TEST_STATUS using (select column1 AS TABLENAME,
column2 AS LASTUPDATED from values ($id,$time_s)) tt
on TEST_STATUS.TABLE_NAME = tt.TABLENAME
when matched then update set TEST_STATUS.LAST_UPDATED = tt.LASTUPDATED
when not matched then insert (TABLE_NAME, LAST_UPDATED) values (tt.TABLENAME, tt.LASTUPDATED)
But when I try to run it via python code as following:
self.table = 'TEST_TABLE1'
self.timestamp='2021-03-31 06:52:51+00:00';
cmd = f"set id ={self.table};"
cmd2 = f"set time_s = str({timestamp});"
merge_cmd = f"merge into {self.table} using (select column1 AS TABLENAME, column2 AS LASTUPDATED from " \
f"values ($id,$time_s)) tt on {self.table}.TABLE_NAME = tt.TABLENAME when " \
f"matched then update set {self.status_tbl}.LAST_UPDATED = tt.LASTUPDATED when not matched then " \
f"insert (TABLE_NAME, LAST_UPDATED) values (tt.TABLENAME, tt.LASTUPDATED) "
self.snowflake_client.run(cmd)
self.snowflake_client.run(cmd2)
self.snowflake_client.run(merge_cmd)
I am getting exception as:
snowflake.connector.errors.ProgrammingError: 000904 (42000): SQL compilation error: error line 1 at position 14
invalid identifier 'TEST_TABLE1'
Can you add single quotation marks when assigning to variables?
self.table = 'TEST_TABLE1'
self.timestamp='2021-03-31 06:52:51+00:00'
cmd = f"set id = '{self.table}';"
cmd2 = f"set time_s = 'str({timestamp})';"
merge_cmd = f"merge into {self.table} using (select column1 AS TABLENAME, column2 AS LASTUPDATED from " \
f"values ('$id','$time_s')) tt on {self.table}.TABLE_NAME = tt.TABLENAME when " \
f"matched then update set {self.status_tbl}.LAST_UPDATED = tt.LASTUPDATED when not matched then " \
f"insert (TABLE_NAME, LAST_UPDATED) values (tt.TABLENAME, tt.LASTUPDATED) "
self.snowflake_client.run(cmd)
self.snowflake_client.run(cmd2)
self.snowflake_client.run(merge_cmd)

Python's Sqlite3 module will not return full rows when using SELECT FROM WHERE

I'm trying to create a function using Python's Sqlite3 module that will return a list of rows based on a datetime timestamp search using the SELECT command.
Right now, selecting everything (with 'select * from example_table') will return a entire rows correctly, but selecting based on timestamps (using '''select %s from %s where %s > ? and %s < ?''' % (date_col_name, table_name, date_col_name, date_col_name)) will only return the timestamp in a tuple (missing the other column).
Previously, I struggled to preserve the datetime data type, but with detect_types=sqlite3.PARSE_DECLTYPES it returns an actual datetime object. Normally I would suspect this to be the issue, however the actual "filtering" part of the SELECT command is working. The correct datetime objects are being returned, they're just missing the other datas in the row they belonged to.
Relevant code:
sql_database_name = 'data_history.db'
date_col_name = 'Date'
class Database manager ...
... init ...
def get_table_range(self, table_name, daterange=None):
con = sqlite3.connect(self.database_name, detect_types=sqlite3.PARSE_DECLTYPES)
c = con.cursor()
if daterange is not None:
startdate = daterange[0]
enddate = daterange[1]
sql = '''select %s from %s where %s > ? and %s < ?''' % (date_col_name, table_name, date_col_name, date_col_name)
data = (startdate, enddate)
c.execute(sql, data)
else:
sql = 'select * from %s' % table_name
c.execute(sql)
print("Fetchine one: ", c.fetchone())
result = c.fetchall()
c.close()
con.close()
return result
if __name__ == "__main__":
test_db = "test.db"
manager = DatabaseManager(database_name=test_db)
selected = manager.get_table_range("test_table")
print("Selected " + str(len(selected)) + "rows.")
print("---")
selected = manager.get_table_range("test_table", (datetime(2020, 3, 2, 23), datetime(2020, 3, 3)))
print("Selected " + str(len(selected)) + "rows.")
Actual output:
Fetchine one: (datetime.datetime(2020, 3, 2, 19, 12, 57, 120184), 291.0)
Selected 97rows.
Fetchine one: (datetime.datetime(2020, 3, 2, 23, 22, 15, 704786),) <<-- extra columns were not returned
Selected 25rows.
Desired output:
Fetchine one: (datetime.datetime(2020, 3, 2, 19, 12, 57, 120184), 291.0)
Selected 97rows.
Fetchine one: (datetime.datetime(2020, 3, 2, 23, 22, 15, 704786), XXX.X)
Selected 25rows.
It's returning exactly what you're asking for, since your query translates into:
SELECT date_col_name FROM table_name WHERE date_col_name < ? AND date_col_name > ?;
You probably want to generate the code SELECT * FROM. . . or SELECT list, of, column, names FROM . . ..
And why are you building the SQL statement with string replacement for the column and table names? You should just be writing:
sql = '''select date_col_name from table_name where date_col_name > ? and date_col_name < ?'''
The column names are not variables (unless you have some strange set-up with multiple identically structured tables with different name and different column names, which could possibly indicate a design flaw).

Speeding up insertion of point data from netcdf

I've got this netcdf of weather data (one of thousands that require postgresql ingestion). I'm currently capable of inserting each band into a postgis-enabled table at a rate of about 20-23 seconds per band. (for monthly data, there is also daily data that i have yet to test.)
I've heard of different ways of speeding this up using COPY FROM, removing the gid, using ssds, etc... but I'm new to python and have no idea how to store the netcdf data to something I could use COPY FROM or what the best route might be.
If anyone has any other ideas on how to speed this up, please share!
Here is the ingestion script
import netCDF4, psycopg2, time
# Establish connection
db1 = psycopg2.connect("host=localhost dbname=postgis_test user=********** password=********")
cur = db1.cursor()
# Create Table in postgis
print(str(time.ctime()) + " CREATING TABLE")
try:
cur.execute("DROP TABLE IF EXISTS table_name;")
db1.commit()
cur.execute(
"CREATE TABLE table_name (gid serial PRIMARY KEY not null, thedate DATE, thepoint geometry, lon decimal, lat decimal, thevalue decimal);")
db1.commit()
print("TABLE CREATED")
except:
print(psycopg2.DatabaseError)
print("TABLE CREATION FAILED")
rawvalue_nc_file = 'netcdf_file.nc'
nc = netCDF4.Dataset(rawvalue_nc_file, mode='r')
nc.variables.keys()
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:], time_var.units)
newtime = [fdate.strftime('%Y-%m-%d') for fdate in dtime]
rawvalue = nc.variables['tx_max'][:]
lathash = {}
lonhash = {}
entry1 = 0
entry2 = 0
lattemp = nc.variables['lat'][:].tolist()
for entry1 in range(lat.size):
lathash[entry1] = lattemp[entry1]
lontemp = nc.variables['lon'][:].tolist()
for entry2 in range(lon.size):
lonhash[entry2] = lontemp[entry2]
for timestep in range(dtime.size):
print(str(time.ctime()) + " " + str(timestep + 1) + "/180")
for _lon in range(lon.size):
for _lat in range(lat.size):
latitude = round(lathash[_lat], 6)
longitude = round(lonhash[_lon], 6)
thedate = newtime[timestep]
thevalue = round(float(rawvalue.data[timestep, _lat, _lon] - 273.15), 3)
if (thevalue > -100):
cur.execute("INSERT INTO table_name (thedate, thepoint, thevalue) VALUES (%s, ST_MakePoint(%s,%s,0), %s)",(thedate, longitude, latitude, thevalue))
db1.commit()
cur.close()
db1.close()
print(" Done!")
If you're certain most of the time is spent in PostgreSQL, and not in any other code of your own, you may want to look at the fast execution helpers, namely cur.execute_values() in your case.
Also, you may want to make sure you're in a transaction, so the database doesn't fall back to an autocommit mode. ("If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it.")
Something like this could do the trick -- not tested though.
for timestep in range(dtime.size):
print(str(time.ctime()) + " " + str(timestep + 1) + "/180")
values = []
cur.execute("BEGIN")
for _lon in range(lon.size):
for _lat in range(lat.size):
latitude = round(lathash[_lat], 6)
longitude = round(lonhash[_lon], 6)
thedate = newtime[timestep]
thevalue = round(
float(rawvalue.data[timestep, _lat, _lon] - 273.15), 3
)
if thevalue > -100:
values.append((thedate, longitude, latitude, thevalue))
psycopg2.extras.execute_values(
cur,
"INSERT INTO table_name (thedate, thepoint, thevalue) VALUES %s",
values,
template="(%s, ST_MakePoint(%s,%s,0), %s)"
)
db1.commit()

python MySQLdb query tables iteratively

I'm trying to query one table against the other using Python and MySQLdb. Here's what I've got so far:
db = MySQLdb.connect( host = 'localhost', user = 'user', passwd=
'password', db = 'vacants')
cursor = db.cursor()
numrows = cursor.rowcount
query = "SELECT address, ((20903520) * acos (cos ( radians(38.67054) )* cos(
radians( lat ) ) * cos( radians( `long` ) - radians(-90.22942) ) + sin (
radians(38.67054) ) * sin( radians( lat ) ))) AS distance FROM vacants HAVING
distance < 100;"
cursor.execute(query)
I have one table, cfs, and another, vacants. I want to see for each row in cfs is there a vacant property within 100 feet. So for the ( radians(38.67054) and radians(-90.22942), I need to loop through the cfs table so that each cfs latitude and longitude replaces those two numbers. (That's just a test latitude and longitude we used)
In the end I'd like to have (in a .csv) the vacant property address, the distance from the call for service, and the type of call (which are two separate fields in the calls for service database). Something like this, which is from the query above:
Here's example data - calls for service coordinates:
38.595767638008056,-90.2316138251402
38.57283495467307,-90.24649031378685
38.67497061776659,-90.28415976525395
38.67650431524285,-90.25623757427952
38.591971519414784,-90.27782710145746
38.61272746420862,-90.23292862245287
38.67312983860098,-90.23591869583113
38.625956494342674,-90.18853950906939
38.69044465638584,-90.24339061920696
38.67745024638241,-90.20657832034047
And vacants:
38.67054,-90.22942
38.642956,-90.21466
38.671535,-90.27293
38.666367,-90.23749
38.65339,-90.23141
38.645996,-90.20334
38.60214,-90.224815
38.67265,-90.214134
38.665504,-90.274414
38.668354,-90.269966
This is not the final solution as there is insufficient info (address field? and 20903520 ?) in the question but it might help you get on track by showing how to iterate through both tables and substitute lat, lon from the CFS table into the query applied to the vacants table:
import mysql.connector
cnx1 = mysql.connector.connect(user='root',password='xxxx',host='127.0.0.1',database=db)
cursor1 = cnx1.cursor()
cnx2 = mysql.connector.connect(user='root',password='xxxx',host='127.0.0.1',database=db)
cursor2 = cnx2.cursor()
sql_cfs = ('select lat,lon from cfs')
cursor1.execute(sql_cfs)
for cfs in cursor1:
[cfs_lat,cfs_lon] = cfs
print (cfs_lat,cfs_lon)
query = ("SELECT address, ((20903520) * " \
"acos (cos(radians(lon)) *" \
"cos(radians({})) * " \
"cos(radians({})-radians(lat)) + sin(radians(lon)) * " \
"sin( radians({})))) AS distance " \
"FROM vacants HAVING distance < 100;".format(cfs_lat,cfs_lon,cfs_lat))
print (query)
cursor2.execute(query)
for vacants in cursor2:
print (vacants)

How to use python to ETL between databases?

Using psycopg2, I'm able to select data from a table in one PostgreSQL database connection and INSERT it into a table in a second PostgreSQL database connection.
However, I'm only able to do it by setting the exact feature I want to extract, and writing out separate variables for each column I'm trying to insert.
Does anyone know of a good practice for either:
moving an entire table between databases, or
iterating through features while not having to declare variables for every column you want to move
or...?
Here's the script I'm currently using where you can see the selection of a specific feature, and the creation of variables (it works, but this is not a practical method):
import psycopg2
connDev = psycopg2.connect("host=host1 dbname=dbname1 user=postgres password=*** ")
connQa = psycopg2.connect("host=host2 dbname=dbname2 user=postgres password=*** ")
curDev = connDev.cursor()
curQa = connQa.cursor()
sql = ('INSERT INTO "tempHoods" (nbhd_name, geom) values (%s, %s);')
curDev.execute('select cast(geom as varchar) from "CCD_Neighborhoods" where nbhd_id = 11;')
tempGeom = curDev.fetchone()
curDev.execute('select nbhd_name from "CCD_Neighborhoods" where nbhd_id = 11;')
tempName = curDev.fetchone()
data = (tempName, tempGeom)
curQa.execute (sql, data)
#commit transactions
connDev.commit()
connQa.commit()
#close connections
curDev.close()
curQa.close()
connDev.close()
connQa.close()
One other note is that python allows the ability to explicitly work with SQL functions / data type casting, which for us is important as we work with the GEOMETRY data type. Above you can see I'm casting it to TEXT then dumping it into an existing geometry column in the source table - this will work with MSSQL Server, which is a huge feature in the geospatial community...
In your solution (your solution and your question have a different order of statements) change the lines which start with 'sql = ' and the loop before '#commit transactions' comment to
sql_insert = 'INSERT INTO "tempHoods" (nbhd_id, nbhd_name, typology, notes, geom) values '
sql_values = ['(%s, %s, %s, %s, %s)']
data_values = []
# you can make this larger if you want
# ...try experimenting to see what works best
batch_size = 100
sql_stmt = sql_insert + ','.join(sql_values*batch_size) + ';'
for i, row in enumerate(rows, 1):
data_values += row[:5]
if i % batch_size == 0:
curQa.execute (sql_stmt , data_values )
data_values = []
if (i % batch_size != 0):
sql_stmt = sql_insert + ','.join(sql_values*(i % batch_size)) + ';'
curQa.execute (sql_stmt , data_values )
BTW, I don't think you need to commit. You don't begin any transactions. So there should not be any need to commit them. Certainly, you don't need to commit a cursor if all you did was a bunch of selects on it.
Here's my updated code based on Dmitry's brilliant solution:
import psycopg2
connDev = psycopg2.connect("host=host1 dbname=dpspgisdev user=postgres password=****")
connQa = psycopg2.connect("host=host2 dbname=dpspgisqa user=postgres password=****")
curDev = connDev.cursor()
curQa = connQa.cursor()
print "Truncating Source"
curQa.execute('delete from "tempHoods"')
connQa.commit()
#Get Data
curDev.execute('select nbhd_id, nbhd_name, typology, notes, cast(geom as varchar) from "CCD_Neighborhoods";') #cast geom to varchar and insert into geometry column!
rows = curDev.fetchall()
sql_insert = 'INSERT INTO "tempHoods" (nbhd_id, nbhd_name, typology, notes, geom) values '
sql_values = ['(%s, %s, %s, %s, %s)'] #number of columns selecting / inserting
data_values = []
batch_size = 1000 #customize for size of tables...
sql_stmt = sql_insert + ','.join(sql_values*batch_size) + ';'
for i, row in enumerate(rows, 1):
data_values += row[:5] #relates to number of columns (%s)
if i % batch_size == 0:
curQa.execute (sql_stmt , data_values )
connQa.commit()
print "Inserting..."
data_values = []
if (i % batch_size != 0):
sql_stmt = sql_insert + ','.join(sql_values*(i % batch_size)) + ';'
curQa.execute (sql_stmt, data_values)
print "Last Values..."
connQa.commit()
# close connections
curDev.close()
curQa.close()
connDev.close()
connQa.close()

Categories

Resources