Create table if needed
()
| 162 | |
| 163 | |
| 164 | def _create_table(): |
| 165 | """ |
| 166 | Create table if needed |
| 167 | """ |
| 168 | # Explicitly check if the table already exists as the library logs a |
| 169 | # warning on CREATE TABLE |
| 170 | query = """SELECT COUNT(TABLE_NAME) FROM information_schema.tables |
| 171 | WHERE table_schema = %s AND table_name = %s""" |
| 172 | cur, _ = run_query( |
| 173 | __context__.get("mysql_client"), |
| 174 | query, |
| 175 | args=(__context__["mysql_kwargs"]["db"], __context__["mysql_table_name"]), |
| 176 | ) |
| 177 | r = cur.fetchone() |
| 178 | cur.close() |
| 179 | if r[0] == 1: |
| 180 | query = """ |
| 181 | SELECT COUNT(TABLE_NAME) |
| 182 | FROM |
| 183 | information_schema.columns |
| 184 | WHERE |
| 185 | table_schema = %s |
| 186 | AND table_name = %s |
| 187 | AND column_name = 'last_update' |
| 188 | """ |
| 189 | cur, _ = run_query( |
| 190 | __context__["mysql_client"], |
| 191 | query, |
| 192 | args=(__context__["mysql_kwargs"]["db"], __context__["mysql_table_name"]), |
| 193 | ) |
| 194 | r = cur.fetchone() |
| 195 | cur.close() |
| 196 | if r[0] == 1: |
| 197 | return |
| 198 | else: |
| 199 | query = """ |
| 200 | ALTER TABLE {}.{} |
| 201 | ADD COLUMN last_update TIMESTAMP NOT NULL |
| 202 | DEFAULT CURRENT_TIMESTAMP |
| 203 | ON UPDATE CURRENT_TIMESTAMP |
| 204 | """.format( |
| 205 | __context__["mysql_kwargs"]["db"], __context__["mysql_table_name"] |
| 206 | ) |
| 207 | cur, _ = run_query(__context__["mysql_client"], query) |
| 208 | cur.close() |
| 209 | return |
| 210 | |
| 211 | query = """CREATE TABLE IF NOT EXISTS {} ( |
| 212 | bank CHAR(255), |
| 213 | etcd_key CHAR(255), |
| 214 | data MEDIUMBLOB, |
| 215 | last_update TIMESTAMP NOT NULL |
| 216 | DEFAULT CURRENT_TIMESTAMP |
| 217 | ON UPDATE CURRENT_TIMESTAMP, |
| 218 | PRIMARY KEY(bank, etcd_key) |
| 219 | );""".format( |
| 220 | __context__["mysql_table_name"] |
| 221 | ) |