-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_helpers.py
308 lines (260 loc) · 8.28 KB
/
database_helpers.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
import csv
import json
import psycopg2
import sys
conn = None
# database connection method
def getConnection():
conn = psycopg2.connect("dbname=geo_database user=postgres password=1234")
cur = conn.cursor()
return cur, conn
def import_data():
values = []
sql = """INSERT INTO area_codes(pincode, place_name, state_name, lat, long, accuracy, g_point) VALUES \n\t"""
pincode_file = 'pincode_data.csv'
with open(pincode_file, 'r') as csvfile:
pincode_reader = csv.reader(csvfile, delimiter=',', quotechar='"')
headerSet = False
for row in pincode_reader:
if not headerSet:
headerSet = True
continue
query = "("
query += "'" + row[0] + "',"
query += "'" + row[1] + "',"
query += "'" + row[2] + "',"
if row[3]:
query += row[3] + ","
else:
query += "null,"
if row[4]:
query += row[4] + ","
else:
query += "null,"
if row[5]:
query += row[5] + ","
else:
query += "null,"
if row[3] and row[4]:
query += "cube({}, {})".format(row[3], row[4])
else:
query += "null"
query += ")"
values.append(query)
sql += ",\n\t ".join(str(x) for x in values)
try:
cur, conn = getConnection()
cur.execute( sql )
conn.commit()
cur.close()
except Exception as e:
print(e)
finally:
if conn is not None:
conn.close()
def import_geojson_data():
values = []
sql = """INSERT INTO area_geojson(place_name, parent_name, type, boundary_points) Values \n\t"""
area_file = 'area_data.json'
with open(area_file) as f:
data = json.load(f)
for feature in data['features']:
polygon_geom = ','.join(list(map(lambda x: str(tuple(x)), feature['geometry']['coordinates'][0])))
query = "("
query += "'" + feature['properties']['name'] + "',"
query += "'" + feature['properties']['parent'] + "',"
query += "'" + feature['properties']['type'] + "',"
query += "'" + polygon_geom + "'"
query += ")"
values.append(query)
print(values[0])
sql += ",\n\t ".join(str(x) for x in values)
try:
cur, conn = getConnection()
cur.execute( sql )
conn.commit()
cur.close()
except Exception as e:
print(e)
finally:
if conn is not None:
conn.close()
def show_data():
sql = """SELECT * FROM area_codes"""
try:
cur, conn = getConnection()
cur.execute(sql)
print(cur.fetchall())
cur.close()
except Exception as e:
print(e)
finally:
if conn is not None:
conn.close()
def delete_data():
sql = """DELETE FROM area_codes"""
try:
cur, conn = getConnection()
cur.execute(sql)
conn.commit()
cur.close()
except Exception as e:
print(e)
finally:
if conn is not None:
conn.close()
def should_save_data(_pincode, _lat, _long, _offset_distance):
sql = """SELECT * FROM area_codes WHERE pincode = 'IN/{0}' OR earth_distance( ll_to_earth(lat::numeric, long::numeric), ll_to_earth({1},{2}) ) / 1000 <= {3}""".format(_pincode, _lat, _long, _offset_distance)
shouldSave = False
response = None
try:
cur, conn = getConnection()
cur.execute( sql )
data = cur.fetchall()
if not data:
shouldSave = True
else:
response = []
for row in data:
response.append({
"pincode": row[0],
"place_name": row[1],
"state_name": row[2],
"lat": row[3],
"long": row[4],
})
cur.close()
except Exception as e:
print(e)
finally:
if conn is not None:
conn.close()
return shouldSave, response
def save_data(_pincode, _place, _state, _lat, _long):
sql = """INSERT INTO area_codes(pincode, place_name, state_name, lat, long, g_point) VALUES ('IN/{}', '{}', '{}', {}, {}, cube({}, {})) """.format(_pincode, _place, _state, _lat, _long, _lat, _long)
status = ''
try:
cur, conn = getConnection()
cur.execute( sql )
conn.commit()
cur.close()
status = 'SUCCESS'
except Exception as e:
status = 'ERROR'
print(e)
finally:
if conn is not None:
conn.close()
return status
def delete_record(_pincode):
sql = """DELETE FROM area_codes WHERE pincode = 'IN/{}'""".format(_pincode)
status = ''
try:
cur, conn = getConnection()
cur.execute( sql )
conn.commit()
cur.close()
status = 'SUCCESS'
print(sql)
except Exception as e:
status = 'ERROR'
print(e)
finally:
if conn is not None:
conn.close()
return status
def get_nearby_data_default(_lat, _long, _distance):
sql = """SELECT *, earth_distance( ll_to_earth(lat::numeric, long::numeric), ll_to_earth({0},{1}) ) as distance
FROM area_codes
WHERE (lat::numeric <> {0} and long::numeric <> {1} ) and earth_distance( ll_to_earth(lat::numeric, long::numeric), ll_to_earth({0},{1}) ) <= {2}
ORDER BY distance ASC
""".format(_lat, _long, _distance)
status = ''
response = []
try:
cur, conn = getConnection()
cur.execute( sql )
data = cur.fetchall()
# print(sql)
for row in data:
response.append({
"pincode": row[0],
"place_name": row[1],
"state_name": row[2],
"lat": row[3],
"long": row[4],
"distance": row[7]
})
cur.close()
status = 'SUCCESS'
except Exception as e:
status = 'ERROR'
print(e)
finally:
if conn is not None:
conn.close()
return status, response
def get_nearby_data_self(_lat, _long, _distance):
sql = """SELECT *, ( 6371 * acos( cos( radians({0}) ) * cos( radians(lat::numeric) ) * cos( radians(long::numeric) - radians({1}) ) + sin( radians({0}) ) * sin( radians(lat::numeric) ) ) ) AS distance
FROM area_codes
WHERE (lat::numeric <> {0} and long::numeric <> {1} ) and ( 6371 * acos( cos( radians({0}) ) * cos( radians(lat::numeric) ) * cos( radians(long::numeric) - radians({1}) ) + sin( radians({0}) ) * sin( radians(lat::numeric) ) ) ) < {2}
ORDER BY distance ASC
""".format(_lat, _long, _distance)
status = ''
response = []
try:
cur, conn = getConnection()
cur.execute( sql )
data = cur.fetchall()
for row in data:
response.append({
"pincode": row[0],
"place_name": row[1],
"state_name": row[2],
"lat": row[3],
"long": row[4],
"distance": row[7]
})
cur.close()
status = 'SUCCESS'
except Exception as e:
status = 'ERROR'
print(e)
finally:
if conn is not None:
conn.close()
return status, response
def get_containing_area(_lat, _long):
sql = """select * from area_geojson where boundary_points @> '({}, {})';""".format(_lat, _long)
status = ''
response = []
try:
cur, conn = getConnection()
cur.execute( sql )
data = cur.fetchall()
for row in data:
response.append({
"id": row[0],
"place_name": row[1],
"state_name": row[2]
})
cur.close()
status = 'SUCCESS'
except Exception as e:
status = 'ERROR'
print(e)
finally:
if conn is not None:
conn.close()
return status, response
def main(*kargs):
program_name = sys.argv[1]
if program_name == 'import_data':
import_data()
import_geojson_data()
elif program_name == 'delete_data':
delete_data()
elif program_name == 'show_data':
show_data()
if __name__ == '__main__':
main()