· 7 years ago · Oct 17, 2018, 01:00 PM
1import psycopg2
2
3# --- SETUP ---
4# for printing some messages in the console
5DEBUG = True
6
7# The only things that need to be filled in to run the script (+ line 102: tables, will change that later):
8# dbname, user, password
9# and
10# year, old data filename, category, empty string for later
11input_for_script = (2016, 'ongeval.csv', 'ongevallen', '')
12
13# Connect to an existing database
14conn = psycopg2.connect("dbname=rws_2011_2017 user=postgres password=Prandall19s!")
15
16# --- EXECUTION ---
17# This code adds a new year of RWS data to the old dataset.
18# Requirements: 1. all tables are located in the same schema (old years, new year to add, reference tables)
19# 2. the table will only join the attributes from the old table
20# 3. the names of the reference tables end in '.txt.csv' */
21
22# Open a cursor to perform database operations
23cur = conn.cursor()
24
25# Creates settings table. input it takes:
26# the year (to add),
27# the name of the old table (containing the previous years)
28# and category (partij/ongeval/slachtoffer/voertuig/etcetera)
29cur.execute("""
30DROP TABLE IF EXISTS _rws_settings;
31CREATE TABLE _rws_settings (
32 year_to_add INT,
33 old_data text,
34 category text,
35 year_filename text);
36""")
37
38cur.execute("""
39INSERT INTO _rws_settings
40 (year_to_add, old_data, category, year_filename)
41VALUES
42 (%s, %s, %s, %s);
43 """,
44 input_for_script)
45
46cur.execute("""
47UPDATE _rws_settings
48SET year_filename = CONCAT(_rws_settings.category, '_', _rws_settings.year_to_add, '.csv');
49""")
50
51
52# Creates lookup table _rws_datatypes, which states the column names and datatypes of old_data from _rws_settings
53cur.execute("""
54DROP TABLE IF EXISTS _rws_datatypes;
55CREATE TABLE _rws_datatypes AS
56SELECT column_name, data_type FROM INFORMATION_SCHEMA.columns
57WHERE table_name = (SELECT old_data FROM _rws_settings);
58""")
59
60# Creates lookup table _rws_references: It takes the columns ending in '_ID' or '_CODE' and the name of the reference table.
61# With this, it'll be possible to look up whether columns in the new table (year to add) have to be transformed into '_OMS'.
62cur.execute("""
63DROP TABLE IF EXISTS _rws_references;
64CREATE TABLE _rws_references AS
65SELECT column_name, table_name FROM INFORMATION_SCHEMA.columns
66WHERE table_name LIKE '%.txt.csv'
67AND (column_name LIKE '%\_ID' OR column_name LIKE '%\_CODE');
68""")
69
70# Selects all columns from new table that end in '_ID' or '_CODE', and outputs it into a Python list
71cur.execute("""
72DROP TABLE IF EXISTS _rws_columns_to_convert;
73CREATE TABLE _rws_columns_to_convert AS
74SELECT column_name FROM INFORMATION_SCHEMA.columns
75WHERE table_name LIKE (SELECT _rws_settings.year_filename FROM _rws_settings)
76AND (column_name LIKE '%\_ID' OR column_name LIKE '%\_CODE');
77""")
78
79# Makes a list on what columns need to be converted with a reference table
80cur.execute("""
81SELECT _rws_columns_to_convert."column_name" FROM _rws_columns_to_convert;
82""")
83list_to_convert = cur.fetchall()
84# removes '(' and '),'
85list_to_convert = [i[0] for i in list_to_convert]
86# List of column names that do end in _ID or _CODE, but should not be converted (checked manually)
87columns_not_to_convert = ['JTE_ID', 'WVK_ID', 'GME_ID', 'PVE_CODE', 'WSE_ID']
88
89# Loop to check if the name should not have a conversion to _OMS, and remove them from the conversion list that will be iterated through (not the table in pgAdmin)
90for name in columns_not_to_convert:
91 if name in list_to_convert:
92 list_to_convert.remove(name)
93print(list_to_convert)
94
95# Query for the loop, selects the correct reference table based on the iteration
96get_table_name_query = """
97SELECT table_name from _rws_references WHERE column_name = '{0}'
98"""
99
100# List of tables that have ID/CODE to convert to OMS ["ongevallen_2016.csv", "ongevallen_2017.csv"]
101# create a temporary data table and fill it with the old data
102tables = ["ongevallen_2016.csv"]
103all_data = cur.execute("""
104DROP TABLE IF EXISTS _rws_all_temp;
105CREATE TABLE _rws_all_temp AS SELECT * FROM (SELECT _rws_settings.old_data FROM _rws_settings) AS derived_temp
106""")
107
108# VKL_NUMMER <--- ID for rows
109# Function to print some messages for easy debug
110def run_query(query):
111 if(DEBUG):
112 print(query)
113 cur.execute(query)
114
115# Function to make a copy of the table to edit in
116def copy_table(table_name):
117 copy_table_query = """
118 DROP TABLE IF EXISTS "{0}_copy";
119 CREATE TABLE "{0}_copy" AS
120 SELECT * FROM "{0}"
121 """.format(table_name)
122
123 run_query(copy_table_query)
124
125# Function to add a column to a table
126def add_column(table_name, column_name, datatype):
127 add_column_query = """
128 ALTER TABLE "{0}"
129 ADD COLUMN "{1}" {2};
130 """.format(table_name, column_name, datatype)
131
132 run_query(add_column_query)
133
134# Runs the function to copy the table mentioned in the variable tables (list)
135for table in tables:
136 copy_table(table)
137
138
139# Function that converts _ID or _CODE into _OMS
140# 0= data table (2016 for example) - table_to_convert
141# 1= the reference table
142# 2=item name, iterable (_ID or _CODE)
143# 3=item name (but the _OMS version, needs function turn_id_or_code_into_oms)
144def run_queries(table_to_convert, from_table, item_name, item_oms):
145
146 add_column(table_to_convert, item_oms, "VARCHAR")
147
148 grab_oms_query = """
149 DROP TABLE IF EXISTS "{3}_temp";
150 CREATE TABLE "{3}_temp" AS
151 SELECT "{0}"."VKL_NUMMER", "{0}"."{2}", oms_table."{3}"
152 FROM "{0}"
153 LEFT JOIN "{1}" as oms_table
154 ON CAST("{0}"."{2}" AS VARCHAR) = CAST(oms_table."{2}" AS VARCHAR);
155 """.format(table_to_convert, from_table, item_name, item_oms)
156
157 fill_oms_column_query = """
158 UPDATE "{0}"
159 SET "{1}" = "{1}_temp"."{1}"
160 FROM "{1}_temp"
161 WHERE "{0}"."VKL_NUMMER" = "{1}_temp"."VKL_NUMMER"
162 """.format(table_to_convert, item_oms)
163
164 drop_temp_table_query = """
165 DROP TABLE IF EXISTS "{0}";
166 """.format(item_oms + "_temp")
167
168 run_query(grab_oms_query)
169 run_query(fill_oms_column_query)
170 run_query(drop_temp_table_query)
171
172
173# changes extension _ID and _CODE into _OMS (for easy lookup in reference table)
174def turn_id_or_code_into_oms(name):
175 if "_CODE" in name:
176 if name == "DAG_CODE" or name == "PVE_CODE":
177 return name.replace("_CODE", "_NAAM")
178 else:
179 return name.replace("_CODE", "_OMS")
180 else:
181 return name.replace("_ID", "_OMS")
182
183# Get list with column names from original datafile
184cur.execute("""
185SELECT _rws_datatypes."column_name" FROM _rws_datatypes;
186""")
187columns_for_union = cur.fetchall()
188# Removes '(' and '),'
189columns_for_union = [i[0] for i in columns_for_union]
190
191# Loop through all the tables and convertable items, find all reference tables and start function run_queries
192for table in tables:
193 table_copy = table + "_copy"
194 for item in list_to_convert:
195 print("PROCESSING: " + table + " - item: " + item)
196 cur.execute(get_table_name_query.format(item))
197 from_table = cur.fetchone()[0]
198 run_queries(table_copy, from_table, item, turn_id_or_code_into_oms(item))
199
200 # Get list with column names from new year datafile
201 columns_in_new_data = cur.execute("""
202 SELECT column_name FROM INFORMATION_SCHEMA.columns
203 WHERE table_name = '{0}';
204 """.format(table_copy))
205 # Removes '(' and '),'
206 columns_in_new_data = cur.fetchall()
207 columns_in_new_data = [i[0] for i in columns_in_new_data]
208 print('2016:', columns_in_new_data)
209
210 for column_name in columns_for_union:
211 # If column exists in original datafile, but not in new datafile: add column with correct datatype
212 if column_name not in columns_in_new_data:
213 datatype_column = cur.execute("""SELECT data_type FROM _rws_datatypes WHERE column_name = '{0}'""".format(column_name))
214 datatype_column = cur.fetchone()
215 datatype_column = datatype_column[0]
216 print(datatype_column)
217 cur.execute("""
218 ALTER TABLE "{0}"
219 ADD COLUMN "{1}" {2};
220 """.format(table_copy, column_name, datatype_column))
221# If column name exists in new datafile, but not in original datafile: drop column
222 for column_name in columns_in_new_data:
223 if column_name not in columns_for_union:
224 cur.execute("""
225 ALTER TABLE "{0}"
226 DROP COLUMN "{1}";
227 """.format(table_copy, column_name))
228
229# If data column in new data is completely empty and exists in the original datafile, cast the correct datatype on it
230# check if column = null
231# pg_stats n_distinct per column <= 1
232# SELECT attname, n_distinct
233# FROM pg_stats
234# WHERE n_distinct <= 1
235# AND tablename = 'ongevallen_2016.csv'
236
237
238
239#for table in tables:
240# cur.execute("""
241# SELECT attname
242# FROM pg_stats
243# WHERE n_distinct <= 1
244# AND tablename = '{0}';
245# """.format(table_copy))
246
247# found_empty_tables = cur.fetchall()
248# found_empty_tables = [i[0] for i in found_empty_tables]
249# print(found_empty_tables)
250
251 cur.execute("""SELECT column_name FROM _rws_datatypes""")
252 all_columns = cur.fetchall()
253 all_columns = [i[0] for i in all_columns]
254
255 for column_name in all_columns:
256 wanted_datatype = cur.execute("""SELECT data_type FROM _rws_datatypes WHERE column_name = '{0}'""".format(column_name))
257 wanted_datatype = cur.fetchone()
258 wanted_datatype = wanted_datatype[0]
259 print("column name: ", column_name, "datatype: ", wanted_datatype)
260 current_datatype = cur.execute("""SELECT data_type FROM INFORMATION_SCHEMA.columns WHERE table_name = '{0}' AND column_name = '{1}';""".format(table_copy, column_name))
261 current_datatype = cur.fetchone()
262 current_datatype = current_datatype[0]
263 print('current: ', current_datatype, 'wanted: ', wanted_datatype)
264
265 if current_datatype != wanted_datatype and current_datatype == 'character varying':
266 cur.execute("""UPDATE "{0}" SET "{1}" = NULL WHERE "{1}" = '';""".format(table_copy, column_name))
267 cur.execute("""
268 ALTER TABLE "{0}"
269 ALTER COLUMN "{1}" TYPE {2} USING "{1}"::{2};
270 """.format(table_copy, column_name, wanted_datatype))
271 elif current_datatype != wanted_datatype and current_datatype != 'character varying':
272 cur.execute("""
273 ALTER TABLE "{0}"
274 ALTER COLUMN "{1}" TYPE {2} USING "{1}"::{2};
275 """.format(table_copy, column_name, wanted_datatype))
276
277
278# Union old and new data
279 cur.execute("""
280 DROP TABLE IF EXISTS _all_data;
281 CREATE TABLE _all_data AS
282 SELECT * FROM "{0}"
283 UNION
284 SELECT * FROM "{1}";
285 """.format(table, table_copy))
286
287# --- TO DO
288#BZD_ID_IF1 -> BZD_IF1_OMS inbouwen
289#union old and new data: What if there are two or more tables to union?
290#create index? aliases?
291# create linking tables (maybe other script)
292# make it work with partij
293# make it work with voertuig
294# make it work with slachtoffer
295# restructure for better readability
296
297# --- FINISH UP RUNNING THE SCRIPT
298# Make the changes to the database persistent
299conn.commit()
300
301# Close communication with the database
302cur.close()
303conn.close()