Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mysql.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. # -*- coding: utf-8 -*-
  2. import copy
  3. import pymysql
  4. import EditorialModel
  5. # The global MH algorithm is as follow :
  6. # A create_table(table_name, pk_name, pk_opt) method that create a table
  7. # with one pk field
  8. # An add_column(table_name, field_name, field_opt) method that add a column to a table
  9. #
  10. # The create_default_table method will call both methods to create the object and relation tables
  11. #
  12. # Supported operations :
  13. # - EmClass creation
  14. # - EmClass deletion (untested)
  15. # - EmField creation
  16. # - EmField deletion (untested)
  17. # - rel2type attribute creation
  18. # - rel2type attribute deletion (unstested)
  19. #
  20. # Unsupported operations :
  21. # - EmClass rename
  22. # - EmField rename
  23. # - rel2type field rename
  24. # - rel2type attribute rename
  25. #
  26. ## @brief Modify a MySQL database given editorial model changes
  27. class MysqlMigrationHandler(EditorialModel.migrationhandler.dummy.DummyMigrationHandler):
  28. ## @brief Object table name
  29. _object_tname = 'object'
  30. ## @brief Relation table name
  31. _relation_tname = 'relation'
  32. ## @brief Construct a MysqlMigrationHandler
  33. # @param host str : The db host
  34. # @param user str : The db user
  35. # @param password str : The db password
  36. # @param db str : The db name
  37. def __init__(self, host, user, password, db, db_engine = 'InnoDB', foreign_keys = True, debug = False, dryrun = False, drop_if_exists = False):
  38. #Connect to MySQL
  39. self.db = pymysql.connect(host=host, user=user, passwd=password, db=db)
  40. self.debug = debug
  41. self.dryrun = dryrun
  42. self.db_engine = db_engine
  43. self.foreign_keys = foreign_keys if db_engine == 'InnoDB' else False
  44. self.drop_if_exists = drop_if_exists
  45. #Create default tables
  46. self._create_default_tables(self.drop_if_exists)
  47. pass
  48. ## @brief Modify the db given an EM change
  49. def register_change(self, em, uid, initial_state, new_state, engine = None):
  50. if engine is None:
  51. engine = self.db_engine
  52. if isinstance(em.component(uid), EditorialModel.classes.EmClass):
  53. if initial_state is None:
  54. #EmClass creation
  55. self.create_emclass_table(em, uid, engine)
  56. elif new_state is None:
  57. #EmClass deletion
  58. self.delete_emclass_table(em, uid)
  59. elif isinstance(em.component(uid), EditorialModel.fields.EmField):
  60. emfield = em.component(uid)
  61. if emfield.rel_field_id is None:
  62. #non rlationnal field
  63. if initial_state is None:
  64. #non relationnal EmField creation
  65. if not(emfield.name in EditorialModel.classtypes.common_fields.keys()):
  66. self.add_col_from_emfield(em,uid)
  67. elif new_state is None:
  68. #non relationnal EmField deletion
  69. if not (emfield.name in EditorialModel.classtypes.common_fields.keys()):
  70. self.del_col_from_emfield(em, uid)
  71. else:
  72. #relationnal field
  73. if initial_state is None:
  74. #Rel2type attr creation
  75. self.add_relationnal_field(em, uid)
  76. elif new_state is None:
  77. #Rel2type attr deletion
  78. self.del_relationnal_field(em, uid)
  79. ## @brief dumdumdummy
  80. def register_model_state(self, em, state_hash):
  81. pass
  82. ## @brief Exec a query
  83. def _query(self, query):
  84. if self.debug:
  85. print(query+"\n")
  86. if not self.dryrun:
  87. with self.db.cursor() as cur:
  88. cur.execute(query)
  89. self.db.commit() #autocommit
  90. ## @brief Add a relationnal field
  91. #
  92. # Add a rel2type attribute
  93. # @note this function handles the table creation
  94. # @param em Model : EditorialModel.model.Model instance
  95. # @param rfuid int : Relationnal field uid
  96. def add_relationnal_field(self, em, rfuid):
  97. emfield = em.component(rfuid)
  98. if not isinstance(emfield, EditorialModel.fields.EmField):
  99. raise ValueError("The given uid is not an EmField uid")
  100. r2tf = em.component(emfield.rel_field_id)
  101. tname = self._r2t2table_name(em, r2tf)
  102. pkname, pkftype = self._relation_pk
  103. #If not exists create a relational table
  104. self._create_table(tname, pkname, pkftype, self.db_engine, if_exists = 'nothing')
  105. #Add a foreign key if wanted
  106. if self.foreign_keys:
  107. self._add_fk(tname, self._relation_tname, pkname, pkname)
  108. #Add the column
  109. self._add_column(tname, emfield.name, emfield.fieldtype_instance())
  110. #Update table triggers
  111. self._generate_triggers(tname, self._r2type2cols(em, r2tf))
  112. ## @brief Delete a rel2type attribute
  113. #
  114. # Delete a rel2type attribute
  115. # @note this method handles the table deletion
  116. # @param em Model : EditorialModel.model.Model instance
  117. # @param rfuid int : Relationnal field uid
  118. def del_relationnal_field(self, em, rfuid):
  119. emfield = em.component(rfuid)
  120. if not isinstance(emfield, EditorialModel.fields.EmField):
  121. raise ValueError("The given uid is not an EmField uid")
  122. r2tf = em.component(emfield.rel_field_id)
  123. tname = self._r2t2table_name(em, r2tf)
  124. if len(self._r2type2cols(em, r2tf)) == 1:
  125. #The table can be deleted (no more attribute for this rel2type)
  126. self._query("""DROP TABLE {table_name}""".format(table_name = tname))
  127. else:
  128. self._del_column(tname, emfield.name)
  129. #Update table triggers
  130. self._generate_triggers(tname, self._r2type2cols(em, r2tf))
  131. ## @brief Given an EmField uid add a column to the corresponding table
  132. # @param em Model : A Model instance
  133. # @param uid int : An EmField uid
  134. # @return None
  135. def add_col_from_emfield(self, em, uid):
  136. emfield = em.component(uid)
  137. if not isinstance(emfield, EditorialModel.fields.EmField):
  138. raise ValueError("The given uid is not an EmField uid")
  139. emclass = emfield.em_class
  140. tname = self._emclass2table_name(emclass)
  141. self._add_column(tname, emfield.name, emfield.fieldtype_instance())
  142. # Refresh the table triggers
  143. cols_l = self._class2cols(emclass)
  144. self._generate_triggers(tname, cols_l)
  145. ## @brief Given a class uid create the coressponding table
  146. def create_emclass_table(self, em, uid, engine):
  147. emclass = em.component(uid)
  148. if not isinstance(emclass, EditorialModel.classes.EmClass):
  149. raise ValueError("The given uid is not an EmClass uid")
  150. pkname, pktype = self._common_field_pk
  151. table_name = self._emclass2table_name(emclass)
  152. self._create_table(table_name, pkname, pktype, engine=engine)
  153. if self.foreign_keys:
  154. self._add_fk(table_name, self._object_tname, pkname, pkname)
  155. ## @brief Given an EmClass uid delete the corresponding table
  156. def delete_emclass_table(self, em, uid):
  157. emclass = emcomponent(uid)
  158. if not isinstance(emclass, EditorialModel.classes.EmClass):
  159. raise ValueError("The give uid is not an EmClass uid")
  160. tname = self._idname_escape(self._emclass2table_name(emclass.name))
  161. # Delete the table triggers to prevent errors
  162. self._generate_triggers(tname, dict())
  163. self._query("""DROP TABLE {table_name};""".format(table_name = tname))
  164. ## @brief Given an EmField delete the corresponding column
  165. # @param em Model : an @ref EditorialModel.model.Model instance
  166. # @param uid int : an EmField uid
  167. def delete_col_from_emfield(self, em, uid):
  168. emfield = em.component(uid)
  169. if not isinstance(emfield, EditorialModel.fields.EmField):
  170. raise ValueError("The given uid is not an EmField uid")
  171. emclass = emfield.em_class
  172. tname = self._emclass2table_name(emclass)
  173. # Delete the table triggers to prevent errors
  174. self._generate_triggers(tname, dict())
  175. self._del_column(tname, emfield.name)
  176. # Refresh the table triggers
  177. cols_ls = self._class2cols(emclass)
  178. self._generate_triggers(tname, cols_l)
  179. ## @brief Delete a column from a table
  180. # @param tname str : The table name
  181. # @param fname str : The column name
  182. def _del_column(self, tname, fname):
  183. tname = self._idname_escape(tname)
  184. fname = self._idname_escape(fname)
  185. self._query("""ALTER TABLE {table_name} DROP COLUMN {col_name};""".format(table_name = tname, col_name = fname))
  186. ## @brief Construct a table name given an EmClass instance
  187. # @param emclass EmClass : An EmClass instance
  188. # @return a table name
  189. def _emclass2table_name(self, emclass):
  190. return "class_%s"%emclass.name
  191. ## @brief Construct a table name given a rela2type EmField instance
  192. # @param em Model : A Model instance
  193. # @param emfield EmField : An EmField instance
  194. # @return a table name
  195. def _r2t2table_name(self, em, emfield):
  196. emclass = emfield.em_class
  197. emtype = em.component(emfield.rel_to_type_id)
  198. return "%s_%s_%s"%(emclass.name, emtype.name, emfield.name)
  199. ## @brief Generate a columns_fieldtype dict given a rel2type EmField
  200. # @param em Model : an @ref EditorialModel.model.Model instance
  201. # @param emfield EmField : and @ref EditorialModel.fields.EmField instance
  202. def _r2type2cols(self, em, emfield):
  203. return { f.name: f.fieldtype_instance() for f in em.components('EmField') if f.rel_field_id == emfield.uid }
  204. ## @brief Generate a columns_fieldtype dict given an EmClass
  205. # @param emclass EmClass : An EmClass instance
  206. # @return A dict with column name as key and EmFieldType instance as value
  207. def _class2cols(self, emclass):
  208. if not isinstance(emclass, EditorialModel.classes.EmClass):
  209. raise ValueError("The given uid is not an EmClass uid")
  210. return { f.name: f.fieldtype_instance() for f in emclass.fields() }
  211. ## @brief Create object and relations tables
  212. # @param drop_if_exist bool : If true drop tables if exists
  213. def _create_default_tables(self, drop_if_exist = False):
  214. if_exists = 'drop' if drop_if_exist else 'nothing'
  215. #Object tablea
  216. tname = self._object_tname
  217. pk_name, pk_ftype = self._common_field_pk
  218. self._create_table(tname, pk_name, pk_ftype, engine=self.db_engine, if_exists = if_exists)
  219. #Adding columns
  220. cols = { fname: self._common_field_to_ftype(fname) for fname in EditorialModel.classtypes.common_fields }
  221. for fname, ftype in cols.items():
  222. if fname != pk_name:
  223. self._add_column(tname, fname, ftype)
  224. #Creating triggers
  225. self._generate_triggers(tname, cols)
  226. #Relation table
  227. tname = self._relation_tname
  228. pk_name, pk_ftype = self._relation_pk
  229. self._create_table(tname, pk_name, pk_ftype, engine = self.db_engine, if_exists = if_exists)
  230. #Adding columns
  231. for fname, ftype in self._relation_cols.items():
  232. self._add_column(tname, fname, ftype)
  233. #Creating triggers
  234. self._generate_triggers(tname, self._relation_cols)
  235. ## @return true if the name changes
  236. def _name_change(self, initial_state, new_state):
  237. return 'name' in initial_state and initial_state['name'] != new_state['name']
  238. ## @brief Create a table with primary key
  239. # @param table_name str : table name
  240. # @param pk_name str : pk column name
  241. # @param pk_specs str : see @ref _field_to_sql()
  242. # @param engine str : The engine to use with this table
  243. # @param charset str : The charset of this table
  244. # @param if_exist str : takes values in ['nothing', 'drop']
  245. # @return None
  246. def _create_table(self, table_name, pk_name, pk_ftype, engine, charset = 'utf8', if_exists = 'nothing'):
  247. #Escaped table name
  248. etname = self._idname_escape(table_name)
  249. pk_type = self._field_to_type(pk_ftype)
  250. pk_specs = self._field_to_specs(pk_ftype)
  251. if if_exists == 'drop':
  252. self._query("""DROP TABLE IF EXISTS {table_name};""".format(table_name = etname))
  253. qres = """
  254. CREATE TABLE {table_name} (
  255. {pk_name} {pk_type} {pk_specs},
  256. PRIMARY KEY({pk_name})
  257. ) ENGINE={engine} DEFAULT CHARSET={charset};"""
  258. elif if_exists == 'nothing':
  259. qres = """CREATE TABLE IF NOT EXISTS {table_name} (
  260. {pk_name} {pk_type} {pk_specs},
  261. PRIMARY KEY({pk_name})
  262. ) ENGINE={engine} DEFAULT CHARSET={charset};"""
  263. else:
  264. raise ValueError("Unexpected value for argument if_exists '%s'."%if_exists)
  265. self._query(qres.format(
  266. table_name = self._idname_escape(table_name),
  267. pk_name = self._idname_escape(pk_name),
  268. pk_type = pk_type,
  269. pk_specs = pk_specs,
  270. engine = engine,
  271. charset = charset
  272. ))
  273. ## @brief Add a column to a table
  274. # @param table_name str : The table name
  275. # @param col_name str : The columns name
  276. # @param col_fieldtype EmFieldype the fieldtype
  277. # @return None
  278. def _add_column(self, table_name, col_name, col_fieldtype, drop_if_exists = False):
  279. add_col = """ALTER TABLE {table_name}
  280. ADD COLUMN {col_name} {col_type} {col_specs};"""
  281. etname = self._idname_escape(table_name)
  282. ecname = self._idname_escape(col_name)
  283. add_col = add_col.format(
  284. table_name = etname,
  285. col_name = ecname,
  286. col_type = self._field_to_type(col_fieldtype),
  287. col_specs = self._field_to_specs(col_fieldtype),
  288. )
  289. try:
  290. self._query(add_col)
  291. except pymysql.err.InternalError as e:
  292. if drop_if_exists:
  293. self._del_column(table_name, col_name)
  294. self._add_column(table_name, col_name, col_fieldtype, drop_if_exists)
  295. else:
  296. #LOG
  297. print("Aborded, column `%s` exists"%col_name)
  298. ## @brief Add a foreign key
  299. # @param src_table_name str : The name of the table where we will add the FK
  300. # @param dst_table_name str : The name of the table the FK will point on
  301. # @param src_col_name str : The name of the concerned column in the src_table
  302. # @param dst_col_name str : The name of the concerned column in the dst_table
  303. def _add_fk(self, src_table_name, dst_table_name, src_col_name, dst_col_name):
  304. stname = self._idname_escape(src_table_name)
  305. dtname = self._idname_escape(dst_table_name)
  306. scname = self._idname_escape(src_col_name)
  307. dcname = self._idname_escape(dst_col_name)
  308. fk_name = self._fk_name(src_table_name, dst_table_name)
  309. self._del_fk(src_table_name, dst_table_name)
  310. self._query("""ALTER TABLE {src_table}
  311. ADD CONSTRAINT {fk_name}
  312. FOREIGN KEY ({src_col}) references {dst_table}({dst_col});""".format(
  313. fk_name = self._idname_escape(fk_name),
  314. src_table = stname,
  315. src_col = scname,
  316. dst_table = dtname,
  317. dst_col = dcname
  318. ))
  319. ## @brief Given a source and a destination table, delete the corresponding FK
  320. # @param src_table_name str : The name of the table where the FK is
  321. # @param dst_table_name str : The name of the table the FK point on
  322. # @warning fails silently
  323. def _del_fk(self, src_table_name, dst_table_name):
  324. try:
  325. self._query("""ALTER TABLE {src_table}
  326. DROP FOREIGN KEY {fk_name}""".format(
  327. src_table = self._idname_escape(src_table_name),
  328. fk_name = self._idname_escape(self._fk_name(src_table_name, dst_table_name))
  329. ))
  330. except pymysql.err.InternalError: pass
  331. def _fk_name(self, src_table_name, dst_table_name):
  332. return "fk_%s_%s"%(src_table_name, dst_table_name)
  333. ## @brief Generate triggers given a table_name and its columns fieldtypes
  334. # @param table_name str : Table name
  335. # @param cols_ftype dict : with col name as key and column fieldtype as value
  336. # @return None
  337. def _generate_triggers(self, table_name, cols_ftype):
  338. colval_l_upd = dict() #param for update trigger
  339. colval_l_ins = dict() #param for insert trigger
  340. for cname, cftype in cols_ftype.items():
  341. if cftype.ftype == 'datetime':
  342. if cftype.now_on_update:
  343. colval_l_upd[cname] = 'NOW()'
  344. if cftype.now_on_create:
  345. colval_l_ins[cname] = 'NOW()'
  346. self._table_trigger(table_name, 'UPDATE', colval_l_upd)
  347. self._table_trigger(table_name, 'INSERT', colval_l_ins)
  348. ## @brief Create trigger for a table
  349. #
  350. # Primarly designed to create trigger for DATETIME types
  351. # The method generates triggers of the form
  352. #
  353. # CREATE TRIGGER BEFORE <moment> ON <table_name>
  354. # FOR EACH ROW SET <for colname, colval in cols_val>
  355. # NEW.<colname> = <colval>,
  356. # <endfor>;
  357. # @param table_name str : The table name
  358. # @param moment str : can be 'update' or 'insert'
  359. # @param cols_val dict : Dict with column name as key and column value as value
  360. # @return None
  361. def _table_trigger(self, table_name, moment, cols_val):
  362. trigger_name = self._idname_escape("%s_%s_trig"%(table_name, moment))
  363. #Try to delete the trigger
  364. drop_trig = """DROP TRIGGER IF EXISTS {trigger_name};""".format(trigger_name = trigger_name)
  365. self._query(drop_trig)
  366. col_val_l = ', '.join([ "NEW.%s = %s"%(self._idname_escape(cname), cval)for cname, cval in cols_val.items() ])
  367. #Create a trigger if needed
  368. if len(col_val_l) > 0:
  369. trig_q = """CREATE TRIGGER {trigger_name} BEFORE {moment} ON {table_name}
  370. FOR EACH ROW SET {col_val_list};""".format(
  371. trigger_name = trigger_name,
  372. table_name = self._idname_escape(table_name),
  373. moment = moment,
  374. col_val_list = col_val_l
  375. )
  376. self._query(trig_q)
  377. ## @brief Identifier escaping
  378. # @param idname str : An SQL identifier
  379. def _idname_escape(self, idname):
  380. if '`' in idname:
  381. raise ValueError("Invalid name : '%s'"%idname)
  382. return '`%s`'%idname
  383. ## @brief Returns column specs from fieldtype
  384. # @param emfieldtype EmFieldType : An EmFieldType insance
  385. # @todo escape default value
  386. def _field_to_specs(self, emfieldtype):
  387. colspec = ''
  388. if not emfieldtype.nullable:
  389. colspec = 'NOT NULL'
  390. if hasattr(emfieldtype, 'default'):
  391. colspec += ' DEFAULT '
  392. if emfieldtype.default is None:
  393. colspec += 'NULL '
  394. else:
  395. colspec += emfieldtype.default #ESCAPE VALUE HERE !!!!
  396. if emfieldtype.name == 'pk':
  397. colspec += ' AUTO_INCREMENT'
  398. return colspec
  399. ## @brief Given a fieldtype return a MySQL type specifier
  400. # @param emfieldtype EmFieldType : A fieldtype
  401. # @return the corresponding MySQL type
  402. def _field_to_type(self, emfieldtype):
  403. ftype = emfieldtype.ftype
  404. if ftype == 'char' or ftype == 'str':
  405. res = "VARCHAR(%d)"%emfieldtype.max_length
  406. elif ftype == 'text':
  407. res = "TEXT"
  408. elif ftype == 'datetime':
  409. res = "DATETIME"
  410. # client side workaround for only one column with CURRENT_TIMESTAMP : giving NULL to timestamp that don't allows NULL
  411. # cf. https://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html#idm139961275230400
  412. # The solution for the migration handler is to create triggers :
  413. # CREATE TRIGGER trigger_name BEFORE INSERT ON `my_super_table`
  414. # FOR EACH ROW SET NEW.my_date_column = NOW();
  415. # and
  416. # CREATE TRIGGER trigger_name BEFORE UPDATE ON
  417. elif ftype == 'bool':
  418. res = "BOOL"
  419. elif ftype == 'int':
  420. res = "INT"
  421. elif ftype == 'rel2type':
  422. res = "INT"
  423. else:
  424. raise ValueError("Unsuported fieldtype ftype : %s"%ftype)
  425. return res
  426. ## @brief Returns a tuple (pkname, pk_ftype)
  427. @property
  428. def _common_field_pk(self):
  429. for fname, fta in EditorialModel.classtypes.common_fields.items():
  430. if fta['fieldtype'] == 'pk':
  431. return (fname, self._common_field_to_ftype(fname))
  432. return (None, None)
  433. ## @brief Returns a tuple (rel_pkname, rel_ftype)
  434. # @todo do it
  435. @property
  436. def _relation_pk(self):
  437. return ('id_relation', EditorialModel.fieldtypes.pk.EmFieldType())
  438. ## @brief Returns a dict { colname:fieldtype } of relation table columns
  439. @property
  440. def _relation_cols(self):
  441. from_name = EditorialModel.fieldtypes.generic.GenericFieldType.from_name
  442. return {
  443. 'id_sup': from_name('integer')(),
  444. 'id_sub': from_name('integer')(),
  445. 'rank': from_name('integer')(),
  446. 'depth': from_name('integer')(),
  447. 'nature': from_name('char')(max_lenght=10),
  448. }
  449. ## @brief Given a common field name return an EmFieldType instance
  450. # @param cname str : Common field name
  451. # @return An EmFieldType instance
  452. def _common_field_to_ftype(self, cname):
  453. fta = copy.copy(EditorialModel.classtypes.common_fields[cname])
  454. fto = EditorialModel.fieldtypes.generic.GenericFieldType.from_name(fta['fieldtype'])
  455. del(fta['fieldtype'])
  456. return fto(**fta)