Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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) -> dict[str, Any]:
  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) -> dict[str, Any] | None:
  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) -> dict[str, Any] | None:
  347. if self.data_source_info:
  348. try:
  349. data_source_info_dict: dict[str, Any] = 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) -> dict[str, Any]:
  356. if self.data_source_info:
  357. if self.data_source_type == "upload_file":
  358. data_source_info_dict: dict[str, Any] = 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. result: dict[str, Any] = json.loads(self.data_source_info)
  378. return result
  379. return {}
  380. @property
  381. def average_segment_length(self):
  382. if self.word_count and self.word_count != 0 and self.segment_count and self.segment_count != 0:
  383. return self.word_count // self.segment_count
  384. return 0
  385. @property
  386. def dataset_process_rule(self):
  387. if self.dataset_process_rule_id:
  388. return db.session.get(DatasetProcessRule, self.dataset_process_rule_id)
  389. return None
  390. @property
  391. def dataset(self):
  392. return db.session.query(Dataset).where(Dataset.id == self.dataset_id).one_or_none()
  393. @property
  394. def segment_count(self):
  395. return db.session.query(DocumentSegment).where(DocumentSegment.document_id == self.id).count()
  396. @property
  397. def hit_count(self):
  398. return (
  399. db.session.query(DocumentSegment)
  400. .with_entities(func.coalesce(func.sum(DocumentSegment.hit_count), 0))
  401. .where(DocumentSegment.document_id == self.id)
  402. .scalar()
  403. )
  404. @property
  405. def uploader(self):
  406. user = db.session.query(Account).where(Account.id == self.created_by).first()
  407. return user.name if user else None
  408. @property
  409. def upload_date(self):
  410. return self.created_at
  411. @property
  412. def last_update_date(self):
  413. return self.updated_at
  414. @property
  415. def doc_metadata_details(self) -> list[dict[str, Any]] | None:
  416. if self.doc_metadata:
  417. document_metadatas = (
  418. db.session.query(DatasetMetadata)
  419. .join(DatasetMetadataBinding, DatasetMetadataBinding.metadata_id == DatasetMetadata.id)
  420. .where(
  421. DatasetMetadataBinding.dataset_id == self.dataset_id, DatasetMetadataBinding.document_id == self.id
  422. )
  423. .all()
  424. )
  425. metadata_list: list[dict[str, Any]] = []
  426. for metadata in document_metadatas:
  427. metadata_dict: dict[str, Any] = {
  428. "id": metadata.id,
  429. "name": metadata.name,
  430. "type": metadata.type,
  431. "value": self.doc_metadata.get(metadata.name),
  432. }
  433. metadata_list.append(metadata_dict)
  434. # deal built-in fields
  435. metadata_list.extend(self.get_built_in_fields())
  436. return metadata_list
  437. return None
  438. @property
  439. def process_rule_dict(self) -> dict[str, Any] | None:
  440. if self.dataset_process_rule_id and self.dataset_process_rule:
  441. return self.dataset_process_rule.to_dict()
  442. return None
  443. def get_built_in_fields(self) -> list[dict[str, Any]]:
  444. built_in_fields: list[dict[str, Any]] = []
  445. built_in_fields.append(
  446. {
  447. "id": "built-in",
  448. "name": BuiltInField.document_name,
  449. "type": "string",
  450. "value": self.name,
  451. }
  452. )
  453. built_in_fields.append(
  454. {
  455. "id": "built-in",
  456. "name": BuiltInField.uploader,
  457. "type": "string",
  458. "value": self.uploader,
  459. }
  460. )
  461. built_in_fields.append(
  462. {
  463. "id": "built-in",
  464. "name": BuiltInField.upload_date,
  465. "type": "time",
  466. "value": str(self.created_at.timestamp()),
  467. }
  468. )
  469. built_in_fields.append(
  470. {
  471. "id": "built-in",
  472. "name": BuiltInField.last_update_date,
  473. "type": "time",
  474. "value": str(self.updated_at.timestamp()),
  475. }
  476. )
  477. built_in_fields.append(
  478. {
  479. "id": "built-in",
  480. "name": BuiltInField.source,
  481. "type": "string",
  482. "value": MetadataDataSource[self.data_source_type].value,
  483. }
  484. )
  485. return built_in_fields
  486. def to_dict(self) -> dict[str, Any]:
  487. return {
  488. "id": self.id,
  489. "tenant_id": self.tenant_id,
  490. "dataset_id": self.dataset_id,
  491. "position": self.position,
  492. "data_source_type": self.data_source_type,
  493. "data_source_info": self.data_source_info,
  494. "dataset_process_rule_id": self.dataset_process_rule_id,
  495. "batch": self.batch,
  496. "name": self.name,
  497. "created_from": self.created_from,
  498. "created_by": self.created_by,
  499. "created_api_request_id": self.created_api_request_id,
  500. "created_at": self.created_at,
  501. "processing_started_at": self.processing_started_at,
  502. "file_id": self.file_id,
  503. "word_count": self.word_count,
  504. "parsing_completed_at": self.parsing_completed_at,
  505. "cleaning_completed_at": self.cleaning_completed_at,
  506. "splitting_completed_at": self.splitting_completed_at,
  507. "tokens": self.tokens,
  508. "indexing_latency": self.indexing_latency,
  509. "completed_at": self.completed_at,
  510. "is_paused": self.is_paused,
  511. "paused_by": self.paused_by,
  512. "paused_at": self.paused_at,
  513. "error": self.error,
  514. "stopped_at": self.stopped_at,
  515. "indexing_status": self.indexing_status,
  516. "enabled": self.enabled,
  517. "disabled_at": self.disabled_at,
  518. "disabled_by": self.disabled_by,
  519. "archived": self.archived,
  520. "archived_reason": self.archived_reason,
  521. "archived_by": self.archived_by,
  522. "archived_at": self.archived_at,
  523. "updated_at": self.updated_at,
  524. "doc_type": self.doc_type,
  525. "doc_metadata": self.doc_metadata,
  526. "doc_form": self.doc_form,
  527. "doc_language": self.doc_language,
  528. "display_status": self.display_status,
  529. "data_source_info_dict": self.data_source_info_dict,
  530. "average_segment_length": self.average_segment_length,
  531. "dataset_process_rule": self.dataset_process_rule.to_dict() if self.dataset_process_rule else None,
  532. "dataset": None, # Dataset class doesn't have a to_dict method
  533. "segment_count": self.segment_count,
  534. "hit_count": self.hit_count,
  535. }
  536. @classmethod
  537. def from_dict(cls, data: dict[str, Any]):
  538. return cls(
  539. id=data.get("id"),
  540. tenant_id=data.get("tenant_id"),
  541. dataset_id=data.get("dataset_id"),
  542. position=data.get("position"),
  543. data_source_type=data.get("data_source_type"),
  544. data_source_info=data.get("data_source_info"),
  545. dataset_process_rule_id=data.get("dataset_process_rule_id"),
  546. batch=data.get("batch"),
  547. name=data.get("name"),
  548. created_from=data.get("created_from"),
  549. created_by=data.get("created_by"),
  550. created_api_request_id=data.get("created_api_request_id"),
  551. created_at=data.get("created_at"),
  552. processing_started_at=data.get("processing_started_at"),
  553. file_id=data.get("file_id"),
  554. word_count=data.get("word_count"),
  555. parsing_completed_at=data.get("parsing_completed_at"),
  556. cleaning_completed_at=data.get("cleaning_completed_at"),
  557. splitting_completed_at=data.get("splitting_completed_at"),
  558. tokens=data.get("tokens"),
  559. indexing_latency=data.get("indexing_latency"),
  560. completed_at=data.get("completed_at"),
  561. is_paused=data.get("is_paused"),
  562. paused_by=data.get("paused_by"),
  563. paused_at=data.get("paused_at"),
  564. error=data.get("error"),
  565. stopped_at=data.get("stopped_at"),
  566. indexing_status=data.get("indexing_status"),
  567. enabled=data.get("enabled"),
  568. disabled_at=data.get("disabled_at"),
  569. disabled_by=data.get("disabled_by"),
  570. archived=data.get("archived"),
  571. archived_reason=data.get("archived_reason"),
  572. archived_by=data.get("archived_by"),
  573. archived_at=data.get("archived_at"),
  574. updated_at=data.get("updated_at"),
  575. doc_type=data.get("doc_type"),
  576. doc_metadata=data.get("doc_metadata"),
  577. doc_form=data.get("doc_form"),
  578. doc_language=data.get("doc_language"),
  579. )
  580. class DocumentSegment(Base):
  581. __tablename__ = "document_segments"
  582. __table_args__ = (
  583. sa.PrimaryKeyConstraint("id", name="document_segment_pkey"),
  584. sa.Index("document_segment_dataset_id_idx", "dataset_id"),
  585. sa.Index("document_segment_document_id_idx", "document_id"),
  586. sa.Index("document_segment_tenant_dataset_idx", "dataset_id", "tenant_id"),
  587. sa.Index("document_segment_tenant_document_idx", "document_id", "tenant_id"),
  588. sa.Index("document_segment_node_dataset_idx", "index_node_id", "dataset_id"),
  589. sa.Index("document_segment_tenant_idx", "tenant_id"),
  590. )
  591. # initial fields
  592. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  593. tenant_id = mapped_column(StringUUID, nullable=False)
  594. dataset_id = mapped_column(StringUUID, nullable=False)
  595. document_id = mapped_column(StringUUID, nullable=False)
  596. position: Mapped[int]
  597. content = mapped_column(sa.Text, nullable=False)
  598. answer = mapped_column(sa.Text, nullable=True)
  599. word_count: Mapped[int]
  600. tokens: Mapped[int]
  601. # indexing fields
  602. keywords = mapped_column(sa.JSON, nullable=True)
  603. index_node_id = mapped_column(String(255), nullable=True)
  604. index_node_hash = mapped_column(String(255), nullable=True)
  605. # basic fields
  606. hit_count: Mapped[int] = mapped_column(sa.Integer, nullable=False, default=0)
  607. enabled: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  608. disabled_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  609. disabled_by = mapped_column(StringUUID, nullable=True)
  610. status: Mapped[str] = mapped_column(String(255), server_default=sa.text("'waiting'::character varying"))
  611. created_by = mapped_column(StringUUID, nullable=False)
  612. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  613. updated_by = mapped_column(StringUUID, nullable=True)
  614. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  615. indexing_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  616. completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  617. error = mapped_column(sa.Text, nullable=True)
  618. stopped_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  619. @property
  620. def dataset(self):
  621. return db.session.scalar(select(Dataset).where(Dataset.id == self.dataset_id))
  622. @property
  623. def document(self):
  624. return db.session.scalar(select(Document).where(Document.id == self.document_id))
  625. @property
  626. def previous_segment(self):
  627. return db.session.scalar(
  628. select(DocumentSegment).where(
  629. DocumentSegment.document_id == self.document_id, DocumentSegment.position == self.position - 1
  630. )
  631. )
  632. @property
  633. def next_segment(self):
  634. return db.session.scalar(
  635. select(DocumentSegment).where(
  636. DocumentSegment.document_id == self.document_id, DocumentSegment.position == self.position + 1
  637. )
  638. )
  639. @property
  640. def child_chunks(self) -> list[Any]:
  641. if not self.document:
  642. return []
  643. process_rule = self.document.dataset_process_rule
  644. if process_rule and process_rule.mode == "hierarchical":
  645. rules_dict = process_rule.rules_dict
  646. if rules_dict:
  647. rules = Rule(**rules_dict)
  648. if rules.parent_mode and rules.parent_mode != ParentMode.FULL_DOC:
  649. child_chunks = (
  650. db.session.query(ChildChunk)
  651. .where(ChildChunk.segment_id == self.id)
  652. .order_by(ChildChunk.position.asc())
  653. .all()
  654. )
  655. return child_chunks or []
  656. return []
  657. def get_child_chunks(self) -> list[Any]:
  658. if not self.document:
  659. return []
  660. process_rule = self.document.dataset_process_rule
  661. if process_rule and process_rule.mode == "hierarchical":
  662. rules_dict = process_rule.rules_dict
  663. if rules_dict:
  664. rules = Rule(**rules_dict)
  665. if rules.parent_mode:
  666. child_chunks = (
  667. db.session.query(ChildChunk)
  668. .where(ChildChunk.segment_id == self.id)
  669. .order_by(ChildChunk.position.asc())
  670. .all()
  671. )
  672. return child_chunks or []
  673. return []
  674. @property
  675. def sign_content(self) -> str:
  676. return self.get_sign_content()
  677. def get_sign_content(self) -> str:
  678. signed_urls: list[tuple[int, int, str]] = []
  679. text = self.content
  680. # For data before v0.10.0
  681. pattern = r"/files/([a-f0-9\-]+)/image-preview"
  682. matches = re.finditer(pattern, text)
  683. for match in matches:
  684. upload_file_id = match.group(1)
  685. nonce = os.urandom(16).hex()
  686. timestamp = str(int(time.time()))
  687. data_to_sign = f"image-preview|{upload_file_id}|{timestamp}|{nonce}"
  688. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  689. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  690. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  691. params = f"timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  692. signed_url = f"{match.group(0)}?{params}"
  693. signed_urls.append((match.start(), match.end(), signed_url))
  694. # For data after v0.10.0
  695. pattern = r"/files/([a-f0-9\-]+)/file-preview"
  696. matches = re.finditer(pattern, text)
  697. for match in matches:
  698. upload_file_id = match.group(1)
  699. nonce = os.urandom(16).hex()
  700. timestamp = str(int(time.time()))
  701. data_to_sign = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"
  702. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  703. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  704. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  705. params = f"timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  706. signed_url = f"{match.group(0)}?{params}"
  707. signed_urls.append((match.start(), match.end(), signed_url))
  708. # Reconstruct the text with signed URLs
  709. offset = 0
  710. for start, end, signed_url in signed_urls:
  711. text = text[: start + offset] + signed_url + text[end + offset :]
  712. offset += len(signed_url) - (end - start)
  713. return text
  714. class ChildChunk(Base):
  715. __tablename__ = "child_chunks"
  716. __table_args__ = (
  717. sa.PrimaryKeyConstraint("id", name="child_chunk_pkey"),
  718. sa.Index("child_chunk_dataset_id_idx", "tenant_id", "dataset_id", "document_id", "segment_id", "index_node_id"),
  719. sa.Index("child_chunks_node_idx", "index_node_id", "dataset_id"),
  720. sa.Index("child_chunks_segment_idx", "segment_id"),
  721. )
  722. # initial fields
  723. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  724. tenant_id = mapped_column(StringUUID, nullable=False)
  725. dataset_id = mapped_column(StringUUID, nullable=False)
  726. document_id = mapped_column(StringUUID, nullable=False)
  727. segment_id = mapped_column(StringUUID, nullable=False)
  728. position: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  729. content = mapped_column(sa.Text, nullable=False)
  730. word_count: Mapped[int] = mapped_column(sa.Integer, nullable=False)
  731. # indexing fields
  732. index_node_id = mapped_column(String(255), nullable=True)
  733. index_node_hash = mapped_column(String(255), nullable=True)
  734. type = mapped_column(String(255), nullable=False, server_default=sa.text("'automatic'::character varying"))
  735. created_by = mapped_column(StringUUID, nullable=False)
  736. created_at: Mapped[datetime] = mapped_column(
  737. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  738. )
  739. updated_by = mapped_column(StringUUID, nullable=True)
  740. updated_at: Mapped[datetime] = mapped_column(
  741. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  742. )
  743. indexing_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  744. completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
  745. error = mapped_column(sa.Text, nullable=True)
  746. @property
  747. def dataset(self):
  748. return db.session.query(Dataset).where(Dataset.id == self.dataset_id).first()
  749. @property
  750. def document(self):
  751. return db.session.query(Document).where(Document.id == self.document_id).first()
  752. @property
  753. def segment(self):
  754. return db.session.query(DocumentSegment).where(DocumentSegment.id == self.segment_id).first()
  755. class AppDatasetJoin(Base):
  756. __tablename__ = "app_dataset_joins"
  757. __table_args__ = (
  758. sa.PrimaryKeyConstraint("id", name="app_dataset_join_pkey"),
  759. sa.Index("app_dataset_join_app_dataset_idx", "dataset_id", "app_id"),
  760. )
  761. id = mapped_column(StringUUID, primary_key=True, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  762. app_id = mapped_column(StringUUID, nullable=False)
  763. dataset_id = mapped_column(StringUUID, nullable=False)
  764. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=db.func.current_timestamp())
  765. @property
  766. def app(self):
  767. return db.session.get(App, self.app_id)
  768. class DatasetQuery(Base):
  769. __tablename__ = "dataset_queries"
  770. __table_args__ = (
  771. sa.PrimaryKeyConstraint("id", name="dataset_query_pkey"),
  772. sa.Index("dataset_query_dataset_id_idx", "dataset_id"),
  773. )
  774. id = mapped_column(StringUUID, primary_key=True, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  775. dataset_id = mapped_column(StringUUID, nullable=False)
  776. content = mapped_column(sa.Text, nullable=False)
  777. source: Mapped[str] = mapped_column(String(255), nullable=False)
  778. source_app_id = mapped_column(StringUUID, nullable=True)
  779. created_by_role = mapped_column(String, nullable=False)
  780. created_by = mapped_column(StringUUID, nullable=False)
  781. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=db.func.current_timestamp())
  782. class DatasetKeywordTable(Base):
  783. __tablename__ = "dataset_keyword_tables"
  784. __table_args__ = (
  785. sa.PrimaryKeyConstraint("id", name="dataset_keyword_table_pkey"),
  786. sa.Index("dataset_keyword_table_dataset_id_idx", "dataset_id"),
  787. )
  788. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  789. dataset_id = mapped_column(StringUUID, nullable=False, unique=True)
  790. keyword_table = mapped_column(sa.Text, nullable=False)
  791. data_source_type = mapped_column(
  792. String(255), nullable=False, server_default=sa.text("'database'::character varying")
  793. )
  794. @property
  795. def keyword_table_dict(self) -> dict[str, set[Any]] | None:
  796. class SetDecoder(json.JSONDecoder):
  797. def __init__(self, *args: Any, **kwargs: Any) -> None:
  798. def object_hook(dct: Any) -> Any:
  799. if isinstance(dct, dict):
  800. result: dict[str, Any] = {}
  801. items = cast(dict[str, Any], dct).items()
  802. for keyword, node_idxs in items:
  803. if isinstance(node_idxs, list):
  804. result[keyword] = set(cast(list[Any], node_idxs))
  805. else:
  806. result[keyword] = node_idxs
  807. return result
  808. return dct
  809. super().__init__(object_hook=object_hook, *args, **kwargs)
  810. # get dataset
  811. dataset = db.session.query(Dataset).filter_by(id=self.dataset_id).first()
  812. if not dataset:
  813. return None
  814. if self.data_source_type == "database":
  815. return json.loads(self.keyword_table, cls=SetDecoder) if self.keyword_table else None
  816. else:
  817. file_key = "keyword_files/" + dataset.tenant_id + "/" + self.dataset_id + ".txt"
  818. try:
  819. keyword_table_text = storage.load_once(file_key)
  820. if keyword_table_text:
  821. return json.loads(keyword_table_text.decode("utf-8"), cls=SetDecoder)
  822. return None
  823. except Exception:
  824. logger.exception("Failed to load keyword table from file: %s", file_key)
  825. return None
  826. class Embedding(Base):
  827. __tablename__ = "embeddings"
  828. __table_args__ = (
  829. sa.PrimaryKeyConstraint("id", name="embedding_pkey"),
  830. sa.UniqueConstraint("model_name", "hash", "provider_name", name="embedding_hash_idx"),
  831. sa.Index("created_at_idx", "created_at"),
  832. )
  833. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  834. model_name = mapped_column(
  835. String(255), nullable=False, server_default=sa.text("'text-embedding-ada-002'::character varying")
  836. )
  837. hash = mapped_column(String(64), nullable=False)
  838. embedding = mapped_column(sa.LargeBinary, nullable=False)
  839. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  840. provider_name = mapped_column(String(255), nullable=False, server_default=sa.text("''::character varying"))
  841. def set_embedding(self, embedding_data: list[float]):
  842. self.embedding = pickle.dumps(embedding_data, protocol=pickle.HIGHEST_PROTOCOL)
  843. def get_embedding(self) -> list[float]:
  844. return cast(list[float], pickle.loads(self.embedding)) # noqa: S301
  845. class DatasetCollectionBinding(Base):
  846. __tablename__ = "dataset_collection_bindings"
  847. __table_args__ = (
  848. sa.PrimaryKeyConstraint("id", name="dataset_collection_bindings_pkey"),
  849. sa.Index("provider_model_name_idx", "provider_name", "model_name"),
  850. )
  851. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  852. provider_name: Mapped[str] = mapped_column(String(255), nullable=False)
  853. model_name: Mapped[str] = mapped_column(String(255), nullable=False)
  854. type = mapped_column(String(40), server_default=sa.text("'dataset'::character varying"), nullable=False)
  855. collection_name = mapped_column(String(64), nullable=False)
  856. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  857. class TidbAuthBinding(Base):
  858. __tablename__ = "tidb_auth_bindings"
  859. __table_args__ = (
  860. sa.PrimaryKeyConstraint("id", name="tidb_auth_bindings_pkey"),
  861. sa.Index("tidb_auth_bindings_tenant_idx", "tenant_id"),
  862. sa.Index("tidb_auth_bindings_active_idx", "active"),
  863. sa.Index("tidb_auth_bindings_created_at_idx", "created_at"),
  864. sa.Index("tidb_auth_bindings_status_idx", "status"),
  865. )
  866. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  867. tenant_id = mapped_column(StringUUID, nullable=True)
  868. cluster_id: Mapped[str] = mapped_column(String(255), nullable=False)
  869. cluster_name: Mapped[str] = mapped_column(String(255), nullable=False)
  870. active: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=db.text("false"))
  871. status = mapped_column(String(255), nullable=False, server_default=db.text("'CREATING'::character varying"))
  872. account: Mapped[str] = mapped_column(String(255), nullable=False)
  873. password: Mapped[str] = mapped_column(String(255), nullable=False)
  874. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  875. class Whitelist(Base):
  876. __tablename__ = "whitelists"
  877. __table_args__ = (
  878. sa.PrimaryKeyConstraint("id", name="whitelists_pkey"),
  879. sa.Index("whitelists_tenant_idx", "tenant_id"),
  880. )
  881. id = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  882. tenant_id = mapped_column(StringUUID, nullable=True)
  883. category: Mapped[str] = mapped_column(String(255), nullable=False)
  884. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  885. class DatasetPermission(Base):
  886. __tablename__ = "dataset_permissions"
  887. __table_args__ = (
  888. sa.PrimaryKeyConstraint("id", name="dataset_permission_pkey"),
  889. sa.Index("idx_dataset_permissions_dataset_id", "dataset_id"),
  890. sa.Index("idx_dataset_permissions_account_id", "account_id"),
  891. sa.Index("idx_dataset_permissions_tenant_id", "tenant_id"),
  892. )
  893. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"), primary_key=True)
  894. dataset_id = mapped_column(StringUUID, nullable=False)
  895. account_id = mapped_column(StringUUID, nullable=False)
  896. tenant_id = mapped_column(StringUUID, nullable=False)
  897. has_permission: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("true"))
  898. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  899. class ExternalKnowledgeApis(Base):
  900. __tablename__ = "external_knowledge_apis"
  901. __table_args__ = (
  902. sa.PrimaryKeyConstraint("id", name="external_knowledge_apis_pkey"),
  903. sa.Index("external_knowledge_apis_tenant_idx", "tenant_id"),
  904. sa.Index("external_knowledge_apis_name_idx", "name"),
  905. )
  906. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  907. name: Mapped[str] = mapped_column(String(255), nullable=False)
  908. description: Mapped[str] = mapped_column(String(255), nullable=False)
  909. tenant_id = mapped_column(StringUUID, nullable=False)
  910. settings = mapped_column(sa.Text, nullable=True)
  911. created_by = mapped_column(StringUUID, nullable=False)
  912. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  913. updated_by = mapped_column(StringUUID, nullable=True)
  914. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  915. def to_dict(self) -> dict[str, Any]:
  916. return {
  917. "id": self.id,
  918. "tenant_id": self.tenant_id,
  919. "name": self.name,
  920. "description": self.description,
  921. "settings": self.settings_dict,
  922. "dataset_bindings": self.dataset_bindings,
  923. "created_by": self.created_by,
  924. "created_at": self.created_at.isoformat(),
  925. }
  926. @property
  927. def settings_dict(self) -> dict[str, Any] | None:
  928. try:
  929. return json.loads(self.settings) if self.settings else None
  930. except JSONDecodeError:
  931. return None
  932. @property
  933. def dataset_bindings(self) -> list[dict[str, Any]]:
  934. external_knowledge_bindings = (
  935. db.session.query(ExternalKnowledgeBindings)
  936. .where(ExternalKnowledgeBindings.external_knowledge_api_id == self.id)
  937. .all()
  938. )
  939. dataset_ids = [binding.dataset_id for binding in external_knowledge_bindings]
  940. datasets = db.session.query(Dataset).where(Dataset.id.in_(dataset_ids)).all()
  941. dataset_bindings: list[dict[str, Any]] = []
  942. for dataset in datasets:
  943. dataset_bindings.append({"id": dataset.id, "name": dataset.name})
  944. return dataset_bindings
  945. class ExternalKnowledgeBindings(Base):
  946. __tablename__ = "external_knowledge_bindings"
  947. __table_args__ = (
  948. sa.PrimaryKeyConstraint("id", name="external_knowledge_bindings_pkey"),
  949. sa.Index("external_knowledge_bindings_tenant_idx", "tenant_id"),
  950. sa.Index("external_knowledge_bindings_dataset_idx", "dataset_id"),
  951. sa.Index("external_knowledge_bindings_external_knowledge_idx", "external_knowledge_id"),
  952. sa.Index("external_knowledge_bindings_external_knowledge_api_idx", "external_knowledge_api_id"),
  953. )
  954. id = mapped_column(StringUUID, nullable=False, server_default=sa.text("uuid_generate_v4()"))
  955. tenant_id = mapped_column(StringUUID, nullable=False)
  956. external_knowledge_api_id = mapped_column(StringUUID, nullable=False)
  957. dataset_id = mapped_column(StringUUID, nullable=False)
  958. external_knowledge_id = mapped_column(sa.Text, nullable=False)
  959. created_by = mapped_column(StringUUID, nullable=False)
  960. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  961. updated_by = mapped_column(StringUUID, nullable=True)
  962. updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  963. class DatasetAutoDisableLog(Base):
  964. __tablename__ = "dataset_auto_disable_logs"
  965. __table_args__ = (
  966. sa.PrimaryKeyConstraint("id", name="dataset_auto_disable_log_pkey"),
  967. sa.Index("dataset_auto_disable_log_tenant_idx", "tenant_id"),
  968. sa.Index("dataset_auto_disable_log_dataset_idx", "dataset_id"),
  969. sa.Index("dataset_auto_disable_log_created_atx", "created_at"),
  970. )
  971. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  972. tenant_id = mapped_column(StringUUID, nullable=False)
  973. dataset_id = mapped_column(StringUUID, nullable=False)
  974. document_id = mapped_column(StringUUID, nullable=False)
  975. notified: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, server_default=sa.text("false"))
  976. created_at: Mapped[datetime] = mapped_column(
  977. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  978. )
  979. class RateLimitLog(Base):
  980. __tablename__ = "rate_limit_logs"
  981. __table_args__ = (
  982. sa.PrimaryKeyConstraint("id", name="rate_limit_log_pkey"),
  983. sa.Index("rate_limit_log_tenant_idx", "tenant_id"),
  984. sa.Index("rate_limit_log_operation_idx", "operation"),
  985. )
  986. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  987. tenant_id = mapped_column(StringUUID, nullable=False)
  988. subscription_plan: Mapped[str] = mapped_column(String(255), nullable=False)
  989. operation: Mapped[str] = mapped_column(String(255), nullable=False)
  990. created_at: Mapped[datetime] = mapped_column(
  991. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  992. )
  993. class DatasetMetadata(Base):
  994. __tablename__ = "dataset_metadatas"
  995. __table_args__ = (
  996. sa.PrimaryKeyConstraint("id", name="dataset_metadata_pkey"),
  997. sa.Index("dataset_metadata_tenant_idx", "tenant_id"),
  998. sa.Index("dataset_metadata_dataset_idx", "dataset_id"),
  999. )
  1000. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1001. tenant_id = mapped_column(StringUUID, nullable=False)
  1002. dataset_id = mapped_column(StringUUID, nullable=False)
  1003. type: Mapped[str] = mapped_column(String(255), nullable=False)
  1004. name: Mapped[str] = mapped_column(String(255), nullable=False)
  1005. created_at: Mapped[datetime] = mapped_column(
  1006. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  1007. )
  1008. updated_at: Mapped[datetime] = mapped_column(
  1009. DateTime, nullable=False, server_default=sa.text("CURRENT_TIMESTAMP(0)")
  1010. )
  1011. created_by = mapped_column(StringUUID, nullable=False)
  1012. updated_by = mapped_column(StringUUID, nullable=True)
  1013. class DatasetMetadataBinding(Base):
  1014. __tablename__ = "dataset_metadata_bindings"
  1015. __table_args__ = (
  1016. sa.PrimaryKeyConstraint("id", name="dataset_metadata_binding_pkey"),
  1017. sa.Index("dataset_metadata_binding_tenant_idx", "tenant_id"),
  1018. sa.Index("dataset_metadata_binding_dataset_idx", "dataset_id"),
  1019. sa.Index("dataset_metadata_binding_metadata_idx", "metadata_id"),
  1020. sa.Index("dataset_metadata_binding_document_idx", "document_id"),
  1021. )
  1022. id = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  1023. tenant_id = mapped_column(StringUUID, nullable=False)
  1024. dataset_id = mapped_column(StringUUID, nullable=False)
  1025. metadata_id = mapped_column(StringUUID, nullable=False)
  1026. document_id = mapped_column(StringUUID, nullable=False)
  1027. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  1028. created_by = mapped_column(StringUUID, nullable=False)