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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. from typing import Any, Optional
  6. import click
  7. import sqlalchemy as sa
  8. from flask import current_app
  9. from pydantic import TypeAdapter
  10. from sqlalchemy import select
  11. from sqlalchemy.exc import SQLAlchemyError
  12. from configs import dify_config
  13. from constants.languages import languages
  14. from core.plugin.entities.plugin import ToolProviderID
  15. from core.rag.datasource.vdb.vector_factory import Vector
  16. from core.rag.datasource.vdb.vector_type import VectorType
  17. from core.rag.index_processor.constant.built_in_field import BuiltInField
  18. from core.rag.models.document import Document
  19. from core.tools.utils.system_oauth_encryption import encrypt_system_oauth_params
  20. from events.app_event import app_was_created
  21. from extensions.ext_database import db
  22. from extensions.ext_redis import redis_client
  23. from extensions.ext_storage import storage
  24. from libs.helper import email as email_validate
  25. from libs.password import hash_password, password_pattern, valid_password
  26. from libs.rsa import generate_key_pair
  27. from models import Tenant
  28. from models.dataset import Dataset, DatasetCollectionBinding, DatasetMetadata, DatasetMetadataBinding, DocumentSegment
  29. from models.dataset import Document as DatasetDocument
  30. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  31. from models.provider import Provider, ProviderModel
  32. from models.tools import ToolOAuthSystemClient
  33. from services.account_service import AccountService, RegisterService, TenantService
  34. from services.clear_free_plan_tenant_expired_logs import ClearFreePlanTenantExpiredLogs
  35. from services.plugin.data_migration import PluginDataMigration
  36. from services.plugin.plugin_migration import PluginMigration
  37. from tasks.remove_app_and_related_data_task import delete_draft_variables_batch
  38. logger = logging.getLogger(__name__)
  39. @click.command("reset-password", help="Reset the account password.")
  40. @click.option("--email", prompt=True, help="Account email to reset password for")
  41. @click.option("--new-password", prompt=True, help="New password")
  42. @click.option("--password-confirm", prompt=True, help="Confirm new password")
  43. def reset_password(email, new_password, password_confirm):
  44. """
  45. Reset password of owner account
  46. Only available in SELF_HOSTED mode
  47. """
  48. if str(new_password).strip() != str(password_confirm).strip():
  49. click.echo(click.style("Passwords do not match.", fg="red"))
  50. return
  51. account = db.session.query(Account).where(Account.email == email).one_or_none()
  52. if not account:
  53. click.echo(click.style(f"Account not found for email: {email}", fg="red"))
  54. return
  55. try:
  56. valid_password(new_password)
  57. except:
  58. click.echo(click.style(f"Invalid password. Must match {password_pattern}", fg="red"))
  59. return
  60. # generate password salt
  61. salt = secrets.token_bytes(16)
  62. base64_salt = base64.b64encode(salt).decode()
  63. # encrypt password with salt
  64. password_hashed = hash_password(new_password, salt)
  65. base64_password_hashed = base64.b64encode(password_hashed).decode()
  66. account.password = base64_password_hashed
  67. account.password_salt = base64_salt
  68. db.session.commit()
  69. AccountService.reset_login_error_rate_limit(email)
  70. click.echo(click.style("Password reset successfully.", fg="green"))
  71. @click.command("reset-email", help="Reset the account email.")
  72. @click.option("--email", prompt=True, help="Current account email")
  73. @click.option("--new-email", prompt=True, help="New email")
  74. @click.option("--email-confirm", prompt=True, help="Confirm new email")
  75. def reset_email(email, new_email, email_confirm):
  76. """
  77. Replace account email
  78. :return:
  79. """
  80. if str(new_email).strip() != str(email_confirm).strip():
  81. click.echo(click.style("New emails do not match.", fg="red"))
  82. return
  83. account = db.session.query(Account).where(Account.email == email).one_or_none()
  84. if not account:
  85. click.echo(click.style(f"Account not found for email: {email}", fg="red"))
  86. return
  87. try:
  88. email_validate(new_email)
  89. except:
  90. click.echo(click.style(f"Invalid email: {new_email}", fg="red"))
  91. return
  92. account.email = new_email
  93. db.session.commit()
  94. click.echo(click.style("Email updated successfully.", fg="green"))
  95. @click.command(
  96. "reset-encrypt-key-pair",
  97. help="Reset the asymmetric key pair of workspace for encrypt LLM credentials. "
  98. "After the reset, all LLM credentials will become invalid, "
  99. "requiring re-entry."
  100. "Only support SELF_HOSTED mode.",
  101. )
  102. @click.confirmation_option(
  103. prompt=click.style(
  104. "Are you sure you want to reset encrypt key pair? This operation cannot be rolled back!", fg="red"
  105. )
  106. )
  107. def reset_encrypt_key_pair():
  108. """
  109. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  110. After the reset, all LLM credentials will become invalid, requiring re-entry.
  111. Only support SELF_HOSTED mode.
  112. """
  113. if dify_config.EDITION != "SELF_HOSTED":
  114. click.echo(click.style("This command is only for SELF_HOSTED installations.", fg="red"))
  115. return
  116. tenants = db.session.query(Tenant).all()
  117. for tenant in tenants:
  118. if not tenant:
  119. click.echo(click.style("No workspaces found. Run /install first.", fg="red"))
  120. return
  121. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  122. db.session.query(Provider).where(Provider.provider_type == "custom", Provider.tenant_id == tenant.id).delete()
  123. db.session.query(ProviderModel).where(ProviderModel.tenant_id == tenant.id).delete()
  124. db.session.commit()
  125. click.echo(
  126. click.style(
  127. f"Congratulations! The asymmetric key pair of workspace {tenant.id} has been reset.",
  128. fg="green",
  129. )
  130. )
  131. @click.command("vdb-migrate", help="Migrate vector db.")
  132. @click.option("--scope", default="all", prompt=False, help="The scope of vector database to migrate, Default is All.")
  133. def vdb_migrate(scope: str):
  134. if scope in {"knowledge", "all"}:
  135. migrate_knowledge_vector_database()
  136. if scope in {"annotation", "all"}:
  137. migrate_annotation_vector_database()
  138. def migrate_annotation_vector_database():
  139. """
  140. Migrate annotation datas to target vector database .
  141. """
  142. click.echo(click.style("Starting annotation data migration.", fg="green"))
  143. create_count = 0
  144. skipped_count = 0
  145. total_count = 0
  146. page = 1
  147. while True:
  148. try:
  149. # get apps info
  150. per_page = 50
  151. apps = (
  152. db.session.query(App)
  153. .where(App.status == "normal")
  154. .order_by(App.created_at.desc())
  155. .limit(per_page)
  156. .offset((page - 1) * per_page)
  157. .all()
  158. )
  159. if not apps:
  160. break
  161. except SQLAlchemyError:
  162. raise
  163. page += 1
  164. for app in apps:
  165. total_count = total_count + 1
  166. click.echo(
  167. f"Processing the {total_count} app {app.id}. " + f"{create_count} created, {skipped_count} skipped."
  168. )
  169. try:
  170. click.echo(f"Creating app annotation index: {app.id}")
  171. app_annotation_setting = (
  172. db.session.query(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app.id).first()
  173. )
  174. if not app_annotation_setting:
  175. skipped_count = skipped_count + 1
  176. click.echo(f"App annotation setting disabled: {app.id}")
  177. continue
  178. # get dataset_collection_binding info
  179. dataset_collection_binding = (
  180. db.session.query(DatasetCollectionBinding)
  181. .where(DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id)
  182. .first()
  183. )
  184. if not dataset_collection_binding:
  185. click.echo(f"App annotation collection binding not found: {app.id}")
  186. continue
  187. annotations = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app.id).all()
  188. dataset = Dataset(
  189. id=app.id,
  190. tenant_id=app.tenant_id,
  191. indexing_technique="high_quality",
  192. embedding_model_provider=dataset_collection_binding.provider_name,
  193. embedding_model=dataset_collection_binding.model_name,
  194. collection_binding_id=dataset_collection_binding.id,
  195. )
  196. documents = []
  197. if annotations:
  198. for annotation in annotations:
  199. document = Document(
  200. page_content=annotation.question,
  201. metadata={"annotation_id": annotation.id, "app_id": app.id, "doc_id": annotation.id},
  202. )
  203. documents.append(document)
  204. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  205. click.echo(f"Migrating annotations for app: {app.id}.")
  206. try:
  207. vector.delete()
  208. click.echo(click.style(f"Deleted vector index for app {app.id}.", fg="green"))
  209. except Exception as e:
  210. click.echo(click.style(f"Failed to delete vector index for app {app.id}.", fg="red"))
  211. raise e
  212. if documents:
  213. try:
  214. click.echo(
  215. click.style(
  216. f"Creating vector index with {len(documents)} annotations for app {app.id}.",
  217. fg="green",
  218. )
  219. )
  220. vector.create(documents)
  221. click.echo(click.style(f"Created vector index for app {app.id}.", fg="green"))
  222. except Exception as e:
  223. click.echo(click.style(f"Failed to created vector index for app {app.id}.", fg="red"))
  224. raise e
  225. click.echo(f"Successfully migrated app annotation {app.id}.")
  226. create_count += 1
  227. except Exception as e:
  228. click.echo(
  229. click.style(f"Error creating app annotation index: {e.__class__.__name__} {str(e)}", fg="red")
  230. )
  231. continue
  232. click.echo(
  233. click.style(
  234. f"Migration complete. Created {create_count} app annotation indexes. Skipped {skipped_count} apps.",
  235. fg="green",
  236. )
  237. )
  238. def migrate_knowledge_vector_database():
  239. """
  240. Migrate vector database datas to target vector database .
  241. """
  242. click.echo(click.style("Starting vector database migration.", fg="green"))
  243. create_count = 0
  244. skipped_count = 0
  245. total_count = 0
  246. vector_type = dify_config.VECTOR_STORE
  247. upper_collection_vector_types = {
  248. VectorType.MILVUS,
  249. VectorType.PGVECTOR,
  250. VectorType.VASTBASE,
  251. VectorType.RELYT,
  252. VectorType.WEAVIATE,
  253. VectorType.ORACLE,
  254. VectorType.ELASTICSEARCH,
  255. VectorType.OPENGAUSS,
  256. VectorType.TABLESTORE,
  257. VectorType.MATRIXONE,
  258. }
  259. lower_collection_vector_types = {
  260. VectorType.ANALYTICDB,
  261. VectorType.CHROMA,
  262. VectorType.MYSCALE,
  263. VectorType.PGVECTO_RS,
  264. VectorType.TIDB_VECTOR,
  265. VectorType.OPENSEARCH,
  266. VectorType.TENCENT,
  267. VectorType.BAIDU,
  268. VectorType.VIKINGDB,
  269. VectorType.UPSTASH,
  270. VectorType.COUCHBASE,
  271. VectorType.OCEANBASE,
  272. }
  273. page = 1
  274. while True:
  275. try:
  276. stmt = (
  277. select(Dataset).where(Dataset.indexing_technique == "high_quality").order_by(Dataset.created_at.desc())
  278. )
  279. datasets = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  280. except SQLAlchemyError:
  281. raise
  282. page += 1
  283. for dataset in datasets:
  284. total_count = total_count + 1
  285. click.echo(
  286. f"Processing the {total_count} dataset {dataset.id}. {create_count} created, {skipped_count} skipped."
  287. )
  288. try:
  289. click.echo(f"Creating dataset vector database index: {dataset.id}")
  290. if dataset.index_struct_dict:
  291. if dataset.index_struct_dict["type"] == vector_type:
  292. skipped_count = skipped_count + 1
  293. continue
  294. collection_name = ""
  295. dataset_id = dataset.id
  296. if vector_type in upper_collection_vector_types:
  297. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  298. elif vector_type == VectorType.QDRANT:
  299. if dataset.collection_binding_id:
  300. dataset_collection_binding = (
  301. db.session.query(DatasetCollectionBinding)
  302. .where(DatasetCollectionBinding.id == dataset.collection_binding_id)
  303. .one_or_none()
  304. )
  305. if dataset_collection_binding:
  306. collection_name = dataset_collection_binding.collection_name
  307. else:
  308. raise ValueError("Dataset Collection Binding not found")
  309. else:
  310. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  311. elif vector_type in lower_collection_vector_types:
  312. collection_name = Dataset.gen_collection_name_by_id(dataset_id).lower()
  313. else:
  314. raise ValueError(f"Vector store {vector_type} is not supported.")
  315. index_struct_dict = {"type": vector_type, "vector_store": {"class_prefix": collection_name}}
  316. dataset.index_struct = json.dumps(index_struct_dict)
  317. vector = Vector(dataset)
  318. click.echo(f"Migrating dataset {dataset.id}.")
  319. try:
  320. vector.delete()
  321. click.echo(
  322. click.style(f"Deleted vector index {collection_name} for dataset {dataset.id}.", fg="green")
  323. )
  324. except Exception as e:
  325. click.echo(
  326. click.style(
  327. f"Failed to delete vector index {collection_name} for dataset {dataset.id}.", fg="red"
  328. )
  329. )
  330. raise e
  331. dataset_documents = (
  332. db.session.query(DatasetDocument)
  333. .where(
  334. DatasetDocument.dataset_id == dataset.id,
  335. DatasetDocument.indexing_status == "completed",
  336. DatasetDocument.enabled == True,
  337. DatasetDocument.archived == False,
  338. )
  339. .all()
  340. )
  341. documents = []
  342. segments_count = 0
  343. for dataset_document in dataset_documents:
  344. segments = (
  345. db.session.query(DocumentSegment)
  346. .where(
  347. DocumentSegment.document_id == dataset_document.id,
  348. DocumentSegment.status == "completed",
  349. DocumentSegment.enabled == True,
  350. )
  351. .all()
  352. )
  353. for segment in segments:
  354. document = Document(
  355. page_content=segment.content,
  356. metadata={
  357. "doc_id": segment.index_node_id,
  358. "doc_hash": segment.index_node_hash,
  359. "document_id": segment.document_id,
  360. "dataset_id": segment.dataset_id,
  361. },
  362. )
  363. documents.append(document)
  364. segments_count = segments_count + 1
  365. if documents:
  366. try:
  367. click.echo(
  368. click.style(
  369. f"Creating vector index with {len(documents)} documents of {segments_count}"
  370. f" segments for dataset {dataset.id}.",
  371. fg="green",
  372. )
  373. )
  374. vector.create(documents)
  375. click.echo(click.style(f"Created vector index for dataset {dataset.id}.", fg="green"))
  376. except Exception as e:
  377. click.echo(click.style(f"Failed to created vector index for dataset {dataset.id}.", fg="red"))
  378. raise e
  379. db.session.add(dataset)
  380. db.session.commit()
  381. click.echo(f"Successfully migrated dataset {dataset.id}.")
  382. create_count += 1
  383. except Exception as e:
  384. db.session.rollback()
  385. click.echo(click.style(f"Error creating dataset index: {e.__class__.__name__} {str(e)}", fg="red"))
  386. continue
  387. click.echo(
  388. click.style(
  389. f"Migration complete. Created {create_count} dataset indexes. Skipped {skipped_count} datasets.", fg="green"
  390. )
  391. )
  392. @click.command("convert-to-agent-apps", help="Convert Agent Assistant to Agent App.")
  393. def convert_to_agent_apps():
  394. """
  395. Convert Agent Assistant to Agent App.
  396. """
  397. click.echo(click.style("Starting convert to agent apps.", fg="green"))
  398. proceeded_app_ids = []
  399. while True:
  400. # fetch first 1000 apps
  401. sql_query = """SELECT a.id AS id FROM apps a
  402. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  403. WHERE a.mode = 'chat'
  404. AND am.agent_mode is not null
  405. AND (
  406. am.agent_mode like '%"strategy": "function_call"%'
  407. OR am.agent_mode like '%"strategy": "react"%'
  408. )
  409. AND (
  410. am.agent_mode like '{"enabled": true%'
  411. OR am.agent_mode like '{"max_iteration": %'
  412. ) ORDER BY a.created_at DESC LIMIT 1000
  413. """
  414. with db.engine.begin() as conn:
  415. rs = conn.execute(sa.text(sql_query))
  416. apps = []
  417. for i in rs:
  418. app_id = str(i.id)
  419. if app_id not in proceeded_app_ids:
  420. proceeded_app_ids.append(app_id)
  421. app = db.session.query(App).where(App.id == app_id).first()
  422. if app is not None:
  423. apps.append(app)
  424. if len(apps) == 0:
  425. break
  426. for app in apps:
  427. click.echo(f"Converting app: {app.id}")
  428. try:
  429. app.mode = AppMode.AGENT_CHAT.value
  430. db.session.commit()
  431. # update conversation mode to agent
  432. db.session.query(Conversation).where(Conversation.app_id == app.id).update(
  433. {Conversation.mode: AppMode.AGENT_CHAT.value}
  434. )
  435. db.session.commit()
  436. click.echo(click.style(f"Converted app: {app.id}", fg="green"))
  437. except Exception as e:
  438. click.echo(click.style(f"Convert app error: {e.__class__.__name__} {str(e)}", fg="red"))
  439. click.echo(click.style(f"Conversion complete. Converted {len(proceeded_app_ids)} agent apps.", fg="green"))
  440. @click.command("add-qdrant-index", help="Add Qdrant index.")
  441. @click.option("--field", default="metadata.doc_id", prompt=False, help="Index field , default is metadata.doc_id.")
  442. def add_qdrant_index(field: str):
  443. click.echo(click.style("Starting Qdrant index creation.", fg="green"))
  444. create_count = 0
  445. try:
  446. bindings = db.session.query(DatasetCollectionBinding).all()
  447. if not bindings:
  448. click.echo(click.style("No dataset collection bindings found.", fg="red"))
  449. return
  450. import qdrant_client
  451. from qdrant_client.http.exceptions import UnexpectedResponse
  452. from qdrant_client.http.models import PayloadSchemaType
  453. from core.rag.datasource.vdb.qdrant.qdrant_vector import QdrantConfig
  454. for binding in bindings:
  455. if dify_config.QDRANT_URL is None:
  456. raise ValueError("Qdrant URL is required.")
  457. qdrant_config = QdrantConfig(
  458. endpoint=dify_config.QDRANT_URL,
  459. api_key=dify_config.QDRANT_API_KEY,
  460. root_path=current_app.root_path,
  461. timeout=dify_config.QDRANT_CLIENT_TIMEOUT,
  462. grpc_port=dify_config.QDRANT_GRPC_PORT,
  463. prefer_grpc=dify_config.QDRANT_GRPC_ENABLED,
  464. )
  465. try:
  466. client = qdrant_client.QdrantClient(**qdrant_config.to_qdrant_params())
  467. # create payload index
  468. client.create_payload_index(binding.collection_name, field, field_schema=PayloadSchemaType.KEYWORD)
  469. create_count += 1
  470. except UnexpectedResponse as e:
  471. # Collection does not exist, so return
  472. if e.status_code == 404:
  473. click.echo(click.style(f"Collection not found: {binding.collection_name}.", fg="red"))
  474. continue
  475. # Some other error occurred, so re-raise the exception
  476. else:
  477. click.echo(
  478. click.style(
  479. f"Failed to create Qdrant index for collection: {binding.collection_name}.", fg="red"
  480. )
  481. )
  482. except Exception:
  483. click.echo(click.style("Failed to create Qdrant client.", fg="red"))
  484. click.echo(click.style(f"Index creation complete. Created {create_count} collection indexes.", fg="green"))
  485. @click.command("old-metadata-migration", help="Old metadata migration.")
  486. def old_metadata_migration():
  487. """
  488. Old metadata migration.
  489. """
  490. click.echo(click.style("Starting old metadata migration.", fg="green"))
  491. page = 1
  492. while True:
  493. try:
  494. stmt = (
  495. select(DatasetDocument)
  496. .where(DatasetDocument.doc_metadata.is_not(None))
  497. .order_by(DatasetDocument.created_at.desc())
  498. )
  499. documents = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  500. except SQLAlchemyError:
  501. raise
  502. if not documents:
  503. break
  504. for document in documents:
  505. if document.doc_metadata:
  506. doc_metadata = document.doc_metadata
  507. for key, value in doc_metadata.items():
  508. for field in BuiltInField:
  509. if field.value == key:
  510. break
  511. else:
  512. dataset_metadata = (
  513. db.session.query(DatasetMetadata)
  514. .where(DatasetMetadata.dataset_id == document.dataset_id, DatasetMetadata.name == key)
  515. .first()
  516. )
  517. if not dataset_metadata:
  518. dataset_metadata = DatasetMetadata(
  519. tenant_id=document.tenant_id,
  520. dataset_id=document.dataset_id,
  521. name=key,
  522. type="string",
  523. created_by=document.created_by,
  524. )
  525. db.session.add(dataset_metadata)
  526. db.session.flush()
  527. dataset_metadata_binding = DatasetMetadataBinding(
  528. tenant_id=document.tenant_id,
  529. dataset_id=document.dataset_id,
  530. metadata_id=dataset_metadata.id,
  531. document_id=document.id,
  532. created_by=document.created_by,
  533. )
  534. db.session.add(dataset_metadata_binding)
  535. else:
  536. dataset_metadata_binding = (
  537. db.session.query(DatasetMetadataBinding) # type: ignore
  538. .where(
  539. DatasetMetadataBinding.dataset_id == document.dataset_id,
  540. DatasetMetadataBinding.document_id == document.id,
  541. DatasetMetadataBinding.metadata_id == dataset_metadata.id,
  542. )
  543. .first()
  544. )
  545. if not dataset_metadata_binding:
  546. dataset_metadata_binding = DatasetMetadataBinding(
  547. tenant_id=document.tenant_id,
  548. dataset_id=document.dataset_id,
  549. metadata_id=dataset_metadata.id,
  550. document_id=document.id,
  551. created_by=document.created_by,
  552. )
  553. db.session.add(dataset_metadata_binding)
  554. db.session.commit()
  555. page += 1
  556. click.echo(click.style("Old metadata migration completed.", fg="green"))
  557. @click.command("create-tenant", help="Create account and tenant.")
  558. @click.option("--email", prompt=True, help="Tenant account email.")
  559. @click.option("--name", prompt=True, help="Workspace name.")
  560. @click.option("--language", prompt=True, help="Account language, default: en-US.")
  561. def create_tenant(email: str, language: Optional[str] = None, name: Optional[str] = None):
  562. """
  563. Create tenant account
  564. """
  565. if not email:
  566. click.echo(click.style("Email is required.", fg="red"))
  567. return
  568. # Create account
  569. email = email.strip()
  570. if "@" not in email:
  571. click.echo(click.style("Invalid email address.", fg="red"))
  572. return
  573. account_name = email.split("@")[0]
  574. if language not in languages:
  575. language = "en-US"
  576. # Validates name encoding for non-Latin characters.
  577. name = name.strip().encode("utf-8").decode("utf-8") if name else None
  578. # generate random password
  579. new_password = secrets.token_urlsafe(16)
  580. # register account
  581. account = RegisterService.register(
  582. email=email,
  583. name=account_name,
  584. password=new_password,
  585. language=language,
  586. create_workspace_required=False,
  587. )
  588. TenantService.create_owner_tenant_if_not_exist(account, name)
  589. click.echo(
  590. click.style(
  591. f"Account and tenant created.\nAccount: {email}\nPassword: {new_password}",
  592. fg="green",
  593. )
  594. )
  595. @click.command("upgrade-db", help="Upgrade the database")
  596. def upgrade_db():
  597. click.echo("Preparing database migration...")
  598. lock = redis_client.lock(name="db_upgrade_lock", timeout=60)
  599. if lock.acquire(blocking=False):
  600. try:
  601. click.echo(click.style("Starting database migration.", fg="green"))
  602. # run db migration
  603. import flask_migrate
  604. flask_migrate.upgrade()
  605. click.echo(click.style("Database migration successful!", fg="green"))
  606. except Exception:
  607. logger.exception("Failed to execute database migration")
  608. finally:
  609. lock.release()
  610. else:
  611. click.echo("Database migration skipped")
  612. @click.command("fix-app-site-missing", help="Fix app related site missing issue.")
  613. def fix_app_site_missing():
  614. """
  615. Fix app related site missing issue.
  616. """
  617. click.echo(click.style("Starting fix for missing app-related sites.", fg="green"))
  618. failed_app_ids = []
  619. while True:
  620. sql = """select apps.id as id from apps left join sites on sites.app_id=apps.id
  621. where sites.id is null limit 1000"""
  622. with db.engine.begin() as conn:
  623. rs = conn.execute(sa.text(sql))
  624. processed_count = 0
  625. for i in rs:
  626. processed_count += 1
  627. app_id = str(i.id)
  628. if app_id in failed_app_ids:
  629. continue
  630. try:
  631. app = db.session.query(App).where(App.id == app_id).first()
  632. if not app:
  633. print(f"App {app_id} not found")
  634. continue
  635. tenant = app.tenant
  636. if tenant:
  637. accounts = tenant.get_accounts()
  638. if not accounts:
  639. print(f"Fix failed for app {app.id}")
  640. continue
  641. account = accounts[0]
  642. print(f"Fixing missing site for app {app.id}")
  643. app_was_created.send(app, account=account)
  644. except Exception:
  645. failed_app_ids.append(app_id)
  646. click.echo(click.style(f"Failed to fix missing site for app {app_id}", fg="red"))
  647. logger.exception("Failed to fix app related site missing issue, app_id: %s", app_id)
  648. continue
  649. if not processed_count:
  650. break
  651. click.echo(click.style("Fix for missing app-related sites completed successfully!", fg="green"))
  652. @click.command("migrate-data-for-plugin", help="Migrate data for plugin.")
  653. def migrate_data_for_plugin():
  654. """
  655. Migrate data for plugin.
  656. """
  657. click.echo(click.style("Starting migrate data for plugin.", fg="white"))
  658. PluginDataMigration.migrate()
  659. click.echo(click.style("Migrate data for plugin completed.", fg="green"))
  660. @click.command("extract-plugins", help="Extract plugins.")
  661. @click.option("--output_file", prompt=True, help="The file to store the extracted plugins.", default="plugins.jsonl")
  662. @click.option("--workers", prompt=True, help="The number of workers to extract plugins.", default=10)
  663. def extract_plugins(output_file: str, workers: int):
  664. """
  665. Extract plugins.
  666. """
  667. click.echo(click.style("Starting extract plugins.", fg="white"))
  668. PluginMigration.extract_plugins(output_file, workers)
  669. click.echo(click.style("Extract plugins completed.", fg="green"))
  670. @click.command("extract-unique-identifiers", help="Extract unique identifiers.")
  671. @click.option(
  672. "--output_file",
  673. prompt=True,
  674. help="The file to store the extracted unique identifiers.",
  675. default="unique_identifiers.json",
  676. )
  677. @click.option(
  678. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  679. )
  680. def extract_unique_plugins(output_file: str, input_file: str):
  681. """
  682. Extract unique plugins.
  683. """
  684. click.echo(click.style("Starting extract unique plugins.", fg="white"))
  685. PluginMigration.extract_unique_plugins_to_file(input_file, output_file)
  686. click.echo(click.style("Extract unique plugins completed.", fg="green"))
  687. @click.command("install-plugins", help="Install plugins.")
  688. @click.option(
  689. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  690. )
  691. @click.option(
  692. "--output_file", prompt=True, help="The file to store the installed plugins.", default="installed_plugins.jsonl"
  693. )
  694. @click.option("--workers", prompt=True, help="The number of workers to install plugins.", default=100)
  695. def install_plugins(input_file: str, output_file: str, workers: int):
  696. """
  697. Install plugins.
  698. """
  699. click.echo(click.style("Starting install plugins.", fg="white"))
  700. PluginMigration.install_plugins(input_file, output_file, workers)
  701. click.echo(click.style("Install plugins completed.", fg="green"))
  702. @click.command("clear-free-plan-tenant-expired-logs", help="Clear free plan tenant expired logs.")
  703. @click.option("--days", prompt=True, help="The days to clear free plan tenant expired logs.", default=30)
  704. @click.option("--batch", prompt=True, help="The batch size to clear free plan tenant expired logs.", default=100)
  705. @click.option(
  706. "--tenant_ids",
  707. prompt=True,
  708. multiple=True,
  709. help="The tenant ids to clear free plan tenant expired logs.",
  710. )
  711. def clear_free_plan_tenant_expired_logs(days: int, batch: int, tenant_ids: list[str]):
  712. """
  713. Clear free plan tenant expired logs.
  714. """
  715. click.echo(click.style("Starting clear free plan tenant expired logs.", fg="white"))
  716. ClearFreePlanTenantExpiredLogs.process(days, batch, tenant_ids)
  717. click.echo(click.style("Clear free plan tenant expired logs completed.", fg="green"))
  718. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  719. @click.command("clear-orphaned-file-records", help="Clear orphaned file records.")
  720. def clear_orphaned_file_records(force: bool):
  721. """
  722. Clear orphaned file records in the database.
  723. """
  724. # define tables and columns to process
  725. files_tables = [
  726. {"table": "upload_files", "id_column": "id", "key_column": "key"},
  727. {"table": "tool_files", "id_column": "id", "key_column": "file_key"},
  728. ]
  729. ids_tables = [
  730. {"type": "uuid", "table": "message_files", "column": "upload_file_id"},
  731. {"type": "text", "table": "documents", "column": "data_source_info"},
  732. {"type": "text", "table": "document_segments", "column": "content"},
  733. {"type": "text", "table": "messages", "column": "answer"},
  734. {"type": "text", "table": "workflow_node_executions", "column": "inputs"},
  735. {"type": "text", "table": "workflow_node_executions", "column": "process_data"},
  736. {"type": "text", "table": "workflow_node_executions", "column": "outputs"},
  737. {"type": "text", "table": "conversations", "column": "introduction"},
  738. {"type": "text", "table": "conversations", "column": "system_instruction"},
  739. {"type": "text", "table": "accounts", "column": "avatar"},
  740. {"type": "text", "table": "apps", "column": "icon"},
  741. {"type": "text", "table": "sites", "column": "icon"},
  742. {"type": "json", "table": "messages", "column": "inputs"},
  743. {"type": "json", "table": "messages", "column": "message"},
  744. ]
  745. # notify user and ask for confirmation
  746. click.echo(
  747. click.style(
  748. "This command will first find and delete orphaned file records from the message_files table,", fg="yellow"
  749. )
  750. )
  751. click.echo(
  752. click.style(
  753. "and then it will find and delete orphaned file records in the following tables:",
  754. fg="yellow",
  755. )
  756. )
  757. for files_table in files_tables:
  758. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  759. click.echo(
  760. click.style("The following tables and columns will be scanned to find orphaned file records:", fg="yellow")
  761. )
  762. for ids_table in ids_tables:
  763. click.echo(click.style(f"- {ids_table['table']} ({ids_table['column']})", fg="yellow"))
  764. click.echo("")
  765. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  766. click.echo(
  767. click.style(
  768. (
  769. "Since not all patterns have been fully tested, "
  770. "please note that this command may delete unintended file records."
  771. ),
  772. fg="yellow",
  773. )
  774. )
  775. click.echo(
  776. click.style("This cannot be undone. Please make sure to back up your database before proceeding.", fg="yellow")
  777. )
  778. click.echo(
  779. click.style(
  780. (
  781. "It is also recommended to run this during the maintenance window, "
  782. "as this may cause high load on your instance."
  783. ),
  784. fg="yellow",
  785. )
  786. )
  787. if not force:
  788. click.confirm("Do you want to proceed?", abort=True)
  789. # start the cleanup process
  790. click.echo(click.style("Starting orphaned file records cleanup.", fg="white"))
  791. # clean up the orphaned records in the message_files table where message_id doesn't exist in messages table
  792. try:
  793. click.echo(
  794. click.style("- Listing message_files records where message_id doesn't exist in messages table", fg="white")
  795. )
  796. query = (
  797. "SELECT mf.id, mf.message_id "
  798. "FROM message_files mf LEFT JOIN messages m ON mf.message_id = m.id "
  799. "WHERE m.id IS NULL"
  800. )
  801. orphaned_message_files = []
  802. with db.engine.begin() as conn:
  803. rs = conn.execute(sa.text(query))
  804. for i in rs:
  805. orphaned_message_files.append({"id": str(i[0]), "message_id": str(i[1])})
  806. if orphaned_message_files:
  807. click.echo(click.style(f"Found {len(orphaned_message_files)} orphaned message_files records:", fg="white"))
  808. for record in orphaned_message_files:
  809. click.echo(click.style(f" - id: {record['id']}, message_id: {record['message_id']}", fg="black"))
  810. if not force:
  811. click.confirm(
  812. (
  813. f"Do you want to proceed "
  814. f"to delete all {len(orphaned_message_files)} orphaned message_files records?"
  815. ),
  816. abort=True,
  817. )
  818. click.echo(click.style("- Deleting orphaned message_files records", fg="white"))
  819. query = "DELETE FROM message_files WHERE id IN :ids"
  820. with db.engine.begin() as conn:
  821. conn.execute(sa.text(query), {"ids": tuple([record["id"] for record in orphaned_message_files])})
  822. click.echo(
  823. click.style(f"Removed {len(orphaned_message_files)} orphaned message_files records.", fg="green")
  824. )
  825. else:
  826. click.echo(click.style("No orphaned message_files records found. There is nothing to delete.", fg="green"))
  827. except Exception as e:
  828. click.echo(click.style(f"Error deleting orphaned message_files records: {str(e)}", fg="red"))
  829. # clean up the orphaned records in the rest of the *_files tables
  830. try:
  831. # fetch file id and keys from each table
  832. all_files_in_tables = []
  833. for files_table in files_tables:
  834. click.echo(click.style(f"- Listing file records in table {files_table['table']}", fg="white"))
  835. query = f"SELECT {files_table['id_column']}, {files_table['key_column']} FROM {files_table['table']}"
  836. with db.engine.begin() as conn:
  837. rs = conn.execute(sa.text(query))
  838. for i in rs:
  839. all_files_in_tables.append({"table": files_table["table"], "id": str(i[0]), "key": i[1]})
  840. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  841. # fetch referred table and columns
  842. guid_regexp = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
  843. all_ids_in_tables = []
  844. for ids_table in ids_tables:
  845. query = ""
  846. if ids_table["type"] == "uuid":
  847. click.echo(
  848. click.style(
  849. f"- Listing file ids in column {ids_table['column']} in table {ids_table['table']}", fg="white"
  850. )
  851. )
  852. query = (
  853. f"SELECT {ids_table['column']} FROM {ids_table['table']} WHERE {ids_table['column']} IS NOT NULL"
  854. )
  855. with db.engine.begin() as conn:
  856. rs = conn.execute(sa.text(query))
  857. for i in rs:
  858. all_ids_in_tables.append({"table": ids_table["table"], "id": str(i[0])})
  859. elif ids_table["type"] == "text":
  860. click.echo(
  861. click.style(
  862. f"- Listing file-id-like strings in column {ids_table['column']} in table {ids_table['table']}",
  863. fg="white",
  864. )
  865. )
  866. query = (
  867. f"SELECT regexp_matches({ids_table['column']}, '{guid_regexp}', 'g') AS extracted_id "
  868. f"FROM {ids_table['table']}"
  869. )
  870. with db.engine.begin() as conn:
  871. rs = conn.execute(sa.text(query))
  872. for i in rs:
  873. for j in i[0]:
  874. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  875. elif ids_table["type"] == "json":
  876. click.echo(
  877. click.style(
  878. (
  879. f"- Listing file-id-like JSON string in column {ids_table['column']} "
  880. f"in table {ids_table['table']}"
  881. ),
  882. fg="white",
  883. )
  884. )
  885. query = (
  886. f"SELECT regexp_matches({ids_table['column']}::text, '{guid_regexp}', 'g') AS extracted_id "
  887. f"FROM {ids_table['table']}"
  888. )
  889. with db.engine.begin() as conn:
  890. rs = conn.execute(sa.text(query))
  891. for i in rs:
  892. for j in i[0]:
  893. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  894. click.echo(click.style(f"Found {len(all_ids_in_tables)} file ids in tables.", fg="white"))
  895. except Exception as e:
  896. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  897. return
  898. # find orphaned files
  899. all_files = [file["id"] for file in all_files_in_tables]
  900. all_ids = [file["id"] for file in all_ids_in_tables]
  901. orphaned_files = list(set(all_files) - set(all_ids))
  902. if not orphaned_files:
  903. click.echo(click.style("No orphaned file records found. There is nothing to delete.", fg="green"))
  904. return
  905. click.echo(click.style(f"Found {len(orphaned_files)} orphaned file records.", fg="white"))
  906. for file in orphaned_files:
  907. click.echo(click.style(f"- orphaned file id: {file}", fg="black"))
  908. if not force:
  909. click.confirm(f"Do you want to proceed to delete all {len(orphaned_files)} orphaned file records?", abort=True)
  910. # delete orphaned records for each file
  911. try:
  912. for files_table in files_tables:
  913. click.echo(click.style(f"- Deleting orphaned file records in table {files_table['table']}", fg="white"))
  914. query = f"DELETE FROM {files_table['table']} WHERE {files_table['id_column']} IN :ids"
  915. with db.engine.begin() as conn:
  916. conn.execute(sa.text(query), {"ids": tuple(orphaned_files)})
  917. except Exception as e:
  918. click.echo(click.style(f"Error deleting orphaned file records: {str(e)}", fg="red"))
  919. return
  920. click.echo(click.style(f"Removed {len(orphaned_files)} orphaned file records.", fg="green"))
  921. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  922. @click.command("remove-orphaned-files-on-storage", help="Remove orphaned files on the storage.")
  923. def remove_orphaned_files_on_storage(force: bool):
  924. """
  925. Remove orphaned files on the storage.
  926. """
  927. # define tables and columns to process
  928. files_tables = [
  929. {"table": "upload_files", "key_column": "key"},
  930. {"table": "tool_files", "key_column": "file_key"},
  931. ]
  932. storage_paths = ["image_files", "tools", "upload_files"]
  933. # notify user and ask for confirmation
  934. click.echo(click.style("This command will find and remove orphaned files on the storage,", fg="yellow"))
  935. click.echo(
  936. click.style("by comparing the files on the storage with the records in the following tables:", fg="yellow")
  937. )
  938. for files_table in files_tables:
  939. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  940. click.echo(click.style("The following paths on the storage will be scanned to find orphaned files:", fg="yellow"))
  941. for storage_path in storage_paths:
  942. click.echo(click.style(f"- {storage_path}", fg="yellow"))
  943. click.echo("")
  944. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  945. click.echo(
  946. click.style(
  947. "Currently, this command will work only for opendal based storage (STORAGE_TYPE=opendal).", fg="yellow"
  948. )
  949. )
  950. click.echo(
  951. click.style(
  952. "Since not all patterns have been fully tested, please note that this command may delete unintended files.",
  953. fg="yellow",
  954. )
  955. )
  956. click.echo(
  957. click.style("This cannot be undone. Please make sure to back up your storage before proceeding.", fg="yellow")
  958. )
  959. click.echo(
  960. click.style(
  961. (
  962. "It is also recommended to run this during the maintenance window, "
  963. "as this may cause high load on your instance."
  964. ),
  965. fg="yellow",
  966. )
  967. )
  968. if not force:
  969. click.confirm("Do you want to proceed?", abort=True)
  970. # start the cleanup process
  971. click.echo(click.style("Starting orphaned files cleanup.", fg="white"))
  972. # fetch file id and keys from each table
  973. all_files_in_tables = []
  974. try:
  975. for files_table in files_tables:
  976. click.echo(click.style(f"- Listing files from table {files_table['table']}", fg="white"))
  977. query = f"SELECT {files_table['key_column']} FROM {files_table['table']}"
  978. with db.engine.begin() as conn:
  979. rs = conn.execute(sa.text(query))
  980. for i in rs:
  981. all_files_in_tables.append(str(i[0]))
  982. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  983. except Exception as e:
  984. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  985. all_files_on_storage = []
  986. for storage_path in storage_paths:
  987. try:
  988. click.echo(click.style(f"- Scanning files on storage path {storage_path}", fg="white"))
  989. files = storage.scan(path=storage_path, files=True, directories=False)
  990. all_files_on_storage.extend(files)
  991. except FileNotFoundError as e:
  992. click.echo(click.style(f" -> Skipping path {storage_path} as it does not exist.", fg="yellow"))
  993. continue
  994. except Exception as e:
  995. click.echo(click.style(f" -> Error scanning files on storage path {storage_path}: {str(e)}", fg="red"))
  996. continue
  997. click.echo(click.style(f"Found {len(all_files_on_storage)} files on storage.", fg="white"))
  998. # find orphaned files
  999. orphaned_files = list(set(all_files_on_storage) - set(all_files_in_tables))
  1000. if not orphaned_files:
  1001. click.echo(click.style("No orphaned files found. There is nothing to remove.", fg="green"))
  1002. return
  1003. click.echo(click.style(f"Found {len(orphaned_files)} orphaned files.", fg="white"))
  1004. for file in orphaned_files:
  1005. click.echo(click.style(f"- orphaned file: {file}", fg="black"))
  1006. if not force:
  1007. click.confirm(f"Do you want to proceed to remove all {len(orphaned_files)} orphaned files?", abort=True)
  1008. # delete orphaned files
  1009. removed_files = 0
  1010. error_files = 0
  1011. for file in orphaned_files:
  1012. try:
  1013. storage.delete(file)
  1014. removed_files += 1
  1015. click.echo(click.style(f"- Removing orphaned file: {file}", fg="white"))
  1016. except Exception as e:
  1017. error_files += 1
  1018. click.echo(click.style(f"- Error deleting orphaned file {file}: {str(e)}", fg="red"))
  1019. continue
  1020. if error_files == 0:
  1021. click.echo(click.style(f"Removed {removed_files} orphaned files without errors.", fg="green"))
  1022. else:
  1023. click.echo(click.style(f"Removed {removed_files} orphaned files, with {error_files} errors.", fg="yellow"))
  1024. @click.command("setup-system-tool-oauth-client", help="Setup system tool oauth client.")
  1025. @click.option("--provider", prompt=True, help="Provider name")
  1026. @click.option("--client-params", prompt=True, help="Client Params")
  1027. def setup_system_tool_oauth_client(provider, client_params):
  1028. """
  1029. Setup system tool oauth client
  1030. """
  1031. provider_id = ToolProviderID(provider)
  1032. provider_name = provider_id.provider_name
  1033. plugin_id = provider_id.plugin_id
  1034. try:
  1035. # json validate
  1036. click.echo(click.style(f"Validating client params: {client_params}", fg="yellow"))
  1037. client_params_dict = TypeAdapter(dict[str, Any]).validate_json(client_params)
  1038. click.echo(click.style("Client params validated successfully.", fg="green"))
  1039. click.echo(click.style(f"Encrypting client params: {client_params}", fg="yellow"))
  1040. click.echo(click.style(f"Using SECRET_KEY: `{dify_config.SECRET_KEY}`", fg="yellow"))
  1041. oauth_client_params = encrypt_system_oauth_params(client_params_dict)
  1042. click.echo(click.style("Client params encrypted successfully.", fg="green"))
  1043. except Exception as e:
  1044. click.echo(click.style(f"Error parsing client params: {str(e)}", fg="red"))
  1045. return
  1046. deleted_count = (
  1047. db.session.query(ToolOAuthSystemClient)
  1048. .filter_by(
  1049. provider=provider_name,
  1050. plugin_id=plugin_id,
  1051. )
  1052. .delete()
  1053. )
  1054. if deleted_count > 0:
  1055. click.echo(click.style(f"Deleted {deleted_count} existing oauth client params.", fg="yellow"))
  1056. oauth_client = ToolOAuthSystemClient(
  1057. provider=provider_name,
  1058. plugin_id=plugin_id,
  1059. encrypted_oauth_params=oauth_client_params,
  1060. )
  1061. db.session.add(oauth_client)
  1062. db.session.commit()
  1063. click.echo(click.style(f"OAuth client params setup successfully. id: {oauth_client.id}", fg="green"))
  1064. def _find_orphaned_draft_variables(batch_size: int = 1000) -> list[str]:
  1065. """
  1066. Find draft variables that reference non-existent apps.
  1067. Args:
  1068. batch_size: Maximum number of orphaned app IDs to return
  1069. Returns:
  1070. List of app IDs that have draft variables but don't exist in the apps table
  1071. """
  1072. query = """
  1073. SELECT DISTINCT wdv.app_id
  1074. FROM workflow_draft_variables AS wdv
  1075. WHERE NOT EXISTS(
  1076. SELECT 1 FROM apps WHERE apps.id = wdv.app_id
  1077. )
  1078. LIMIT :batch_size
  1079. """
  1080. with db.engine.connect() as conn:
  1081. result = conn.execute(sa.text(query), {"batch_size": batch_size})
  1082. return [row[0] for row in result]
  1083. def _count_orphaned_draft_variables() -> dict[str, Any]:
  1084. """
  1085. Count orphaned draft variables by app.
  1086. Returns:
  1087. Dictionary with statistics about orphaned variables
  1088. """
  1089. query = """
  1090. SELECT
  1091. wdv.app_id,
  1092. COUNT(*) as variable_count
  1093. FROM workflow_draft_variables AS wdv
  1094. WHERE NOT EXISTS(
  1095. SELECT 1 FROM apps WHERE apps.id = wdv.app_id
  1096. )
  1097. GROUP BY wdv.app_id
  1098. ORDER BY variable_count DESC
  1099. """
  1100. with db.engine.connect() as conn:
  1101. result = conn.execute(sa.text(query))
  1102. orphaned_by_app = {row[0]: row[1] for row in result}
  1103. total_orphaned = sum(orphaned_by_app.values())
  1104. app_count = len(orphaned_by_app)
  1105. return {
  1106. "total_orphaned_variables": total_orphaned,
  1107. "orphaned_app_count": app_count,
  1108. "orphaned_by_app": orphaned_by_app,
  1109. }
  1110. @click.command()
  1111. @click.option("--dry-run", is_flag=True, help="Show what would be deleted without actually deleting")
  1112. @click.option("--batch-size", default=1000, help="Number of records to process per batch (default 1000)")
  1113. @click.option("--max-apps", default=None, type=int, help="Maximum number of apps to process (default: no limit)")
  1114. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  1115. def cleanup_orphaned_draft_variables(
  1116. dry_run: bool,
  1117. batch_size: int,
  1118. max_apps: int | None,
  1119. force: bool = False,
  1120. ):
  1121. """
  1122. Clean up orphaned draft variables from the database.
  1123. This script finds and removes draft variables that belong to apps
  1124. that no longer exist in the database.
  1125. """
  1126. logger = logging.getLogger(__name__)
  1127. # Get statistics
  1128. stats = _count_orphaned_draft_variables()
  1129. logger.info("Found %s orphaned draft variables", stats["total_orphaned_variables"])
  1130. logger.info("Across %s non-existent apps", stats["orphaned_app_count"])
  1131. if stats["total_orphaned_variables"] == 0:
  1132. logger.info("No orphaned draft variables found. Exiting.")
  1133. return
  1134. if dry_run:
  1135. logger.info("DRY RUN: Would delete the following:")
  1136. for app_id, count in sorted(stats["orphaned_by_app"].items(), key=lambda x: x[1], reverse=True)[
  1137. :10
  1138. ]: # Show top 10
  1139. logger.info(" App %s: %s variables", app_id, count)
  1140. if len(stats["orphaned_by_app"]) > 10:
  1141. logger.info(" ... and %s more apps", len(stats["orphaned_by_app"]) - 10)
  1142. return
  1143. # Confirm deletion
  1144. if not force:
  1145. click.confirm(
  1146. f"Are you sure you want to delete {stats['total_orphaned_variables']} "
  1147. f"orphaned draft variables from {stats['orphaned_app_count']} apps?",
  1148. abort=True,
  1149. )
  1150. total_deleted = 0
  1151. processed_apps = 0
  1152. while True:
  1153. if max_apps and processed_apps >= max_apps:
  1154. logger.info("Reached maximum app limit (%s). Stopping.", max_apps)
  1155. break
  1156. orphaned_app_ids = _find_orphaned_draft_variables(batch_size=10)
  1157. if not orphaned_app_ids:
  1158. logger.info("No more orphaned draft variables found.")
  1159. break
  1160. for app_id in orphaned_app_ids:
  1161. if max_apps and processed_apps >= max_apps:
  1162. break
  1163. try:
  1164. deleted_count = delete_draft_variables_batch(app_id, batch_size)
  1165. total_deleted += deleted_count
  1166. processed_apps += 1
  1167. logger.info("Deleted %s variables for app %s", deleted_count, app_id)
  1168. except Exception:
  1169. logger.exception("Error processing app %s", app_id)
  1170. continue
  1171. logger.info("Cleanup completed. Total deleted: %s variables across %s apps", total_deleted, processed_apps)