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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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. from sqlalchemy import func
  15. from sqlalchemy.dialects.postgresql import JSONB
  16. from sqlalchemy.orm import Mapped, mapped_column
  17. from configs import dify_config
  18. from core.rag.index_processor.constant.built_in_field import BuiltInField, MetadataDataSource
  19. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  20. from extensions.ext_storage import storage
  21. from services.entities.knowledge_entities.knowledge_entities import ParentMode, Rule
  22. from .account import Account
  23. from .base import Base
  24. from .engine import db
  25. from .model import App, Tag, TagBinding, UploadFile
  26. from .types import StringUUID
  27. class DatasetPermissionEnum(enum.StrEnum):
  28. ONLY_ME = "only_me"
  29. ALL_TEAM = "all_team_members"
  30. PARTIAL_TEAM = "partial_members"
  31. class Dataset(Base):
  32. __tablename__ = "datasets"
  33. __table_args__ = (
  34. db.PrimaryKeyConstraint("id", name="dataset_pkey"),
  35. db.Index("dataset_tenant_idx", "tenant_id"),
  36. db.Index("retrieval_model_idx", "retrieval_model", postgresql_using="gin"),
  37. )
  38. INDEXING_TECHNIQUE_LIST = ["high_quality", "economy", None]
  39. PROVIDER_LIST = ["vendor", "external", None]
  40. id = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  41. tenant_id: Mapped[str] = mapped_column(StringUUID)
  42. name: Mapped[str] = mapped_column(db.String(255))
  43. description = mapped_column(db.Text, nullable=True)
  44. provider: Mapped[str] = mapped_column(db.String(255), server_default=db.text("'vendor'::character varying"))
  45. permission: Mapped[str] = mapped_column(db.String(255), server_default=db.text("'only_me'::character varying"))
  46. data_source_type = mapped_column(db.String(255))
  47. indexing_technique: Mapped[Optional[str]] = mapped_column(db.String(255))
  48. index_struct = mapped_column(db.Text, nullable=True)
  49. created_by = mapped_column(StringUUID, nullable=False)
  50. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  51. updated_by = mapped_column(StringUUID, nullable=True)
  52. updated_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  53. embedding_model = db.Column(db.String(255), nullable=True) # TODO: mapped_column
  54. embedding_model_provider = db.Column(db.String(255), nullable=True) # TODO: mapped_column
  55. collection_binding_id = mapped_column(StringUUID, nullable=True)
  56. retrieval_model = mapped_column(JSONB, nullable=True)
  57. built_in_field_enabled = mapped_column(db.Boolean, nullable=False, server_default=db.text("false"))
  58. @property
  59. def dataset_keyword_table(self):
  60. dataset_keyword_table = (
  61. db.session.query(DatasetKeywordTable).filter(DatasetKeywordTable.dataset_id == self.id).first()
  62. )
  63. if dataset_keyword_table:
  64. return dataset_keyword_table
  65. return None
  66. @property
  67. def index_struct_dict(self):
  68. return json.loads(self.index_struct) if self.index_struct else None
  69. @property
  70. def external_retrieval_model(self):
  71. default_retrieval_model = {
  72. "top_k": 2,
  73. "score_threshold": 0.0,
  74. }
  75. return self.retrieval_model or default_retrieval_model
  76. @property
  77. def created_by_account(self):
  78. return db.session.get(Account, self.created_by)
  79. @property
  80. def latest_process_rule(self):
  81. return (
  82. db.session.query(DatasetProcessRule)
  83. .filter(DatasetProcessRule.dataset_id == self.id)
  84. .order_by(DatasetProcessRule.created_at.desc())
  85. .first()
  86. )
  87. @property
  88. def app_count(self):
  89. return (
  90. db.session.query(func.count(AppDatasetJoin.id))
  91. .filter(AppDatasetJoin.dataset_id == self.id, App.id == AppDatasetJoin.app_id)
  92. .scalar()
  93. )
  94. @property
  95. def document_count(self):
  96. return db.session.query(func.count(Document.id)).filter(Document.dataset_id == self.id).scalar()
  97. @property
  98. def available_document_count(self):
  99. return (
  100. db.session.query(func.count(Document.id))
  101. .filter(
  102. Document.dataset_id == self.id,
  103. Document.indexing_status == "completed",
  104. Document.enabled == True,
  105. Document.archived == False,
  106. )
  107. .scalar()
  108. )
  109. @property
  110. def available_segment_count(self):
  111. return (
  112. db.session.query(func.count(DocumentSegment.id))
  113. .filter(
  114. DocumentSegment.dataset_id == self.id,
  115. DocumentSegment.status == "completed",
  116. DocumentSegment.enabled == True,
  117. )
  118. .scalar()
  119. )
  120. @property
  121. def word_count(self):
  122. return (
  123. db.session.query(Document)
  124. .with_entities(func.coalesce(func.sum(Document.word_count), 0))
  125. .filter(Document.dataset_id == self.id)
  126. .scalar()
  127. )
  128. @property
  129. def doc_form(self):
  130. document = db.session.query(Document).filter(Document.dataset_id == self.id).first()
  131. if document:
  132. return document.doc_form
  133. return None
  134. @property
  135. def retrieval_model_dict(self):
  136. default_retrieval_model = {
  137. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  138. "reranking_enable": False,
  139. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  140. "top_k": 2,
  141. "score_threshold_enabled": False,
  142. }
  143. return self.retrieval_model or default_retrieval_model
  144. @property
  145. def tags(self):
  146. tags = (
  147. db.session.query(Tag)
  148. .join(TagBinding, Tag.id == TagBinding.tag_id)
  149. .filter(
  150. TagBinding.target_id == self.id,
  151. TagBinding.tenant_id == self.tenant_id,
  152. Tag.tenant_id == self.tenant_id,
  153. Tag.type == "knowledge",
  154. )
  155. .all()
  156. )
  157. return tags or []
  158. @property
  159. def external_knowledge_info(self):
  160. if self.provider != "external":
  161. return None
  162. external_knowledge_binding = (
  163. db.session.query(ExternalKnowledgeBindings).filter(ExternalKnowledgeBindings.dataset_id == self.id).first()
  164. )
  165. if not external_knowledge_binding:
  166. return None
  167. external_knowledge_api = (
  168. db.session.query(ExternalKnowledgeApis)
  169. .filter(ExternalKnowledgeApis.id == external_knowledge_binding.external_knowledge_api_id)
  170. .first()
  171. )
  172. if not external_knowledge_api:
  173. return None
  174. return {
  175. "external_knowledge_id": external_knowledge_binding.external_knowledge_id,
  176. "external_knowledge_api_id": external_knowledge_api.id,
  177. "external_knowledge_api_name": external_knowledge_api.name,
  178. "external_knowledge_api_endpoint": json.loads(external_knowledge_api.settings).get("endpoint", ""),
  179. }
  180. @property
  181. def doc_metadata(self):
  182. dataset_metadatas = db.session.query(DatasetMetadata).filter(DatasetMetadata.dataset_id == self.id).all()
  183. doc_metadata = [
  184. {
  185. "id": dataset_metadata.id,
  186. "name": dataset_metadata.name,
  187. "type": dataset_metadata.type,
  188. }
  189. for dataset_metadata in dataset_metadatas
  190. ]
  191. if self.built_in_field_enabled:
  192. doc_metadata.append(
  193. {
  194. "id": "built-in",
  195. "name": BuiltInField.document_name.value,
  196. "type": "string",
  197. }
  198. )
  199. doc_metadata.append(
  200. {
  201. "id": "built-in",
  202. "name": BuiltInField.uploader.value,
  203. "type": "string",
  204. }
  205. )
  206. doc_metadata.append(
  207. {
  208. "id": "built-in",
  209. "name": BuiltInField.upload_date.value,
  210. "type": "time",
  211. }
  212. )
  213. doc_metadata.append(
  214. {
  215. "id": "built-in",
  216. "name": BuiltInField.last_update_date.value,
  217. "type": "time",
  218. }
  219. )
  220. doc_metadata.append(
  221. {
  222. "id": "built-in",
  223. "name": BuiltInField.source.value,
  224. "type": "string",
  225. }
  226. )
  227. return doc_metadata
  228. @staticmethod
  229. def gen_collection_name_by_id(dataset_id: str) -> str:
  230. normalized_dataset_id = dataset_id.replace("-", "_")
  231. return f"{dify_config.VECTOR_INDEX_NAME_PREFIX}_{normalized_dataset_id}_Node"
  232. class DatasetProcessRule(Base):
  233. __tablename__ = "dataset_process_rules"
  234. __table_args__ = (
  235. db.PrimaryKeyConstraint("id", name="dataset_process_rule_pkey"),
  236. db.Index("dataset_process_rule_dataset_id_idx", "dataset_id"),
  237. )
  238. id = mapped_column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  239. dataset_id = mapped_column(StringUUID, nullable=False)
  240. mode = mapped_column(db.String(255), nullable=False, server_default=db.text("'automatic'::character varying"))
  241. rules = mapped_column(db.Text, nullable=True)
  242. created_by = mapped_column(StringUUID, nullable=False)
  243. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  244. MODES = ["automatic", "custom", "hierarchical"]
  245. PRE_PROCESSING_RULES = ["remove_stopwords", "remove_extra_spaces", "remove_urls_emails"]
  246. AUTOMATIC_RULES: dict[str, Any] = {
  247. "pre_processing_rules": [
  248. {"id": "remove_extra_spaces", "enabled": True},
  249. {"id": "remove_urls_emails", "enabled": False},
  250. ],
  251. "segmentation": {"delimiter": "\n", "max_tokens": 500, "chunk_overlap": 50},
  252. }
  253. def to_dict(self):
  254. return {
  255. "id": self.id,
  256. "dataset_id": self.dataset_id,
  257. "mode": self.mode,
  258. "rules": self.rules_dict,
  259. }
  260. @property
  261. def rules_dict(self):
  262. try:
  263. return json.loads(self.rules) if self.rules else None
  264. except JSONDecodeError:
  265. return None
  266. class Document(Base):
  267. __tablename__ = "documents"
  268. __table_args__ = (
  269. db.PrimaryKeyConstraint("id", name="document_pkey"),
  270. db.Index("document_dataset_id_idx", "dataset_id"),
  271. db.Index("document_is_paused_idx", "is_paused"),
  272. db.Index("document_tenant_idx", "tenant_id"),
  273. db.Index("document_metadata_idx", "doc_metadata", postgresql_using="gin"),
  274. )
  275. # initial fields
  276. id = mapped_column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  277. tenant_id = mapped_column(StringUUID, nullable=False)
  278. dataset_id = mapped_column(StringUUID, nullable=False)
  279. position = mapped_column(db.Integer, nullable=False)
  280. data_source_type = mapped_column(db.String(255), nullable=False)
  281. data_source_info = mapped_column(db.Text, nullable=True)
  282. dataset_process_rule_id = mapped_column(StringUUID, nullable=True)
  283. batch = mapped_column(db.String(255), nullable=False)
  284. name = mapped_column(db.String(255), nullable=False)
  285. created_from = mapped_column(db.String(255), nullable=False)
  286. created_by = mapped_column(StringUUID, nullable=False)
  287. created_api_request_id = mapped_column(StringUUID, nullable=True)
  288. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  289. # start processing
  290. processing_started_at = mapped_column(db.DateTime, nullable=True)
  291. # parsing
  292. file_id = mapped_column(db.Text, nullable=True)
  293. word_count = mapped_column(db.Integer, nullable=True)
  294. parsing_completed_at = mapped_column(db.DateTime, nullable=True)
  295. # cleaning
  296. cleaning_completed_at = mapped_column(db.DateTime, nullable=True)
  297. # split
  298. splitting_completed_at = mapped_column(db.DateTime, nullable=True)
  299. # indexing
  300. tokens = mapped_column(db.Integer, nullable=True)
  301. indexing_latency = mapped_column(db.Float, nullable=True)
  302. completed_at = mapped_column(db.DateTime, nullable=True)
  303. # pause
  304. is_paused = mapped_column(db.Boolean, nullable=True, server_default=db.text("false"))
  305. paused_by = mapped_column(StringUUID, nullable=True)
  306. paused_at = mapped_column(db.DateTime, nullable=True)
  307. # error
  308. error = mapped_column(db.Text, nullable=True)
  309. stopped_at = mapped_column(db.DateTime, nullable=True)
  310. # basic fields
  311. indexing_status = mapped_column(
  312. db.String(255), nullable=False, server_default=db.text("'waiting'::character varying")
  313. )
  314. enabled = mapped_column(db.Boolean, nullable=False, server_default=db.text("true"))
  315. disabled_at = mapped_column(db.DateTime, nullable=True)
  316. disabled_by = mapped_column(StringUUID, nullable=True)
  317. archived = mapped_column(db.Boolean, nullable=False, server_default=db.text("false"))
  318. archived_reason = mapped_column(db.String(255), nullable=True)
  319. archived_by = mapped_column(StringUUID, nullable=True)
  320. archived_at = mapped_column(db.DateTime, nullable=True)
  321. updated_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  322. doc_type = mapped_column(db.String(40), nullable=True)
  323. doc_metadata = mapped_column(JSONB, nullable=True)
  324. doc_form = mapped_column(db.String(255), nullable=False, server_default=db.text("'text_model'::character varying"))
  325. doc_language = mapped_column(db.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. .filter(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).filter(Dataset.id == self.dataset_id).one_or_none()
  392. @property
  393. def segment_count(self):
  394. return db.session.query(DocumentSegment).filter(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. .filter(DocumentSegment.document_id == self.id)
  401. .scalar()
  402. )
  403. @property
  404. def uploader(self):
  405. user = db.session.query(Account).filter(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. .filter(
  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": 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": 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. db.PrimaryKeyConstraint("id", name="document_segment_pkey"),
  583. db.Index("document_segment_dataset_id_idx", "dataset_id"),
  584. db.Index("document_segment_document_id_idx", "document_id"),
  585. db.Index("document_segment_tenant_dataset_idx", "dataset_id", "tenant_id"),
  586. db.Index("document_segment_tenant_document_idx", "document_id", "tenant_id"),
  587. db.Index("document_segment_node_dataset_idx", "index_node_id", "dataset_id"),
  588. db.Index("document_segment_tenant_idx", "tenant_id"),
  589. )
  590. # initial fields
  591. id = mapped_column(StringUUID, nullable=False, server_default=db.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(db.Text, nullable=False)
  597. answer = mapped_column(db.Text, nullable=True)
  598. word_count: Mapped[int]
  599. tokens: Mapped[int]
  600. # indexing fields
  601. keywords = mapped_column(db.JSON, nullable=True)
  602. index_node_id = mapped_column(db.String(255), nullable=True)
  603. index_node_hash = mapped_column(db.String(255), nullable=True)
  604. # basic fields
  605. hit_count = mapped_column(db.Integer, nullable=False, default=0)
  606. enabled = mapped_column(db.Boolean, nullable=False, server_default=db.text("true"))
  607. disabled_at = mapped_column(db.DateTime, nullable=True)
  608. disabled_by = mapped_column(StringUUID, nullable=True)
  609. status: Mapped[str] = mapped_column(db.String(255), server_default=db.text("'waiting'::character varying"))
  610. created_by = mapped_column(StringUUID, nullable=False)
  611. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  612. updated_by = mapped_column(StringUUID, nullable=True)
  613. updated_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  614. indexing_at = mapped_column(db.DateTime, nullable=True)
  615. completed_at: Mapped[Optional[datetime]] = mapped_column(db.DateTime, nullable=True)
  616. error = mapped_column(db.Text, nullable=True)
  617. stopped_at = mapped_column(db.DateTime, nullable=True)
  618. @property
  619. def dataset(self):
  620. return db.session.query(Dataset).filter(Dataset.id == self.dataset_id).first()
  621. @property
  622. def document(self):
  623. return db.session.query(Document).filter(Document.id == self.document_id).first()
  624. @property
  625. def previous_segment(self):
  626. return (
  627. db.session.query(DocumentSegment)
  628. .filter(DocumentSegment.document_id == self.document_id, DocumentSegment.position == self.position - 1)
  629. .first()
  630. )
  631. @property
  632. def next_segment(self):
  633. return (
  634. db.session.query(DocumentSegment)
  635. .filter(DocumentSegment.document_id == self.document_id, DocumentSegment.position == self.position + 1)
  636. .first()
  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. .filter(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. .filter(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. db.PrimaryKeyConstraint("id", name="child_chunk_pkey"),
  715. db.Index("child_chunk_dataset_id_idx", "tenant_id", "dataset_id", "document_id", "segment_id", "index_node_id"),
  716. db.Index("child_chunks_node_idx", "index_node_id", "dataset_id"),
  717. db.Index("child_chunks_segment_idx", "segment_id"),
  718. )
  719. # initial fields
  720. id = mapped_column(StringUUID, nullable=False, server_default=db.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_column(db.Integer, nullable=False)
  726. content = mapped_column(db.Text, nullable=False)
  727. word_count = mapped_column(db.Integer, nullable=False)
  728. # indexing fields
  729. index_node_id = mapped_column(db.String(255), nullable=True)
  730. index_node_hash = mapped_column(db.String(255), nullable=True)
  731. type = mapped_column(db.String(255), nullable=False, server_default=db.text("'automatic'::character varying"))
  732. created_by = mapped_column(StringUUID, nullable=False)
  733. created_at = mapped_column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  734. updated_by = mapped_column(StringUUID, nullable=True)
  735. updated_at = mapped_column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  736. indexing_at = mapped_column(db.DateTime, nullable=True)
  737. completed_at = mapped_column(db.DateTime, nullable=True)
  738. error = mapped_column(db.Text, nullable=True)
  739. @property
  740. def dataset(self):
  741. return db.session.query(Dataset).filter(Dataset.id == self.dataset_id).first()
  742. @property
  743. def document(self):
  744. return db.session.query(Document).filter(Document.id == self.document_id).first()
  745. @property
  746. def segment(self):
  747. return db.session.query(DocumentSegment).filter(DocumentSegment.id == self.segment_id).first()
  748. class AppDatasetJoin(Base):
  749. __tablename__ = "app_dataset_joins"
  750. __table_args__ = (
  751. db.PrimaryKeyConstraint("id", name="app_dataset_join_pkey"),
  752. db.Index("app_dataset_join_app_dataset_idx", "dataset_id", "app_id"),
  753. )
  754. id = mapped_column(StringUUID, primary_key=True, nullable=False, server_default=db.text("uuid_generate_v4()"))
  755. app_id = mapped_column(StringUUID, nullable=False)
  756. dataset_id = mapped_column(StringUUID, nullable=False)
  757. created_at = mapped_column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
  758. @property
  759. def app(self):
  760. return db.session.get(App, self.app_id)
  761. class DatasetQuery(Base):
  762. __tablename__ = "dataset_queries"
  763. __table_args__ = (
  764. db.PrimaryKeyConstraint("id", name="dataset_query_pkey"),
  765. db.Index("dataset_query_dataset_id_idx", "dataset_id"),
  766. )
  767. id = mapped_column(StringUUID, primary_key=True, nullable=False, server_default=db.text("uuid_generate_v4()"))
  768. dataset_id = mapped_column(StringUUID, nullable=False)
  769. content = mapped_column(db.Text, nullable=False)
  770. source = mapped_column(db.String(255), nullable=False)
  771. source_app_id = mapped_column(StringUUID, nullable=True)
  772. created_by_role = mapped_column(db.String, nullable=False)
  773. created_by = mapped_column(StringUUID, nullable=False)
  774. created_at = mapped_column(db.DateTime, nullable=False, server_default=db.func.current_timestamp())
  775. class DatasetKeywordTable(Base):
  776. __tablename__ = "dataset_keyword_tables"
  777. __table_args__ = (
  778. db.PrimaryKeyConstraint("id", name="dataset_keyword_table_pkey"),
  779. db.Index("dataset_keyword_table_dataset_id_idx", "dataset_id"),
  780. )
  781. id = mapped_column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  782. dataset_id = mapped_column(StringUUID, nullable=False, unique=True)
  783. keyword_table = mapped_column(db.Text, nullable=False)
  784. data_source_type = mapped_column(
  785. db.String(255), nullable=False, server_default=db.text("'database'::character varying")
  786. )
  787. @property
  788. def keyword_table_dict(self):
  789. class SetDecoder(json.JSONDecoder):
  790. def __init__(self, *args, **kwargs):
  791. super().__init__(object_hook=self.object_hook, *args, **kwargs)
  792. def object_hook(self, dct):
  793. if isinstance(dct, dict):
  794. for keyword, node_idxs in dct.items():
  795. if isinstance(node_idxs, list):
  796. dct[keyword] = set(node_idxs)
  797. return dct
  798. # get dataset
  799. dataset = db.session.query(Dataset).filter_by(id=self.dataset_id).first()
  800. if not dataset:
  801. return None
  802. if self.data_source_type == "database":
  803. return json.loads(self.keyword_table, cls=SetDecoder) if self.keyword_table else None
  804. else:
  805. file_key = "keyword_files/" + dataset.tenant_id + "/" + self.dataset_id + ".txt"
  806. try:
  807. keyword_table_text = storage.load_once(file_key)
  808. if keyword_table_text:
  809. return json.loads(keyword_table_text.decode("utf-8"), cls=SetDecoder)
  810. return None
  811. except Exception as e:
  812. logging.exception(f"Failed to load keyword table from file: {file_key}")
  813. return None
  814. class Embedding(Base):
  815. __tablename__ = "embeddings"
  816. __table_args__ = (
  817. db.PrimaryKeyConstraint("id", name="embedding_pkey"),
  818. db.UniqueConstraint("model_name", "hash", "provider_name", name="embedding_hash_idx"),
  819. db.Index("created_at_idx", "created_at"),
  820. )
  821. id = mapped_column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  822. model_name = mapped_column(
  823. db.String(255), nullable=False, server_default=db.text("'text-embedding-ada-002'::character varying")
  824. )
  825. hash = mapped_column(db.String(64), nullable=False)
  826. embedding = mapped_column(db.LargeBinary, nullable=False)
  827. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  828. provider_name = mapped_column(db.String(255), nullable=False, server_default=db.text("''::character varying"))
  829. def set_embedding(self, embedding_data: list[float]):
  830. self.embedding = pickle.dumps(embedding_data, protocol=pickle.HIGHEST_PROTOCOL)
  831. def get_embedding(self) -> list[float]:
  832. return cast(list[float], pickle.loads(self.embedding)) # noqa: S301
  833. class DatasetCollectionBinding(Base):
  834. __tablename__ = "dataset_collection_bindings"
  835. __table_args__ = (
  836. db.PrimaryKeyConstraint("id", name="dataset_collection_bindings_pkey"),
  837. db.Index("provider_model_name_idx", "provider_name", "model_name"),
  838. )
  839. id = mapped_column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  840. provider_name = mapped_column(db.String(255), nullable=False)
  841. model_name = mapped_column(db.String(255), nullable=False)
  842. type = mapped_column(db.String(40), server_default=db.text("'dataset'::character varying"), nullable=False)
  843. collection_name = mapped_column(db.String(64), nullable=False)
  844. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  845. class TidbAuthBinding(Base):
  846. __tablename__ = "tidb_auth_bindings"
  847. __table_args__ = (
  848. db.PrimaryKeyConstraint("id", name="tidb_auth_bindings_pkey"),
  849. db.Index("tidb_auth_bindings_tenant_idx", "tenant_id"),
  850. db.Index("tidb_auth_bindings_active_idx", "active"),
  851. db.Index("tidb_auth_bindings_created_at_idx", "created_at"),
  852. db.Index("tidb_auth_bindings_status_idx", "status"),
  853. )
  854. id = mapped_column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  855. tenant_id = mapped_column(StringUUID, nullable=True)
  856. cluster_id = mapped_column(db.String(255), nullable=False)
  857. cluster_name = mapped_column(db.String(255), nullable=False)
  858. active = mapped_column(db.Boolean, nullable=False, server_default=db.text("false"))
  859. status = mapped_column(db.String(255), nullable=False, server_default=db.text("CREATING"))
  860. account = mapped_column(db.String(255), nullable=False)
  861. password = mapped_column(db.String(255), nullable=False)
  862. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  863. class Whitelist(Base):
  864. __tablename__ = "whitelists"
  865. __table_args__ = (
  866. db.PrimaryKeyConstraint("id", name="whitelists_pkey"),
  867. db.Index("whitelists_tenant_idx", "tenant_id"),
  868. )
  869. id = mapped_column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  870. tenant_id = mapped_column(StringUUID, nullable=True)
  871. category = mapped_column(db.String(255), nullable=False)
  872. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  873. class DatasetPermission(Base):
  874. __tablename__ = "dataset_permissions"
  875. __table_args__ = (
  876. db.PrimaryKeyConstraint("id", name="dataset_permission_pkey"),
  877. db.Index("idx_dataset_permissions_dataset_id", "dataset_id"),
  878. db.Index("idx_dataset_permissions_account_id", "account_id"),
  879. db.Index("idx_dataset_permissions_tenant_id", "tenant_id"),
  880. )
  881. id = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"), primary_key=True)
  882. dataset_id = mapped_column(StringUUID, nullable=False)
  883. account_id = mapped_column(StringUUID, nullable=False)
  884. tenant_id = mapped_column(StringUUID, nullable=False)
  885. has_permission = mapped_column(db.Boolean, nullable=False, server_default=db.text("true"))
  886. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  887. class ExternalKnowledgeApis(Base):
  888. __tablename__ = "external_knowledge_apis"
  889. __table_args__ = (
  890. db.PrimaryKeyConstraint("id", name="external_knowledge_apis_pkey"),
  891. db.Index("external_knowledge_apis_tenant_idx", "tenant_id"),
  892. db.Index("external_knowledge_apis_name_idx", "name"),
  893. )
  894. id = mapped_column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  895. name = mapped_column(db.String(255), nullable=False)
  896. description = mapped_column(db.String(255), nullable=False)
  897. tenant_id = mapped_column(StringUUID, nullable=False)
  898. settings = mapped_column(db.Text, nullable=True)
  899. created_by = mapped_column(StringUUID, nullable=False)
  900. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  901. updated_by = mapped_column(StringUUID, nullable=True)
  902. updated_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  903. def to_dict(self):
  904. return {
  905. "id": self.id,
  906. "tenant_id": self.tenant_id,
  907. "name": self.name,
  908. "description": self.description,
  909. "settings": self.settings_dict,
  910. "dataset_bindings": self.dataset_bindings,
  911. "created_by": self.created_by,
  912. "created_at": self.created_at.isoformat(),
  913. }
  914. @property
  915. def settings_dict(self):
  916. try:
  917. return json.loads(self.settings) if self.settings else None
  918. except JSONDecodeError:
  919. return None
  920. @property
  921. def dataset_bindings(self):
  922. external_knowledge_bindings = (
  923. db.session.query(ExternalKnowledgeBindings)
  924. .filter(ExternalKnowledgeBindings.external_knowledge_api_id == self.id)
  925. .all()
  926. )
  927. dataset_ids = [binding.dataset_id for binding in external_knowledge_bindings]
  928. datasets = db.session.query(Dataset).filter(Dataset.id.in_(dataset_ids)).all()
  929. dataset_bindings = []
  930. for dataset in datasets:
  931. dataset_bindings.append({"id": dataset.id, "name": dataset.name})
  932. return dataset_bindings
  933. class ExternalKnowledgeBindings(Base):
  934. __tablename__ = "external_knowledge_bindings"
  935. __table_args__ = (
  936. db.PrimaryKeyConstraint("id", name="external_knowledge_bindings_pkey"),
  937. db.Index("external_knowledge_bindings_tenant_idx", "tenant_id"),
  938. db.Index("external_knowledge_bindings_dataset_idx", "dataset_id"),
  939. db.Index("external_knowledge_bindings_external_knowledge_idx", "external_knowledge_id"),
  940. db.Index("external_knowledge_bindings_external_knowledge_api_idx", "external_knowledge_api_id"),
  941. )
  942. id = mapped_column(StringUUID, nullable=False, server_default=db.text("uuid_generate_v4()"))
  943. tenant_id = mapped_column(StringUUID, nullable=False)
  944. external_knowledge_api_id = mapped_column(StringUUID, nullable=False)
  945. dataset_id = mapped_column(StringUUID, nullable=False)
  946. external_knowledge_id = mapped_column(db.Text, nullable=False)
  947. created_by = mapped_column(StringUUID, nullable=False)
  948. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  949. updated_by = mapped_column(StringUUID, nullable=True)
  950. updated_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  951. class DatasetAutoDisableLog(Base):
  952. __tablename__ = "dataset_auto_disable_logs"
  953. __table_args__ = (
  954. db.PrimaryKeyConstraint("id", name="dataset_auto_disable_log_pkey"),
  955. db.Index("dataset_auto_disable_log_tenant_idx", "tenant_id"),
  956. db.Index("dataset_auto_disable_log_dataset_idx", "dataset_id"),
  957. db.Index("dataset_auto_disable_log_created_atx", "created_at"),
  958. )
  959. id = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  960. tenant_id = mapped_column(StringUUID, nullable=False)
  961. dataset_id = mapped_column(StringUUID, nullable=False)
  962. document_id = mapped_column(StringUUID, nullable=False)
  963. notified = mapped_column(db.Boolean, nullable=False, server_default=db.text("false"))
  964. created_at = mapped_column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  965. class RateLimitLog(Base):
  966. __tablename__ = "rate_limit_logs"
  967. __table_args__ = (
  968. db.PrimaryKeyConstraint("id", name="rate_limit_log_pkey"),
  969. db.Index("rate_limit_log_tenant_idx", "tenant_id"),
  970. db.Index("rate_limit_log_operation_idx", "operation"),
  971. )
  972. id = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  973. tenant_id = mapped_column(StringUUID, nullable=False)
  974. subscription_plan = mapped_column(db.String(255), nullable=False)
  975. operation = mapped_column(db.String(255), nullable=False)
  976. created_at = mapped_column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  977. class DatasetMetadata(Base):
  978. __tablename__ = "dataset_metadatas"
  979. __table_args__ = (
  980. db.PrimaryKeyConstraint("id", name="dataset_metadata_pkey"),
  981. db.Index("dataset_metadata_tenant_idx", "tenant_id"),
  982. db.Index("dataset_metadata_dataset_idx", "dataset_id"),
  983. )
  984. id = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  985. tenant_id = mapped_column(StringUUID, nullable=False)
  986. dataset_id = mapped_column(StringUUID, nullable=False)
  987. type = mapped_column(db.String(255), nullable=False)
  988. name = mapped_column(db.String(255), nullable=False)
  989. created_at = mapped_column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  990. updated_at = mapped_column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP(0)"))
  991. created_by = mapped_column(StringUUID, nullable=False)
  992. updated_by = mapped_column(StringUUID, nullable=True)
  993. class DatasetMetadataBinding(Base):
  994. __tablename__ = "dataset_metadata_bindings"
  995. __table_args__ = (
  996. db.PrimaryKeyConstraint("id", name="dataset_metadata_binding_pkey"),
  997. db.Index("dataset_metadata_binding_tenant_idx", "tenant_id"),
  998. db.Index("dataset_metadata_binding_dataset_idx", "dataset_id"),
  999. db.Index("dataset_metadata_binding_metadata_idx", "metadata_id"),
  1000. db.Index("dataset_metadata_binding_document_idx", "document_id"),
  1001. )
  1002. id = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  1003. tenant_id = mapped_column(StringUUID, nullable=False)
  1004. dataset_id = mapped_column(StringUUID, nullable=False)
  1005. metadata_id = mapped_column(StringUUID, nullable=False)
  1006. document_id = mapped_column(StringUUID, nullable=False)
  1007. created_at = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  1008. created_by = mapped_column(StringUUID, nullable=False)