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.

dataset.py 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. import base64
  2. import enum
  3. import hashlib
  4. import hmac
  5. import json
  6. import logging
  7. import os
  8. import pickle
  9. import re
  10. import time
  11. from datetime import datetime
  12. from json import JSONDecodeError
  13. from typing import Any, Optional, cast
  14. import sqlalchemy as sa
  15. from sqlalchemy import DateTime, String, func, select
  16. from sqlalchemy.dialects.postgresql import JSONB
  17. from sqlalchemy.orm import Mapped, mapped_column
  18. from configs import dify_config
  19. from core.rag.index_processor.constant.built_in_field import BuiltInField, MetadataDataSource
  20. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  21. from extensions.ext_storage import storage
  22. from services.entities.knowledge_entities.knowledge_entities import ParentMode, Rule
  23. from .account import Account
  24. from .base import Base
  25. from .engine import db
  26. from .model import App, Tag, TagBinding, UploadFile
  27. from .types import StringUUID
  28. logger = logging.getLogger(__name__)
  29. class DatasetPermissionEnum(enum.StrEnum):
  30. ONLY_ME = "only_me"
  31. ALL_TEAM = "all_team_members"
  32. PARTIAL_TEAM = "partial_members"
  33. class Dataset(Base):
  34. __tablename__ = "datasets"
  35. __table_args__ = (
  36. sa.PrimaryKeyConstraint("id", name="dataset_pkey"),
  37. sa.Index("dataset_tenant_idx", "tenant_id"),
  38. sa.Index("retrieval_model_idx", "retrieval_model", postgresql_using="gin"),
  39. )
  40. INDEXING_TECHNIQUE_LIST = ["high_quality", "economy", None]
  41. PROVIDER_LIST = ["vendor", "external", None]
  42. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  43. tenant_id: Mapped[str] = mapped_column(StringUUID)
  44. name: Mapped[str] = mapped_column(String(255))
  45. description = mapped_column(sa.Text, nullable=True)
  46. provider: Mapped[str] = mapped_column(String(255), server_default=sa.text("'vendor'::character varying"))
  47. permission: Mapped[str] = mapped_column(String(255), server_default=sa.text("'only_me'::character varying"))
  48. data_source_type = mapped_column(String(255))
  49. indexing_technique: Mapped[Optional[str]] = mapped_column(String(255))
  50. index_struct = mapped_column(sa.Text, nullable=True)
  51. created_by = mapped_column(StringUUID, nullable=False)
  52. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  53. updated_by = mapped_column(StringUUID, nullable=True)
  54. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  55. embedding_model = mapped_column(String(255), nullable=True)
  56. embedding_model_provider = mapped_column(String(255), nullable=True)
  57. collection_binding_id = mapped_column(StringUUID, nullable=True)
  58. retrieval_model = mapped_column(JSONB, nullable=True)
  59. built_in_field_enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  60. @property
  61. def dataset_keyword_table(self):
  62. dataset_keyword_table = (
  63. db.session.query(DatasetKeywordTable).where(DatasetKeywordTable.dataset_id == self.id).first()
  64. )
  65. if dataset_keyword_table:
  66. return dataset_keyword_table
  67. return None
  68. @property
  69. def index_struct_dict(self):
  70. return json.loads(self.index_struct) if self.index_struct else None
  71. @property
  72. def external_retrieval_model(self):
  73. default_retrieval_model = {
  74. "top_k": 2,
  75. "score_threshold": 0.0,
  76. }
  77. return self.retrieval_model or default_retrieval_model
  78. @property
  79. def created_by_account(self):
  80. return db.session.get(Account, self.created_by)
  81. @property
  82. def latest_process_rule(self):
  83. return (
  84. db.session.query(DatasetProcessRule)
  85. .where(DatasetProcessRule.dataset_id == self.id)
  86. .order_by(DatasetProcessRule.created_at.desc())
  87. .first()
  88. )
  89. @property
  90. def app_count(self):
  91. return (
  92. db.session.query(func.count(AppDatasetJoin.id))
  93. .where(AppDatasetJoin.dataset_id == self.id, App.id == AppDatasetJoin.app_id)
  94. .scalar()
  95. )
  96. @property
  97. def document_count(self):
  98. return db.session.query(func.count(Document.id)).where(Document.dataset_id == self.id).scalar()
  99. @property
  100. def available_document_count(self):
  101. return (
  102. db.session.query(func.count(Document.id))
  103. .where(
  104. Document.dataset_id == self.id,
  105. Document.indexing_status == "completed",
  106. Document.enabled == True,
  107. Document.archived == False,
  108. )
  109. .scalar()
  110. )
  111. @property
  112. def available_segment_count(self):
  113. return (
  114. db.session.query(func.count(DocumentSegment.id))
  115. .where(
  116. DocumentSegment.dataset_id == self.id,
  117. DocumentSegment.status == "completed",
  118. DocumentSegment.enabled == True,
  119. )
  120. .scalar()
  121. )
  122. @property
  123. def word_count(self):
  124. return (
  125. db.session.query(Document)
  126. .with_entities(func.coalesce(func.sum(Document.word_count), 0))
  127. .where(Document.dataset_id == self.id)
  128. .scalar()
  129. )
  130. @property
  131. def doc_form(self):
  132. document = db.session.query(Document).where(Document.dataset_id == self.id).first()
  133. if document:
  134. return document.doc_form
  135. return None
  136. @property
  137. def retrieval_model_dict(self):
  138. default_retrieval_model = {
  139. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  140. "reranking_enable": False,
  141. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  142. "top_k": 2,
  143. "score_threshold_enabled": False,
  144. }
  145. return self.retrieval_model or default_retrieval_model
  146. @property
  147. def tags(self):
  148. tags = (
  149. db.session.query(Tag)
  150. .join(TagBinding, Tag.id == TagBinding.tag_id)
  151. .where(
  152. TagBinding.target_id == self.id,
  153. TagBinding.tenant_id == self.tenant_id,
  154. Tag.tenant_id == self.tenant_id,
  155. Tag.type == "knowledge",
  156. )
  157. .all()
  158. )
  159. return tags or []
  160. @property
  161. def external_knowledge_info(self):
  162. if self.provider != "external":
  163. return None
  164. external_knowledge_binding = (
  165. db.session.query(ExternalKnowledgeBindings).where(ExternalKnowledgeBindings.dataset_id == self.id).first()
  166. )
  167. if not external_knowledge_binding:
  168. return None
  169. external_knowledge_api = db.session.scalar(
  170. select(ExternalKnowledgeApis).where(
  171. ExternalKnowledgeApis.id == external_knowledge_binding.external_knowledge_api_id
  172. )
  173. )
  174. if not external_knowledge_api:
  175. return None
  176. return {
  177. "external_knowledge_id": external_knowledge_binding.external_knowledge_id,
  178. "external_knowledge_api_id": external_knowledge_api.id,
  179. "external_knowledge_api_name": external_knowledge_api.name,
  180. "external_knowledge_api_endpoint": json.loads(external_knowledge_api.settings).get("endpoint", ""),
  181. }
  182. @property
  183. def doc_metadata(self):
  184. dataset_metadatas = db.session.query(DatasetMetadata).where(DatasetMetadata.dataset_id == self.id).all()
  185. doc_metadata = [
  186. {
  187. "id": dataset_metadata.id,
  188. "name": dataset_metadata.name,
  189. "type": dataset_metadata.type,
  190. }
  191. for dataset_metadata in dataset_metadatas
  192. ]
  193. if self.built_in_field_enabled:
  194. doc_metadata.append(
  195. {
  196. "id": "built-in",
  197. "name": BuiltInField.document_name.value,
  198. "type": "string",
  199. }
  200. )
  201. doc_metadata.append(
  202. {
  203. "id": "built-in",
  204. "name": BuiltInField.uploader.value,
  205. "type": "string",
  206. }
  207. )
  208. doc_metadata.append(
  209. {
  210. "id": "built-in",
  211. "name": BuiltInField.upload_date.value,
  212. "type": "time",
  213. }
  214. )
  215. doc_metadata.append(
  216. {
  217. "id": "built-in",
  218. "name": BuiltInField.last_update_date.value,
  219. "type": "time",
  220. }
  221. )
  222. doc_metadata.append(
  223. {
  224. "id": "built-in",
  225. "name": BuiltInField.source.value,
  226. "type": "string",
  227. }
  228. )
  229. return doc_metadata
  230. @staticmethod
  231. def gen_collection_name_by_id(dataset_id: str) -> str:
  232. normalized_dataset_id = dataset_id.replace("-", "_")
  233. return f"{dify_config.VECTOR_INDEX_NAME_PREFIX}_{normalized_dataset_id}_Node"
  234. class DatasetProcessRule(Base):
  235. __tablename__ = "dataset_process_rules"
  236. __table_args__ = (
  237. sa.PrimaryKeyConstraint("id", name="dataset_process_rule_pkey"),
  238. sa.Index("dataset_process_rule_dataset_id_idx", "dataset_id"),
  239. )
  240. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  241. dataset_id = mapped_column(StringUUID, nullable=False)
  242. mode = mapped_column(String(255), nullable=False, server_default=sa.text("'automatic'::character varying"))
  243. rules = mapped_column(sa.Text, nullable=True)
  244. created_by = mapped_column(StringUUID, nullable=False)
  245. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  246. MODES = ["automatic", "custom", "hierarchical"]
  247. PRE_PROCESSING_RULES = ["remove_stopwords", "remove_extra_spaces", "remove_urls_emails"]
  248. AUTOMATIC_RULES: dict[str, Any] = {
  249. "pre_processing_rules": [
  250. {"id": "remove_extra_spaces", "enabled": True},
  251. {"id": "remove_urls_emails", "enabled": False},
  252. ],
  253. "segmentation": {"delimiter": "\n", "max_tokens": 500, "chunk_overlap": 50},
  254. }
  255. def to_dict(self):
  256. return {
  257. "id": self.id,
  258. "dataset_id": self.dataset_id,
  259. "mode": self.mode,
  260. "rules": self.rules_dict,
  261. }
  262. @property
  263. def rules_dict(self):
  264. try:
  265. return json.loads(self.rules) if self.rules else None
  266. except JSONDecodeError:
  267. return None
  268. class Document(Base):
  269. __tablename__ = "documents"
  270. __table_args__ = (
  271. sa.PrimaryKeyConstraint("id", name="document_pkey"),
  272. sa.Index("document_dataset_id_idx", "dataset_id"),
  273. sa.Index("document_is_paused_idx", "is_paused"),
  274. sa.Index("document_tenant_idx", "tenant_id"),
  275. sa.Index("document_metadata_idx", "doc_metadata", postgresql_using="gin"),
  276. )
  277. # initial fields
  278. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  279. tenant_id = mapped_column(StringUUID, nullable=False)
  280. dataset_id = mapped_column(StringUUID, nullable=False)
  281. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  282. data_source_type: Mapped[str] = mapped_column(String(255), nullable=False)
  283. data_source_info = mapped_column(sa.Text, nullable=True)
  284. dataset_process_rule_id = mapped_column(StringUUID, nullable=True)
  285. batch: Mapped[str] = mapped_column(String(255), nullable=False)
  286. name: Mapped[str] = mapped_column(String(255), nullable=False)
  287. created_from: Mapped[str] = mapped_column(String(255), nullable=False)
  288. created_by = mapped_column(StringUUID, nullable=False)
  289. created_api_request_id = mapped_column(StringUUID, nullable=True)
  290. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  291. # start processing
  292. processing_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  293. # parsing
  294. file_id = mapped_column(sa.Text, nullable=True)
  295. word_count: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True) # TODO: make this not nullable
  296. parsing_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  297. # cleaning
  298. cleaning_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  299. # split
  300. splitting_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  301. # indexing
  302. tokens: Mapped[Optional[int]] = mapped_column(sa.Integer, nullable=True)
  303. indexing_latency: Mapped[Optional[float]] = mapped_column(sa.Float, nullable=True)
  304. completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  305. # pause
  306. is_paused: Mapped[Optional[bool]] = mapped_column(sa.Boolean, nullable=True, server_default=sa.text("false"))
  307. paused_by = mapped_column(StringUUID, nullable=True)
  308. paused_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  309. # error
  310. error = mapped_column(sa.Text, nullable=True)
  311. stopped_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  312. # basic fields
  313. indexing_status = mapped_column(String(255), nullable=False, server_default=sa.text("'waiting'::character varying"))
  314. enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  315. disabled_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  316. disabled_by = mapped_column(StringUUID, nullable=True)
  317. archived: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  318. archived_reason = mapped_column(String(255), nullable=True)
  319. archived_by = mapped_column(StringUUID, nullable=True)
  320. archived_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  321. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  322. doc_type = mapped_column(String(40), nullable=True)
  323. doc_metadata = mapped_column(JSONB, nullable=True)
  324. doc_form = mapped_column(String(255), nullable=False, server_default=sa.text("'text_model'::character varying"))
  325. doc_language = mapped_column(String(255), nullable=True)
  326. DATA_SOURCES = ["upload_file", "notion_import", "website_crawl"]
  327. @property
  328. def display_status(self):
  329. status = None
  330. if self.indexing_status == "waiting":
  331. status = "queuing"
  332. elif self.indexing_status not in {"completed", "error", "waiting"} and self.is_paused:
  333. status = "paused"
  334. elif self.indexing_status in {"parsing", "cleaning", "splitting", "indexing"}:
  335. status = "indexing"
  336. elif self.indexing_status == "error":
  337. status = "error"
  338. elif self.indexing_status == "completed" and not self.archived and self.enabled:
  339. status = "available"
  340. elif self.indexing_status == "completed" and not self.archived and not self.enabled:
  341. status = "disabled"
  342. elif self.indexing_status == "completed" and self.archived:
  343. status = "archived"
  344. return status
  345. @property
  346. def data_source_info_dict(self):
  347. if self.data_source_info:
  348. try:
  349. data_source_info_dict = json.loads(self.data_source_info)
  350. except JSONDecodeError:
  351. data_source_info_dict = {}
  352. return data_source_info_dict
  353. return None
  354. @property
  355. def data_source_detail_dict(self):
  356. if self.data_source_info:
  357. if self.data_source_type == "upload_file":
  358. data_source_info_dict = json.loads(self.data_source_info)
  359. file_detail = (
  360. db.session.query(UploadFile)
  361. .where(UploadFile.id == data_source_info_dict["upload_file_id"])
  362. .one_or_none()
  363. )
  364. if file_detail:
  365. return {
  366. "upload_file": {
  367. "id": file_detail.id,
  368. "name": file_detail.name,
  369. "size": file_detail.size,
  370. "extension": file_detail.extension,
  371. "mime_type": file_detail.mime_type,
  372. "created_by": file_detail.created_by,
  373. "created_at": file_detail.created_at.timestamp(),
  374. }
  375. }
  376. elif self.data_source_type in {"notion_import", "website_crawl"}:
  377. return json.loads(self.data_source_info)
  378. return {}
  379. @property
  380. def average_segment_length(self):
  381. if self.word_count and self.word_count != 0 and self.segment_count and self.segment_count != 0:
  382. return self.word_count // self.segment_count
  383. return 0
  384. @property
  385. def dataset_process_rule(self):
  386. if self.dataset_process_rule_id:
  387. return db.session.get(DatasetProcessRule, self.dataset_process_rule_id)
  388. return None
  389. @property
  390. def dataset(self):
  391. return db.session.query(Dataset).where(Dataset.id == self.dataset_id).one_or_none()
  392. @property
  393. def segment_count(self):
  394. return db.session.query(DocumentSegment).where(DocumentSegment.document_id == self.id).count()
  395. @property
  396. def hit_count(self):
  397. return (
  398. db.session.query(DocumentSegment)
  399. .with_entities(func.coalesce(func.sum(DocumentSegment.hit_count), 0))
  400. .where(DocumentSegment.document_id == self.id)
  401. .scalar()
  402. )
  403. @property
  404. def uploader(self):
  405. user = db.session.query(Account).where(Account.id == self.created_by).first()
  406. return user.name if user else None
  407. @property
  408. def upload_date(self):
  409. return self.created_at
  410. @property
  411. def last_update_date(self):
  412. return self.updated_at
  413. @property
  414. def doc_metadata_details(self):
  415. if self.doc_metadata:
  416. document_metadatas = (
  417. db.session.query(DatasetMetadata)
  418. .join(DatasetMetadataBinding, DatasetMetadataBinding.metadata_id == DatasetMetadata.id)
  419. .where(
  420. DatasetMetadataBinding.dataset_id == self.dataset_id, DatasetMetadataBinding.document_id == self.id
  421. )
  422. .all()
  423. )
  424. metadata_list = []
  425. for metadata in document_metadatas:
  426. metadata_dict = {
  427. "id": metadata.id,
  428. "name": metadata.name,
  429. "type": metadata.type,
  430. "value": self.doc_metadata.get(metadata.name),
  431. }
  432. metadata_list.append(metadata_dict)
  433. # deal built-in fields
  434. metadata_list.extend(self.get_built_in_fields())
  435. return metadata_list
  436. return None
  437. @property
  438. def process_rule_dict(self):
  439. if self.dataset_process_rule_id:
  440. return self.dataset_process_rule.to_dict()
  441. return None
  442. def get_built_in_fields(self):
  443. built_in_fields = []
  444. built_in_fields.append(
  445. {
  446. "id": "built-in",
  447. "name": BuiltInField.document_name,
  448. "type": "string",
  449. "value": self.name,
  450. }
  451. )
  452. built_in_fields.append(
  453. {
  454. "id": "built-in",
  455. "name": BuiltInField.uploader,
  456. "type": "string",
  457. "value": self.uploader,
  458. }
  459. )
  460. built_in_fields.append(
  461. {
  462. "id": "built-in",
  463. "name": BuiltInField.upload_date,
  464. "type": "time",
  465. "value": str(self.created_at.timestamp()),
  466. }
  467. )
  468. built_in_fields.append(
  469. {
  470. "id": "built-in",
  471. "name": BuiltInField.last_update_date,
  472. "type": "time",
  473. "value": str(self.updated_at.timestamp()),
  474. }
  475. )
  476. built_in_fields.append(
  477. {
  478. "id": "built-in",
  479. "name": BuiltInField.source,
  480. "type": "string",
  481. "value": MetadataDataSource[self.data_source_type].value,
  482. }
  483. )
  484. return built_in_fields
  485. def to_dict(self):
  486. return {
  487. "id": self.id,
  488. "tenant_id": self.tenant_id,
  489. "dataset_id": self.dataset_id,
  490. "position": self.position,
  491. "data_source_type": self.data_source_type,
  492. "data_source_info": self.data_source_info,
  493. "dataset_process_rule_id": self.dataset_process_rule_id,
  494. "batch": self.batch,
  495. "name": self.name,
  496. "created_from": self.created_from,
  497. "created_by": self.created_by,
  498. "created_api_request_id": self.created_api_request_id,
  499. "created_at": self.created_at,
  500. "processing_started_at": self.processing_started_at,
  501. "file_id": self.file_id,
  502. "word_count": self.word_count,
  503. "parsing_completed_at": self.parsing_completed_at,
  504. "cleaning_completed_at": self.cleaning_completed_at,
  505. "splitting_completed_at": self.splitting_completed_at,
  506. "tokens": self.tokens,
  507. "indexing_latency": self.indexing_latency,
  508. "completed_at": self.completed_at,
  509. "is_paused": self.is_paused,
  510. "paused_by": self.paused_by,
  511. "paused_at": self.paused_at,
  512. "error": self.error,
  513. "stopped_at": self.stopped_at,
  514. "indexing_status": self.indexing_status,
  515. "enabled": self.enabled,
  516. "disabled_at": self.disabled_at,
  517. "disabled_by": self.disabled_by,
  518. "archived": self.archived,
  519. "archived_reason": self.archived_reason,
  520. "archived_by": self.archived_by,
  521. "archived_at": self.archived_at,
  522. "updated_at": self.updated_at,
  523. "doc_type": self.doc_type,
  524. "doc_metadata": self.doc_metadata,
  525. "doc_form": self.doc_form,
  526. "doc_language": self.doc_language,
  527. "display_status": self.display_status,
  528. "data_source_info_dict": self.data_source_info_dict,
  529. "average_segment_length": self.average_segment_length,
  530. "dataset_process_rule": self.dataset_process_rule.to_dict() if self.dataset_process_rule else None,
  531. "dataset": self.dataset.to_dict() if self.dataset else None,
  532. "segment_count": self.segment_count,
  533. "hit_count": self.hit_count,
  534. }
  535. @classmethod
  536. def from_dict(cls, data: dict):
  537. return cls(
  538. id=data.get("id"),
  539. tenant_id=data.get("tenant_id"),
  540. dataset_id=data.get("dataset_id"),
  541. position=data.get("position"),
  542. data_source_type=data.get("data_source_type"),
  543. data_source_info=data.get("data_source_info"),
  544. dataset_process_rule_id=data.get("dataset_process_rule_id"),
  545. batch=data.get("batch"),
  546. name=data.get("name"),
  547. created_from=data.get("created_from"),
  548. created_by=data.get("created_by"),
  549. created_api_request_id=data.get("created_api_request_id"),
  550. created_at=data.get("created_at"),
  551. processing_started_at=data.get("processing_started_at"),
  552. file_id=data.get("file_id"),
  553. word_count=data.get("word_count"),
  554. parsing_completed_at=data.get("parsing_completed_at"),
  555. cleaning_completed_at=data.get("cleaning_completed_at"),
  556. splitting_completed_at=data.get("splitting_completed_at"),
  557. tokens=data.get("tokens"),
  558. indexing_latency=data.get("indexing_latency"),
  559. completed_at=data.get("completed_at"),
  560. is_paused=data.get("is_paused"),
  561. paused_by=data.get("paused_by"),
  562. paused_at=data.get("paused_at"),
  563. error=data.get("error"),
  564. stopped_at=data.get("stopped_at"),
  565. indexing_status=data.get("indexing_status"),
  566. enabled=data.get("enabled"),
  567. disabled_at=data.get("disabled_at"),
  568. disabled_by=data.get("disabled_by"),
  569. archived=data.get("archived"),
  570. archived_reason=data.get("archived_reason"),
  571. archived_by=data.get("archived_by"),
  572. archived_at=data.get("archived_at"),
  573. updated_at=data.get("updated_at"),
  574. doc_type=data.get("doc_type"),
  575. doc_metadata=data.get("doc_metadata"),
  576. doc_form=data.get("doc_form"),
  577. doc_language=data.get("doc_language"),
  578. )
  579. class DocumentSegment(Base):
  580. __tablename__ = "document_segments"
  581. __table_args__ = (
  582. sa.PrimaryKeyConstraint("id", name="document_segment_pkey"),
  583. sa.Index("document_segment_dataset_id_idx", "dataset_id"),
  584. sa.Index("document_segment_document_id_idx", "document_id"),
  585. sa.Index("document_segment_tenant_dataset_idx", "dataset_id", "tenant_id"),
  586. sa.Index("document_segment_tenant_document_idx", "document_id", "tenant_id"),
  587. sa.Index("document_segment_node_dataset_idx", "index_node_id", "dataset_id"),
  588. sa.Index("document_segment_tenant_idx", "tenant_id"),
  589. )
  590. # initial fields
  591. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  592. tenant_id = mapped_column(StringUUID, nullable=False)
  593. dataset_id = mapped_column(StringUUID, nullable=False)
  594. document_id = mapped_column(StringUUID, nullable=False)
  595. position: Mapped[int]
  596. content = mapped_column(sa.Text, nullable=False)
  597. answer = mapped_column(sa.Text, nullable=True)
  598. word_count: Mapped[int]
  599. tokens: Mapped[int]
  600. # indexing fields
  601. keywords = mapped_column(sa.JSON, nullable=True)
  602. index_node_id = mapped_column(String(255), nullable=True)
  603. index_node_hash = mapped_column(String(255), nullable=True)
  604. # basic fields
  605. hit_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  606. enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  607. disabled_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  608. disabled_by = mapped_column(StringUUID, nullable=True)
  609. status: Mapped[str] = mapped_column(String(255), server_default=sa.text("'waiting'::character varying"))
  610. created_by = mapped_column(StringUUID, nullable=False)
  611. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  612. updated_by = mapped_column(StringUUID, nullable=True)
  613. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  614. indexing_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  615. completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  616. error = mapped_column(sa.Text, nullable=True)
  617. stopped_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  618. @property
  619. def dataset(self):
  620. return db.session.scalar(select(Dataset).where(Dataset.id == self.dataset_id))
  621. @property
  622. def document(self):
  623. return db.session.scalar(select(Document).where(Document.id == self.document_id))
  624. @property
  625. def previous_segment(self):
  626. return db.session.scalar(
  627. select(DocumentSegment).where(
  628. DocumentSegment.document_id == self.document_id, DocumentSegment.position == self.position - 1
  629. )
  630. )
  631. @property
  632. def next_segment(self):
  633. return db.session.scalar(
  634. select(DocumentSegment).where(
  635. DocumentSegment.document_id == self.document_id, DocumentSegment.position == self.position + 1
  636. )
  637. )
  638. @property
  639. def child_chunks(self):
  640. process_rule = self.document.dataset_process_rule
  641. if process_rule.mode == "hierarchical":
  642. rules = Rule(**process_rule.rules_dict)
  643. if rules.parent_mode and rules.parent_mode != ParentMode.FULL_DOC:
  644. child_chunks = (
  645. db.session.query(ChildChunk)
  646. .where(ChildChunk.segment_id == self.id)
  647. .order_by(ChildChunk.position.asc())
  648. .all()
  649. )
  650. return child_chunks or []
  651. else:
  652. return []
  653. else:
  654. return []
  655. def get_child_chunks(self):
  656. process_rule = self.document.dataset_process_rule
  657. if process_rule.mode == "hierarchical":
  658. rules = Rule(**process_rule.rules_dict)
  659. if rules.parent_mode:
  660. child_chunks = (
  661. db.session.query(ChildChunk)
  662. .where(ChildChunk.segment_id == self.id)
  663. .order_by(ChildChunk.position.asc())
  664. .all()
  665. )
  666. return child_chunks or []
  667. else:
  668. return []
  669. else:
  670. return []
  671. @property
  672. def sign_content(self):
  673. return self.get_sign_content()
  674. def get_sign_content(self):
  675. signed_urls = []
  676. text = self.content
  677. # For data before v0.10.0
  678. pattern = r"/files/([a-f0-9\-]+)/image-preview"
  679. matches = re.finditer(pattern, text)
  680. for match in matches:
  681. upload_file_id = match.group(1)
  682. nonce = os.urandom(16).hex()
  683. timestamp = str(int(time.time()))
  684. data_to_sign = f"image-preview|{upload_file_id}|{timestamp}|{nonce}"
  685. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  686. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  687. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  688. params = f"timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  689. signed_url = f"{match.group(0)}?{params}"
  690. signed_urls.append((match.start(), match.end(), signed_url))
  691. # For data after v0.10.0
  692. pattern = r"/files/([a-f0-9\-]+)/file-preview"
  693. matches = re.finditer(pattern, text)
  694. for match in matches:
  695. upload_file_id = match.group(1)
  696. nonce = os.urandom(16).hex()
  697. timestamp = str(int(time.time()))
  698. data_to_sign = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"
  699. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  700. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  701. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  702. params = f"timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  703. signed_url = f"{match.group(0)}?{params}"
  704. signed_urls.append((match.start(), match.end(), signed_url))
  705. # Reconstruct the text with signed URLs
  706. offset = 0
  707. for start, end, signed_url in signed_urls:
  708. text = text[: start + offset] + signed_url + text[end + offset :]
  709. offset += len(signed_url) - (end - start)
  710. return text
  711. class ChildChunk(Base):
  712. __tablename__ = "child_chunks"
  713. __table_args__ = (
  714. sa.PrimaryKeyConstraint("id", name="child_chunk_pkey"),
  715. sa.Index("child_chunk_dataset_id_idx", "tenant_id", "dataset_id", "document_id", "segment_id", "index_node_id"),
  716. sa.Index("child_chunks_node_idx", "index_node_id", "dataset_id"),
  717. sa.Index("child_chunks_segment_idx", "segment_id"),
  718. )
  719. # initial fields
  720. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  721. tenant_id = mapped_column(StringUUID, nullable=False)
  722. dataset_id = mapped_column(StringUUID, nullable=False)
  723. document_id = mapped_column(StringUUID, nullable=False)
  724. segment_id = mapped_column(StringUUID, nullable=False)
  725. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  726. content = mapped_column(sa.Text, nullable=False)
  727. word_count: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  728. # indexing fields
  729. index_node_id = mapped_column(String(255), nullable=True)
  730. index_node_hash = mapped_column(String(255), nullable=True)
  731. type = mapped_column(String(255), nullable=False, server_default=sa.text("'automatic'::character varying"))
  732. created_by = mapped_column(StringUUID, nullable=False)
  733. created_at: Mapped[datetime] = mapped_column(
  734. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  735. )
  736. updated_by = mapped_column(StringUUID, nullable=True)
  737. updated_at: Mapped[datetime] = mapped_column(
  738. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  739. )
  740. indexing_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  741. completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  742. error = mapped_column(sa.Text, nullable=True)
  743. @property
  744. def dataset(self):
  745. return db.session.query(Dataset).where(Dataset.id == self.dataset_id).first()
  746. @property
  747. def document(self):
  748. return db.session.query(Document).where(Document.id == self.document_id).first()
  749. @property
  750. def segment(self):
  751. return db.session.query(DocumentSegment).where(DocumentSegment.id == self.segment_id).first()
  752. class AppDatasetJoin(Base):
  753. __tablename__ = "app_dataset_joins"
  754. __table_args__ = (
  755. sa.PrimaryKeyConstraint("id", name="app_dataset_join_pkey"),
  756. sa.Index("app_dataset_join_app_dataset_idx", "dataset_id", "app_id"),
  757. )
  758. id = mapped_column(StringUUID, primary_key=True, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  759. app_id = mapped_column(StringUUID, nullable=False)
  760. dataset_id = mapped_column(StringUUID, nullable=False)
  761. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=db.func.current_timestamp())
  762. @property
  763. def app(self):
  764. return db.session.get(App, self.app_id)
  765. class DatasetQuery(Base):
  766. __tablename__ = "dataset_queries"
  767. __table_args__ = (
  768. sa.PrimaryKeyConstraint("id", name="dataset_query_pkey"),
  769. sa.Index("dataset_query_dataset_id_idx", "dataset_id"),
  770. )
  771. id = mapped_column(StringUUID, primary_key=True, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  772. dataset_id = mapped_column(StringUUID, nullable=False)
  773. content = mapped_column(sa.Text, nullable=False)
  774. source: Mapped[str] = mapped_column(String(255), nullable=False)
  775. source_app_id = mapped_column(StringUUID, nullable=True)
  776. created_by_role = mapped_column(String, nullable=False)
  777. created_by = mapped_column(StringUUID, nullable=False)
  778. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=db.func.current_timestamp())
  779. class DatasetKeywordTable(Base):
  780. __tablename__ = "dataset_keyword_tables"
  781. __table_args__ = (
  782. sa.PrimaryKeyConstraint("id", name="dataset_keyword_table_pkey"),
  783. sa.Index("dataset_keyword_table_dataset_id_idx", "dataset_id"),
  784. )
  785. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  786. dataset_id = mapped_column(StringUUID, nullable=False, unique=True)
  787. keyword_table = mapped_column(sa.Text, nullable=False)
  788. data_source_type = mapped_column(
  789. String(255), nullable=False, server_default=sa.text("'database'::character varying")
  790. )
  791. @property
  792. def keyword_table_dict(self):
  793. class SetDecoder(json.JSONDecoder):
  794. def __init__(self, *args, **kwargs):
  795. super().__init__(object_hook=self.object_hook, *args, **kwargs)
  796. def object_hook(self, dct):
  797. if isinstance(dct, dict):
  798. for keyword, node_idxs in dct.items():
  799. if isinstance(node_idxs, list):
  800. dct[keyword] = set(node_idxs)
  801. return dct
  802. # get dataset
  803. dataset = db.session.query(Dataset).filter_by(id=self.dataset_id).first()
  804. if not dataset:
  805. return None
  806. if self.data_source_type == "database":
  807. return json.loads(self.keyword_table, cls=SetDecoder) if self.keyword_table else None
  808. else:
  809. file_key = "keyword_files/" + dataset.tenant_id + "/" + self.dataset_id + ".txt"
  810. try:
  811. keyword_table_text = storage.load_once(file_key)
  812. if keyword_table_text:
  813. return json.loads(keyword_table_text.decode("utf-8"), cls=SetDecoder)
  814. return None
  815. except Exception:
  816. logger.exception("Failed to load keyword table from file: %s", file_key)
  817. return None
  818. class Embedding(Base):
  819. __tablename__ = "embeddings"
  820. __table_args__ = (
  821. sa.PrimaryKeyConstraint("id", name="embedding_pkey"),
  822. sa.UniqueConstraint("model_name", "hash", "provider_name", name="embedding_hash_idx"),
  823. sa.Index("created_at_idx", "created_at"),
  824. )
  825. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  826. model_name = mapped_column(
  827. String(255), nullable=False, server_default=sa.text("'text-embedding-ada-002'::character varying")
  828. )
  829. hash = mapped_column(String(64), nullable=False)
  830. embedding = mapped_column(sa.LargeBinary, nullable=False)
  831. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  832. provider_name = mapped_column(String(255), nullable=False, server_default=sa.text("''::character varying"))
  833. def set_embedding(self, embedding_data: list[float]):
  834. self.embedding = pickle.dumps(embedding_data, protocol=pickle.HIGHEST_PROTOCOL)
  835. def get_embedding(self) -> list[float]:
  836. return cast(list[float], pickle.loads(self.embedding)) # noqa: S301
  837. class DatasetCollectionBinding(Base):
  838. __tablename__ = "dataset_collection_bindings"
  839. __table_args__ = (
  840. sa.PrimaryKeyConstraint("id", name="dataset_collection_bindings_pkey"),
  841. sa.Index("provider_model_name_idx", "provider_name", "model_name"),
  842. )
  843. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  844. provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
  845. model_name: Mapped[str] = mapped_column(String(255), nullable=False)
  846. type = mapped_column(String(40), server_default=sa.text("'dataset'::character varying"), nullable=False)
  847. collection_name = mapped_column(String(64), nullable=False)
  848. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  849. class TidbAuthBinding(Base):
  850. __tablename__ = "tidb_auth_bindings"
  851. __table_args__ = (
  852. sa.PrimaryKeyConstraint("id", name="tidb_auth_bindings_pkey"),
  853. sa.Index("tidb_auth_bindings_tenant_idx", "tenant_id"),
  854. sa.Index("tidb_auth_bindings_active_idx", "active"),
  855. sa.Index("tidb_auth_bindings_created_at_idx", "created_at"),
  856. sa.Index("tidb_auth_bindings_status_idx", "status"),
  857. )
  858. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  859. tenant_id = mapped_column(StringUUID, nullable=True)
  860. cluster_id: Mapped[str] = mapped_column(String(255), nullable=False)
  861. cluster_name: Mapped[str] = mapped_column(String(255), nullable=False)
  862. active: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=db.text("false"))
  863. status = mapped_column(String(255), nullable=False, server_default=db.text("'CREATING'::character varying"))
  864. account: Mapped[str] = mapped_column(String(255), nullable=False)
  865. password: Mapped[str] = mapped_column(String(255), nullable=False)
  866. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  867. class Whitelist(Base):
  868. __tablename__ = "whitelists"
  869. __table_args__ = (
  870. sa.PrimaryKeyConstraint("id", name="whitelists_pkey"),
  871. sa.Index("whitelists_tenant_idx", "tenant_id"),
  872. )
  873. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  874. tenant_id = mapped_column(StringUUID, nullable=True)
  875. category: Mapped[str] = mapped_column(String(255), nullable=False)
  876. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  877. class DatasetPermission(Base):
  878. __tablename__ = "dataset_permissions"
  879. __table_args__ = (
  880. sa.PrimaryKeyConstraint("id", name="dataset_permission_pkey"),
  881. sa.Index("idx_dataset_permissions_dataset_id", "dataset_id"),
  882. sa.Index("idx_dataset_permissions_account_id", "account_id"),
  883. sa.Index("idx_dataset_permissions_tenant_id", "tenant_id"),
  884. )
  885. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"), primary_key=True)
  886. dataset_id = mapped_column(StringUUID, nullable=False)
  887. account_id = mapped_column(StringUUID, nullable=False)
  888. tenant_id = mapped_column(StringUUID, nullable=False)
  889. has_permission: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  890. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  891. class ExternalKnowledgeApis(Base):
  892. __tablename__ = "external_knowledge_apis"
  893. __table_args__ = (
  894. sa.PrimaryKeyConstraint("id", name="external_knowledge_apis_pkey"),
  895. sa.Index("external_knowledge_apis_tenant_idx", "tenant_id"),
  896. sa.Index("external_knowledge_apis_name_idx", "name"),
  897. )
  898. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  899. name: Mapped[str] = mapped_column(String(255), nullable=False)
  900. description: Mapped[str] = mapped_column(String(255), nullable=False)
  901. tenant_id = mapped_column(StringUUID, nullable=False)
  902. settings = mapped_column(sa.Text, nullable=True)
  903. created_by = mapped_column(StringUUID, nullable=False)
  904. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  905. updated_by = mapped_column(StringUUID, nullable=True)
  906. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  907. def to_dict(self):
  908. return {
  909. "id": self.id,
  910. "tenant_id": self.tenant_id,
  911. "name": self.name,
  912. "description": self.description,
  913. "settings": self.settings_dict,
  914. "dataset_bindings": self.dataset_bindings,
  915. "created_by": self.created_by,
  916. "created_at": self.created_at.isoformat(),
  917. }
  918. @property
  919. def settings_dict(self):
  920. try:
  921. return json.loads(self.settings) if self.settings else None
  922. except JSONDecodeError:
  923. return None
  924. @property
  925. def dataset_bindings(self):
  926. external_knowledge_bindings = (
  927. db.session.query(ExternalKnowledgeBindings)
  928. .where(ExternalKnowledgeBindings.external_knowledge_api_id == self.id)
  929. .all()
  930. )
  931. dataset_ids = [binding.dataset_id for binding in external_knowledge_bindings]
  932. datasets = db.session.query(Dataset).where(Dataset.id.in_(dataset_ids)).all()
  933. dataset_bindings = []
  934. for dataset in datasets:
  935. dataset_bindings.append({"id": dataset.id, "name": dataset.name})
  936. return dataset_bindings
  937. class ExternalKnowledgeBindings(Base):
  938. __tablename__ = "external_knowledge_bindings"
  939. __table_args__ = (
  940. sa.PrimaryKeyConstraint("id", name="external_knowledge_bindings_pkey"),
  941. sa.Index("external_knowledge_bindings_tenant_idx", "tenant_id"),
  942. sa.Index("external_knowledge_bindings_dataset_idx", "dataset_id"),
  943. sa.Index("external_knowledge_bindings_external_knowledge_idx", "external_knowledge_id"),
  944. sa.Index("external_knowledge_bindings_external_knowledge_api_idx", "external_knowledge_api_id"),
  945. )
  946. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  947. tenant_id = mapped_column(StringUUID, nullable=False)
  948. external_knowledge_api_id = mapped_column(StringUUID, nullable=False)
  949. dataset_id = mapped_column(StringUUID, nullable=False)
  950. external_knowledge_id = mapped_column(sa.Text, nullable=False)
  951. created_by = mapped_column(StringUUID, nullable=False)
  952. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  953. updated_by = mapped_column(StringUUID, nullable=True)
  954. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  955. class DatasetAutoDisableLog(Base):
  956. __tablename__ = "dataset_auto_disable_logs"
  957. __table_args__ = (
  958. sa.PrimaryKeyConstraint("id", name="dataset_auto_disable_log_pkey"),
  959. sa.Index("dataset_auto_disable_log_tenant_idx", "tenant_id"),
  960. sa.Index("dataset_auto_disable_log_dataset_idx", "dataset_id"),
  961. sa.Index("dataset_auto_disable_log_created_atx", "created_at"),
  962. )
  963. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  964. tenant_id = mapped_column(StringUUID, nullable=False)
  965. dataset_id = mapped_column(StringUUID, nullable=False)
  966. document_id = mapped_column(StringUUID, nullable=False)
  967. notified: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  968. created_at: Mapped[datetime] = mapped_column(
  969. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  970. )
  971. class RateLimitLog(Base):
  972. __tablename__ = "rate_limit_logs"
  973. __table_args__ = (
  974. sa.PrimaryKeyConstraint("id", name="rate_limit_log_pkey"),
  975. sa.Index("rate_limit_log_tenant_idx", "tenant_id"),
  976. sa.Index("rate_limit_log_operation_idx", "operation"),
  977. )
  978. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  979. tenant_id = mapped_column(StringUUID, nullable=False)
  980. subscription_plan: Mapped[str] = mapped_column(String(255), nullable=False)
  981. operation: Mapped[str] = mapped_column(String(255), nullable=False)
  982. created_at: Mapped[datetime] = mapped_column(
  983. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  984. )
  985. class DatasetMetadata(Base):
  986. __tablename__ = "dataset_metadatas"
  987. __table_args__ = (
  988. sa.PrimaryKeyConstraint("id", name="dataset_metadata_pkey"),
  989. sa.Index("dataset_metadata_tenant_idx", "tenant_id"),
  990. sa.Index("dataset_metadata_dataset_idx", "dataset_id"),
  991. )
  992. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  993. tenant_id = mapped_column(StringUUID, nullable=False)
  994. dataset_id = mapped_column(StringUUID, nullable=False)
  995. type: Mapped[str] = mapped_column(String(255), nullable=False)
  996. name: Mapped[str] = mapped_column(String(255), nullable=False)
  997. created_at: Mapped[datetime] = mapped_column(
  998. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  999. )
  1000. updated_at: Mapped[datetime] = mapped_column(
  1001. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  1002. )
  1003. created_by = mapped_column(StringUUID, nullable=False)
  1004. updated_by = mapped_column(StringUUID, nullable=True)
  1005. class DatasetMetadataBinding(Base):
  1006. __tablename__ = "dataset_metadata_bindings"
  1007. __table_args__ = (
  1008. sa.PrimaryKeyConstraint("id", name="dataset_metadata_binding_pkey"),
  1009. sa.Index("dataset_metadata_binding_tenant_idx", "tenant_id"),
  1010. sa.Index("dataset_metadata_binding_dataset_idx", "dataset_id"),
  1011. sa.Index("dataset_metadata_binding_metadata_idx", "metadata_id"),
  1012. sa.Index("dataset_metadata_binding_document_idx", "document_id"),
  1013. )
  1014. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1015. tenant_id = mapped_column(StringUUID, nullable=False)
  1016. dataset_id = mapped_column(StringUUID, nullable=False)
  1017. metadata_id = mapped_column(StringUUID, nullable=False)
  1018. document_id = mapped_column(StringUUID, nullable=False)
  1019. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  1020. created_by = mapped_column(StringUUID, nullable=False)