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.

db_utils.py 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #
  2. # Copyright 2019 The RAG Flow 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 web_server.utils import current_timestamp, timestamp_to_date
  20. from web_server.db.db_models import DB, DataBaseModel
  21. from web_server.db.runtime_config import RuntimeConfig
  22. from web_server.utils.log_utils import getLogger
  23. from enum import Enum
  24. LOGGER = getLogger()
  25. @DB.connection_context()
  26. def bulk_insert_into_db(model, data_source, replace_on_conflict=False):
  27. DB.create_tables([model])
  28. current_time = current_timestamp()
  29. current_date = timestamp_to_date(current_time)
  30. for data in data_source:
  31. if 'f_create_time' not in data:
  32. data['f_create_time'] = current_time
  33. data['f_create_date'] = timestamp_to_date(data['f_create_time'])
  34. data['f_update_time'] = current_time
  35. data['f_update_date'] = current_date
  36. preserve = tuple(data_source[0].keys() - {'f_create_time', 'f_create_date'})
  37. batch_size = 50 if RuntimeConfig.USE_LOCAL_DATABASE else 1000
  38. for i in range(0, len(data_source), batch_size):
  39. with DB.atomic():
  40. query = model.insert_many(data_source[i:i + batch_size])
  41. if replace_on_conflict:
  42. query = query.on_conflict(preserve=preserve)
  43. query.execute()
  44. def get_dynamic_db_model(base, job_id):
  45. return type(base.model(table_index=get_dynamic_tracking_table_index(job_id=job_id)))
  46. def get_dynamic_tracking_table_index(job_id):
  47. return job_id[:8]
  48. def fill_db_model_object(model_object, human_model_dict):
  49. for k, v in human_model_dict.items():
  50. attr_name = 'f_%s' % k
  51. if hasattr(model_object.__class__, attr_name):
  52. setattr(model_object, attr_name, v)
  53. return model_object
  54. # https://docs.peewee-orm.com/en/latest/peewee/query_operators.html
  55. supported_operators = {
  56. '==': operator.eq,
  57. '<': operator.lt,
  58. '<=': operator.le,
  59. '>': operator.gt,
  60. '>=': operator.ge,
  61. '!=': operator.ne,
  62. '<<': operator.lshift,
  63. '>>': operator.rshift,
  64. '%': operator.mod,
  65. '**': operator.pow,
  66. '^': operator.xor,
  67. '~': operator.inv,
  68. }
  69. def query_dict2expression(model: Type[DataBaseModel], query: Dict[str, Union[bool, int, str, list, tuple]]):
  70. expression = []
  71. for field, value in query.items():
  72. if not isinstance(value, (list, tuple)):
  73. value = ('==', value)
  74. op, *val = value
  75. field = getattr(model, f'f_{field}')
  76. value = supported_operators[op](field, val[0]) if op in supported_operators else getattr(field, op)(*val)
  77. expression.append(value)
  78. return reduce(operator.iand, expression)
  79. def query_db(model: Type[DataBaseModel], limit: int = 0, offset: int = 0,
  80. query: dict = None, order_by: Union[str, list, tuple] = None):
  81. data = model.select()
  82. if query:
  83. data = data.where(query_dict2expression(model, query))
  84. count = data.count()
  85. if not order_by:
  86. order_by = 'create_time'
  87. if not isinstance(order_by, (list, tuple)):
  88. order_by = (order_by, 'asc')
  89. order_by, order = order_by
  90. order_by = getattr(model, f'f_{order_by}')
  91. order_by = getattr(order_by, order)()
  92. data = data.order_by(order_by)
  93. if limit > 0:
  94. data = data.limit(limit)
  95. if offset > 0:
  96. data = data.offset(offset)
  97. return list(data), count
  98. class StatusEnum(Enum):
  99. # 样本可用状态
  100. VALID = "1"
  101. IN_VALID = "0"