Brak opisu
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.

ledatasourcesql.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #-*- coding: utf-8 -*-
  2. import pymysql
  3. from leobject.datasources.dummy import DummyDatasource
  4. from leobject.leobject import REL_SUB, REL_SUP
  5. from mosql.db import Database, all_to_dicts
  6. from mosql.query import select, insert, update, delete, join
  7. from mosql.util import raw
  8. import mosql.mysql
  9. ## MySQL DataSource for LeObject
  10. class LeDataSourceSQL(DummyDatasource):
  11. RELATIONS_TABLE_NAME = 'relations'
  12. RELATIONS_POSITIONS_FIELDS = { REL_SUP: 'superior_id', REL_SUB: 'subordinate_id'}
  13. RELATIONS_NATURE_FIELD = 'nature'
  14. LODEL_ID_FIELD = 'lodel_id'
  15. CLASS_TABLE_PREFIX = 'class_'
  16. OBJECTS_TABLE_NAME = 'object'
  17. def __init__(self, module=pymysql, conn_args={'host': '127.0.0.1', 'user':'lodel', 'passwd':'bruno', 'db': 'lodel2'}):
  18. super(LeDataSourceSQL, self).__init__()
  19. self.module = module
  20. self.connection = Database(pymysql, host=conn_args['host'], user=conn_args['user'], passwd=conn_args['passwd'], db=conn_args['db'])
  21. ## @brief inserts a new object
  22. # @param letype LeType
  23. # @param leclass LeClass
  24. # @param datas dict : dictionnary of field:value pairs to save
  25. # @return int : lodel_id of the created object
  26. # @todo add the returning clause and the insertion in "object"
  27. def insert(self, letype, leclass, datas):
  28. if isinstance(datas, list):
  29. res = list()
  30. for data in datas:
  31. res.append(self.insert(letype, leclass, data))
  32. return res
  33. elif isinstance(datas, dict):
  34. with self.connection as cur:
  35. object_datas = {'class_id': leclass._class_id, 'type_id': letype._type_id}
  36. if cur.execute(insert(self.OBJECTS_TABLE_NAME, object_datas)) != 1:
  37. raise RuntimeError('SQL error')
  38. if cur.execute('SELECT last_insert_id() as lodel_id') != 1:
  39. raise RuntimeError('SQL error')
  40. lodel_id, = cur.fetchone()
  41. datas[self.LODEL_ID_FIELD] = lodel_id
  42. query_table_name = self._get_table_name_from_class_name(leclass.__name__)
  43. query = insert(query_table_name, datas)
  44. if cur.execute(query) != 1:
  45. raise RuntimeError('SQL error')
  46. return lodel_id
  47. ## @brief search for a collection of objects
  48. # @param leclass LeClass
  49. # @param letype LeType
  50. # @field_list list
  51. # @param filters list : list of tuples formatted as (FIELD, OPERATOR, VALUE)
  52. # @param relation_filters list : list of tuples formatted as (('superior'|'subordinate', FIELD), OPERATOR, VALUE)
  53. # @return list
  54. def get(self, leclass, letype, field_list, filters, relational_filters=None):
  55. query_table_name = self._get_table_name_from_class_name(leclass.__name__)
  56. where_filters = self._prepare_filters(filters, query_table_name)
  57. join_fields = {}
  58. if relational_filters is not None and len(relational_filters) > 0:
  59. rel_filters = self._prepare_rel_filters(relational_filters)
  60. for rel_filter in rel_filters:
  61. # join condition
  62. relation_table_join_field = "%s.%s" % (self.RELATIONS_TABLE_NAME, self.RELATIONS_POSITIONS_FIELDS[rel_filter['position']])
  63. query_table_join_field = "%s.%s" % (query_table_name, self.LODEL_ID_FIELD)
  64. join_fields[query_table_join_field] = relation_table_join_field
  65. # Adding "where" filters
  66. where_filters['%s.%s' % (self.RELATIONS_TABLE_NAME, self.RELATIONS_NATURE_FIELD)] = rel_filter['nature']
  67. where_filters[rel_filter['condition_key']] = rel_filter['condition_value']
  68. # building the query
  69. query = select(query_table_name, where=where_filters, select=field_list, joins=join(self.RELATIONS_TABLE_NAME, join_fields))
  70. else:
  71. query = select(query_table_name, where=where_filters, select=field_list)
  72. # Executing the query
  73. with self.connection as cur:
  74. results = all_to_dicts(cur.execute(query))
  75. return results
  76. ## @brief delete an existing object
  77. # @param letype LeType
  78. # @param leclass LeClass
  79. # @param filters list : list of tuples formatted as (FIELD, OPERATOR, VALUE)
  80. # @param relational_filters list : list of tuples formatted as (('superior'|'subordinate', FIELD), OPERATOR, VALUE)
  81. # @return bool : True on success
  82. def delete(self, letype, leclass, filters, relational_filters):
  83. query_table_name = self._get_table_name_from_class_name(leclass.__name__)
  84. prep_filters = self._prepare_filters(filters, query_table_name)
  85. prep_rel_filters = self._prepare_rel_filters(relational_filters)
  86. if len(prep_rel_filters) > 0:
  87. query = "DELETE %s FROM " % query_table_name
  88. for prep_rel_filter in prep_rel_filters:
  89. query += "%s INNER JOIN %s ON (%s.%s = %s.%s)" % (
  90. self.RELATIONS_TABLE_NAME,
  91. query_table_name,
  92. self.RELATIONS_TABLE_NAME,
  93. prep_rel_filter['position'],
  94. query_table_name,
  95. self.LODEL_ID_FIELD
  96. )
  97. if prep_rel_filter['condition_key'][0] is not None:
  98. prep_filters[("%s.%s" % (self.RELATIONS_TABLE_NAME, prep_rel_filter['condition_key'][0]), prep_rel_filter['condition_key'][1])] = prep_rel_filter['condition_value']
  99. if prep_filters is not None and len(prep_filters) > 0:
  100. query += " WHERE "
  101. filter_counter = 0
  102. for filter_item in prep_filters:
  103. if filter_counter > 1:
  104. query += " AND "
  105. query += "%s %s %s" % (filter_item[0][0], filter_item[0][1], filter_item[1])
  106. else:
  107. query = delete(query_table_name, filters)
  108. query_delete_from_object = delete(self.OBJECTS_TABLE_NAME, {'lodel_id':filters['lodel_id']})
  109. with self.connection as cur:
  110. cur.execute(query)
  111. cur.execute(query_delete_from_object)
  112. return True
  113. ## @brief update an existing object's data
  114. # @param letype LeType
  115. # @param leclass LeClass
  116. # @param filters list : list of tuples formatted as (FIELD, OPERATOR, VALUE)
  117. # @param rel_filters list : list of tuples formatted as (('superior'|'subordinate', FIELD), OPERATOR, VALUE)
  118. # @param data dict
  119. # @return bool
  120. # @todo prendre en compte les rel_filters
  121. def update(self, letype, leclass, filters, rel_filters, data):
  122. query_table_name = self._get_table_name_from_class_name(leclass.__name__)
  123. where_filters = filters
  124. set_data = data
  125. prepared_rel_filters = self._prepare_rel_filters(rel_filters)
  126. # Building the query
  127. query = update(table=query_table_name, where=where_filters, set=set_data)
  128. # Executing the query
  129. with self.connection as cur:
  130. cur.execute(query)
  131. return True
  132. ## @brief prepares the table name using a "class_" prefix
  133. # @params classname str
  134. # @return str
  135. def _get_table_name_from_class_name(self, classname):
  136. return (classname if self.CLASS_TABLE_PREFIX in classname else "%s%s" % (self.CLASS_TABLE_PREFIX, classname)).lower()
  137. ## @brief prepares the relational filters
  138. # @params rel_filters : (("superior"|"subordinate"), operator, value)
  139. # @return list
  140. def _prepare_rel_filters(self, rel_filters):
  141. prepared_rel_filters = []
  142. if rel_filters is not None and len(rel_filters) > 0:
  143. for rel_filter in rel_filters:
  144. rel_filter_dict = {
  145. 'position': REL_SUB if rel_filter[0][0] == REL_SUP else REL_SUB,
  146. 'nature': rel_filter[0][1],
  147. 'condition_key': (self.RELATIONS_POSITIONS_FIELDS[rel_filter[0][0]], rel_filter[1]),
  148. 'condition_value': rel_filter[2]
  149. }
  150. prepared_rel_filters.append(rel_filter_dict)
  151. return prepared_rel_filters
  152. ## @brief prepares the filters to be used by the mosql library's functions
  153. # @params filters : (FIELD, OPERATOR, VALUE) tuples
  154. # @return dict : Dictionnary with (FIELD, OPERATOR):VALUE style elements
  155. def _prepare_filters(self, filters, tablename=None):
  156. prepared_filters = {}
  157. if filters is not None and len(filters) > 0:
  158. for filter_item in filters:
  159. if '.' in filter_item[0]:
  160. prepared_filter_key = (filter_item[0], filter_item[1])
  161. else:
  162. prepared_filter_key = ("%s.%s" % (tablename, filter_item[0]), filter_item[1])
  163. prepared_filter_value = filter_item[2]
  164. prepared_filters[prepared_filter_key] = prepared_filter_value
  165. return prepared_filters
  166. ## @brief Link two object given a relation nature, depth and rank
  167. # @param lesup LeObject : a LeObject
  168. # @param lesub LeObject : a LeObject
  169. # @param nature str|None : The relation nature or None if rel2type
  170. # @param rank int : a rank
  171. def add_relation(self, lesup, lesub, nature=None, depth=None, rank=None, **rel_attr):
  172. if len(rel_attr) > 0 and not (nature is None):
  173. #not a rel2type but have some relation attribute
  174. raise AttributeError("No relation attributes allowed for non rel2type relations")
  175. with self.connection() as cur:
  176. sql = insert(RELATIONS_TABLE_NAME, {'id_sup':lesup.lodel_id, 'id_sub':lesub.lodel_id, 'nature':nature,'rank':rank, 'depth':depth})
  177. if cur.execute(sql) != 1:
  178. raise RuntimeError("Unknow SQL error")
  179. if len(rel_attr) > 0:
  180. #a relation table exists
  181. cur.execute('SELECT last_insert_id()')
  182. relation_id, = cur.fetchone()
  183. raise NotImplementedError()
  184. return True
  185. ## @brief Delete a link between two objects given a relation nature
  186. # @param lesup LeObject : a LeObject
  187. # @param lesub LeObject : a LeObject
  188. # @param nature str|None : The relation nature
  189. def del_relation(self, lesup, lesub, nature=None):
  190. raise NotImplementedError()
  191. ## @brief Return all relation of a lodel_id given a position and a nature
  192. # @param lodel_id int : We want the relations of this lodel_id
  193. # @param superior bool : If true search the relations where lodel_id is in id_sup
  194. # @param nature str|None : Search for relations with the given nature (if None rel2type)
  195. # @param return an array of dict with keys [ id_sup, id_sub, rank, depth, nature ]
  196. def get_relations(self, lodel_id, superior=True, nature=None):
  197. raise NotImplementedError()