-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjupiter_db.py
564 lines (436 loc) · 18.1 KB
/
jupiter_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# -*- coding: utf-8 -*-
"""
Jupiter db access layer class
Jakob Lanstorp, MST 14-09-2017
NOTE:
-QGIS crashes hard on any db error
-It is JupiterDb responsibility to quote strings
-Always encapsulate sql in double quotes "", since single quotes '' are reserved for add string params to sql
"""
import psycopg2
import psycopg2.extras
import sys
import time
from jupiter_aux import *
import base64
from qgis.core import QgsDataSourceURI
class JupiterDb(object):
""" Provides database access via psycopy2 and QgsDataSourceURI """
CURRENT_SCHEMA = 'jupiter'
def __init__(self):
pass
def getUri(self):
""" Prepare connection to database """
params = self.get_dbparams()
uri = QgsDataSourceURI()
uri.setConnection(params['host'], str(params['port']), params['dbname'], params['user'], params['password'])
return uri
def test_connection(self):
""" Test database connection """
conn = None
try:
conn = psycopg2.connect(**self.get_dbparams())
conn.close()
return True
except:
return False
finally:
if conn:
conn.close()
def get_version(self):
""" Get version of PostgreSQL"""
sql = 'SELECT Version()'
cur = self.execute_sql(sql, dict_cursor=False)
row_tuple = cur.fetchone()
ver = row_tuple[0]
return ver
def execute_sql(self, sql, data=None, dict_cursor=True, print_sql=False):
""" Execute a SQL query
:param sql: SQL to be executed
:param data: Data to query in where clause
:param dict_cursor: Flag indicating if cursor is a dict or not. Use false for scalar queries
:param print_sql: Flag indicating if sql is to be printet
:return: returns a cursor
"""
if print_sql: print sql
database = psycopg2.connect(**self.get_dbparams())
if dict_cursor:
cur = database.cursor(cursor_factory=psycopg2.extras.DictCursor)
else:
cur = database.cursor()
try:
if data == None:
cur.execute(sql)
else:
cur.execute(sql, data)
return cur
#cur.close()
#database.close()
except psycopg2.DatabaseError, e:
JupiterAux.log_error('psycopg2.DatabaseError jalan error {}'.format(e))
sys.exit(1)
finally:
pass
# TODO
# if conn:
# conn.close()
def mogrify(self, sql, dict_cursor=True):
""" Test how psycopg2 renderes the sql before sending it to the database a SQL query
:param sql: SQL to be testet
:param dict_cursor: Flag indicating if cursor is a dict or not. Use false for scalar queries
:return: returns checked sql string
"""
conn = psycopg2.connect(**self.get_dbparams())
if dict_cursor:
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
else:
cur = conn.cursor()
try:
check_sql = cur.mogrify(sql)
return check_sql
except psycopg2.DatabaseError, e:
print 'MST DB Error {}'.format(e)
GrukosAux.log_error('MST DB Error {}'.format(e))
sys.exit(1)
finally:
pass
if conn:
conn.close()
def get_compound(self, compondType, wkt, dateFrom=None, dateTo=None, dateLatest=None):
"""
:param compondType:
:param wkt:
:param dateFrom:
:param dateTo:
:param dateLatest:
"""
pass
def boring_not_in_csv(self, dguno_str, dguno_arr):
"""
:param dguno_str: '167. 511, 168. 299, 168. 376'
:param dguno_arr: [u'167. 511', u'168. 299', u'168. 376']
:return: boreholeno not found in borehole table
"""
sql = 'SELECt boreholeno from {}.borehole WHERE boreholeno in ({});'.format(self.CURRENT_SCHEMA, dguno_str)
dictcur = self.execute_sql(sql)
rows_list = dictcur.fetchall()
if not rows_list:
return None
# boreholes found
list_boreholes = []
for row in rows_list:
boreholeno = str(row['boreholeno'])
list_boreholes.append(boreholeno)
dictcur.close()
# boreholes not found
list_boreholes_not_found = [b for b in dguno_arr if b not in list_boreholes]
#JupiterAux.msg_box('len(dguno_arr): {}'.format(len(dguno_arr)))
#JupiterAux.msg_box('len(rows_list): {}'.format(len(rows_list)))
#JupiterAux.msg_box('len(list_boreholes_not_found): {}'.format(len(list_boreholes_not_found)))
return list_boreholes_not_found
def get_style(self, style_name):
sql = "SELECT styleqml FROM public.layer_styles WHERE stylename = '{}';".format(style_name)
#JupiterAux.enable_qgis_log(haltApp=True)
cur = self.execute_sql(sql)
dictrow = cur.fetchone() # type DictRow
return unicode(dictrow[0])
def get_unit(self, sampleid, compound_name):
sql = "SELECT unit FROM {}.mst_compoundname_to_unit({}, '{}');".format(self.CURRENT_SCHEMA, sampleid, compound_name)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rec = dictcur.fetchone()
if not rec:
return None
unit = rec['unit']
dictcur.close()
return unit
def get_unit_quess(self, compound_no):
"""
Return the unit that is used the most for a compound
:param compound_no:
:return:
"""
sql = """
SELECT
c.longtext, count(*) AS count_units
FROM
jupiter.grwchemanalysis gca
INNER JOIN jupiter.code c ON c.code::NUMERIC = gca.unit AND c.codetype = 752
WHERE gca.compoundno = {}
GROUP BY c.longtext
ORDER BY count_units DESC
LIMIT 1;
""".format(compound_no)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql, dict_cursor=True)
rec = dictcur.fetchone()
if not rec:
return None
dictcur.close()
return rec['longtext']
def count_compound_units(self, compound_name):
""" Returns count of unit and unit for a given compound"""
sql = "SELECT antal, unit FROM {}.mst_count_compound_units('{}');".format(self.CURRENT_SCHEMA, compound_name)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rows_list = dictcur.fetchall()
if not rows_list:
return None
list_of_tuples = []
for row in rows_list:
count = int(row['antal'])
unit = str(row['unit']).encode('utf-8')
list_of_tuples.append((count, unit))
dictcur.close()
return list_of_tuples
def compoundname_to_no(self, compound_name):
sql = "SELECT {}.mst_compoundname_to_no('{}');".format(self.CURRENT_SCHEMA, compound_name)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rec = dictcur.fetchone()
if not rec:
return None
compoundno = rec[0]
dictcur.close()
return compoundno
def compoundno_to_name(self, compound_id):
sql = "SELECT {}.mst_compoundno_to_name({});".format(self.CURRENT_SCHEMA, compound_id)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rec = dictcur.fetchone()
if not rec:
return None
compoundname = rec[0]
dictcur.close()
return compoundname
def database_youngest_insert_in_days(self):
'''
:return: age in days since youngest sample inserted in database
'''
sql = "SELECT {}.db_age_in_days();".format(self.CURRENT_SCHEMA)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rec = dictcur.fetchone()
if not rec:
return None
days = rec[0]
dictcur.close()
return days
def database_geus_export_time_in_days(self):
'''
:return: age in days since complete database export from geus
'''
sql = "SELECT extract(days from now() - exporttime) AS dage FROM {}.exporttime;".format(self.CURRENT_SCHEMA)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rec = dictcur.fetchone()
if not rec:
return None
days = rec[0]
dictcur.close()
return days
def database_dbsync_success_in_days(self):
'''
:return: age in days of last succesfull dbsync run
'''
#sql = "SELECT extract(days from now() - endtime) AS dage FROM {}.synchronizationlog WHERE success = TRUE ORDER BY endtime DESC LIMIT 1;".format(self.CURRENT_SCHEMA)
sql = """
SELECT
extract(days from now() - endtime) AS dage
FROM
{}.synchronizationlog
WHERE success = TRUE
ORDER BY endtime DESC
LIMIT 1;
"""
sql = sql.format(self.CURRENT_SCHEMA)
#JupiterAux.enable_qgis_log(haltApp=True)
dictcur = self.execute_sql(sql)
rec = dictcur.fetchone()
if not rec:
return None
days = rec[0]
dictcur.close()
return days
def get_timeserie(self, boreholeno, compound, datefrom=None, dateto=None):
""" TODO: move function to plpgsql - currrently hardcoded schema
Intake query is disabled - all intake used
"""
from datetime import datetime
input_data = (
compound,
boreholeno,
datetime.strptime(datefrom, '%Y-%m-%d'),
datetime.strptime(dateto, '%Y-%m-%d')
)
sql = """
SELECT
ca.amount,
cs.sampledate
FROM jupiter.borehole b
INNER JOIN jupiter.grwchemsample cs USING (boreholeno)
INNER JOIN jupiter.grwchemanalysis ca ON ca.sampleid = cs.sampleid
INNER JOIN jupiter.compoundlist cl ON ca.compoundno = cl.compoundno
WHERE cl.long_text ilike %s AND
b.boreholeno = %s AND
cs.sampledate >= %s AND
cs.sampledate <= %s
ORDER BY cs.sampledate;
"""
cur = self.execute_sql(sql, data=input_data, dict_cursor=False)
result_data = cur.fetchall()
cur.close()
if (len(result_data)) > 0:
amount, dt = zip(*result_data)
return amount, dt
return None, None
def get_scatter_array_bbox(self, compoundno_x, compoundno_y, bbox, datefrom, dateto, compoundname_x, compoundname_y):
"""
:param compoundno_x: Compound number for x-ax
:param compoundno_y: Compound number for y-ax
:param bbox: QGIS boundingbox for query boreholes
:param datefrom: extract data from this date
:param dateto: extract data to this date
:return: tuple of two arrays with analysis amount of the two quried compounds
"""
from datetime import datetime
data_arg = {
'cmpno_x': compoundno_x,
'cmpno_y': compoundno_y,
'cmpname_x': compoundname_x,
'cmpname_y': compoundname_y,
'datefrom': datetime.strptime(datefrom, '%Y-%m-%d'),
'dateto': datetime.strptime(dateto, '%Y-%m-%d'),
'xmin': bbox.xMinimum(),
'ymin': bbox.yMinimum(),
'xmax': bbox.xMaximum(),
'ymax': bbox.yMaximum()
}
sql = """
WITH compound1 AS (
SELECT
boreholeno,
sampleid,
amount
FROM jupiter.mstmvw_bulk_grwchem_alldates
WHERE compoundno = %(cmpno_x)s AND
sampledate >= %(datefrom)s AND sampledate <= %(dateto)s AND
geom && ST_MakeEnvelope(%(xmin)s, %(ymin)s, %(xmax)s, %(ymax)s, 25832)
),
compound2 AS (
SELECT
sampleid,
amount
FROM jupiter.mstmvw_bulk_grwchem_alldates
WHERE compoundno = %(cmpno_y)s AND
sampledate >= %(datefrom)s AND sampledate <= %(dateto)s AND
geom && ST_MakeEnvelope(%(xmin)s, %(ymin)s, %(xmax)s, %(ymax)s, 25832)
)
SELECT
c1.boreholeno,
c1.amount AS {},
c2.amount AS {}
FROM compound1 c1
INNER JOIN compound2 c2 USING (sampleid)
""".format(compoundname_x, compoundname_y)
cur = self.execute_sql(sql, data=data_arg, dict_cursor=False)
data_result = cur.fetchall()
cur.close()
if (len(data_result)) > 0:
boreholeno, x, y = zip(*data_result) # zip list of record tuples to three single arrays
return x, y, boreholeno # array of sodium, array of sulphor, array of boreholeno
return None, None, None
def get_scatter_array_wkt(self, compoundno_x, compoundno_y, wkt, datefrom, dateto, compoundname_x, compoundname_y):
"""
:param compoundno_x: Compound number for x-ax
:param compoundno_y: Compound number for y-ax
:param wkt: WKT geometry for query boreholes
:param datefrom: extract data from this date
:param dateto: extract data to this date
:return: tuple of two arrays with analysis amount of the two quried compounds
"""
from datetime import datetime
data_arg = {
'cmpno_x': compoundno_x,
'cmpno_y': compoundno_y,
'cmpname_x': compoundname_x,
'cmpname_y': compoundname_y,
'datefrom': datetime.strptime(datefrom, '%Y-%m-%d'),
'dateto': datetime.strptime(dateto, '%Y-%m-%d'),
'wkt': wkt
}
# where_sql = "ST_WITHIN(geom , ST_GeomFromText('{}', 25832))".format(wkt)
sql = """
WITH compound1 AS (
SELECT
boreholeno,
sampleid,
amount
FROM jupiter.mstmvw_bulk_grwchem_alldates
WHERE compoundno = %(cmpno_x)s AND
sampledate >= %(datefrom)s AND sampledate <= %(dateto)s AND
ST_WITHIN(geom , ST_GeomFromText(%(wkt)s, 25832))
),
compound2 AS (
SELECT
sampleid,
amount
FROM jupiter.mstmvw_bulk_grwchem_alldates
WHERE compoundno = %(cmpno_y)s AND
sampledate >= %(datefrom)s AND sampledate <= %(dateto)s AND
ST_WITHIN(geom , ST_GeomFromText(%(wkt)s, 25832))
)
SELECT
c1.boreholeno,
c1.amount AS {},
c2.amount AS {}
FROM compound1 c1
INNER JOIN compound2 c2 USING (sampleid)
""".format(compoundname_x, compoundname_y)
cur = self.execute_sql(sql, data=data_arg, dict_cursor=False)
data_result = cur.fetchall()
cur.close()
if (len(data_result)) > 0:
boreholeno, x, y = zip(*data_result)
return x, y, boreholeno # array of sodium, array of sulphor
return None, None, None
def get_xy(self, boreholeno):
sql = """
SELECT
ST_X(geom) AS x,
ST_Y(geom) AS y
FROM jupiter.borehole
WHERE boreholeno = '{}'
""".format(boreholeno)
cur = self.execute_sql(sql)
row = cur.fetchone()
cur.close()
if row:
x = row['x']
y = row['y']
return x, y
return None, None
def get_dbparams(self):
# Get db connections params #
return {'host': 'localhost', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_user', 'password': 'jupiter_user'}
'''
def get_dbparams(self):
# Get db connections params #
# Use this for multiple user support and log access for personal queries #
import getpass
bno = getpass.getuser().upper()
dict_user = {
'B020574': {'host': 'localhost', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_jalan', 'password': 'bfa4e464-0e8e-43f8-a982-f3456e954c90'},
'B006303': {'host': 'C1400020', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_trini', 'password': '55b553d5-a22b-4417-974f-a80bb680cf4a'},
'B028026': {'host': 'C1400020', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_nalje', 'password': '9a0f5cc3-a8cb-41b0-b2b3-35d32c607988'},
'B005556': {'host': 'C1400020', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_jehan', 'password': 'b4c83817-799d-492c-bbb4-57e7320ede6f'},
'B006337': {'host': 'C1400020', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_zicos', 'password': '2f8a47e6-5e3c-479e-b8ac-8f65ef5b9786'},
'B005625': {'host': 'C1400020', 'port': 5432, 'dbname': 'pcjupiterxl', 'user': 'jupiter_josiv', 'password': '66fc890f-8b68-469c-bb4a-cfa936f60987'}
}
credentials = dict_user[bno]
if credentials == None:
JupiterAux.msg_box(u'{} er ikke bruger på Qupiter. Kontakt [email protected] for oprettelse'.format(bno))
return None
else:
return credentials
'''