db_utils.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import operator
  17. from functools import reduce
  18. from typing import Dict, Type, Union
  19. from fate_arch.common.base_utils import current_timestamp, timestamp_to_date
  20. from fate_flow.db.db_models import DB, DataBaseModel
  21. from fate_flow.db.runtime_config import RuntimeConfig
  22. from fate_flow.utils.log_utils import getLogger
  23. LOGGER = getLogger()
  24. @DB.connection_context()
  25. def bulk_insert_into_db(model, data_source, replace_on_conflict=False):
  26. DB.create_tables([model])
  27. current_time = current_timestamp()
  28. current_date = timestamp_to_date(current_time)
  29. for data in data_source:
  30. if 'f_create_time' not in data:
  31. data['f_create_time'] = current_time
  32. data['f_create_date'] = timestamp_to_date(data['f_create_time'])
  33. data['f_update_time'] = current_time
  34. data['f_update_date'] = current_date
  35. preserve = tuple(data_source[0].keys() - {'f_create_time', 'f_create_date'})
  36. batch_size = 50 if RuntimeConfig.USE_LOCAL_DATABASE else 1000
  37. for i in range(0, len(data_source), batch_size):
  38. with DB.atomic():
  39. query = model.insert_many(data_source[i:i + batch_size])
  40. if replace_on_conflict:
  41. query = query.on_conflict(preserve=preserve)
  42. query.execute()
  43. def get_dynamic_db_model(base, job_id):
  44. return type(base.model(table_index=get_dynamic_tracking_table_index(job_id=job_id)))
  45. def get_dynamic_tracking_table_index(job_id):
  46. return job_id[:8]
  47. def fill_db_model_object(model_object, human_model_dict):
  48. for k, v in human_model_dict.items():
  49. attr_name = 'f_%s' % k
  50. if hasattr(model_object.__class__, attr_name):
  51. setattr(model_object, attr_name, v)
  52. return model_object
  53. # https://docs.peewee-orm.com/en/latest/peewee/query_operators.html
  54. supported_operators = {
  55. '==': operator.eq,
  56. '<': operator.lt,
  57. '<=': operator.le,
  58. '>': operator.gt,
  59. '>=': operator.ge,
  60. '!=': operator.ne,
  61. '<<': operator.lshift,
  62. '>>': operator.rshift,
  63. '%': operator.mod,
  64. '**': operator.pow,
  65. '^': operator.xor,
  66. '~': operator.inv,
  67. }
  68. '''
  69. query = {
  70. # Job.f_job_id == '1234567890'
  71. 'job_id': '1234567890',
  72. # Job.f_party_id == 999
  73. 'party_id': 999,
  74. # Job.f_tag != 'submit_failed'
  75. 'tag': ('!=', 'submit_failed'),
  76. # Job.f_status.in_(['success', 'running', 'waiting'])
  77. 'status': ('in_', ['success', 'running', 'waiting']),
  78. # Job.f_create_time.between(10000, 99999)
  79. 'create_time': ('between', 10000, 99999),
  80. # Job.f_description.distinct()
  81. 'description': ('distinct', ),
  82. }
  83. '''
  84. def query_dict2expression(model: Type[DataBaseModel], query: Dict[str, Union[bool, int, str, list, tuple]]):
  85. expression = []
  86. for field, value in query.items():
  87. if not isinstance(value, (list, tuple)):
  88. value = ('==', value)
  89. op, *val = value
  90. field = getattr(model, f'f_{field}')
  91. value = supported_operators[op](field, val[0]) if op in supported_operators else getattr(field, op)(*val)
  92. expression.append(value)
  93. return reduce(operator.iand, expression)
  94. def query_db(model: Type[DataBaseModel], limit: int = 0, offset: int = 0,
  95. query: dict = None, order_by: Union[str, list, tuple] = None):
  96. data = model.select()
  97. if query:
  98. data = data.where(query_dict2expression(model, query))
  99. count = data.count()
  100. if not order_by:
  101. order_by = 'create_time'
  102. if not isinstance(order_by, (list, tuple)):
  103. order_by = (order_by, 'asc')
  104. order_by, order = order_by
  105. order_by = getattr(model, f'f_{order_by}')
  106. order_by = getattr(order_by, order)()
  107. data = data.order_by(order_by)
  108. if limit > 0:
  109. data = data.limit(limit)
  110. if offset > 0:
  111. data = data.offset(offset)
  112. return list(data), count