|
| 1 | +import os |
| 2 | +from pathlib import Path |
| 3 | +from shutil import copy2 |
| 4 | + |
| 5 | +from pydantic import BaseModel, field_validator |
| 6 | + |
| 7 | +from lfx.log.logger import logger |
| 8 | +from lfx.utils.util_strings import is_valid_database_url, sanitize_database_url |
| 9 | + |
| 10 | + |
| 11 | +class DatabaseSettings(BaseModel): |
| 12 | + """Database connection, pooling, and migration settings. |
| 13 | +
|
| 14 | + Note: ``database_url`` is validated at the :class:`Settings` level because |
| 15 | + it reads ``config_dir`` from :class:`PathSettings`. |
| 16 | + """ |
| 17 | + |
| 18 | + save_db_in_config_dir: bool = False |
| 19 | + """Define if langflow database should be saved in LANGFLOW_CONFIG_DIR or in the langflow directory |
| 20 | + (i.e. in the package directory).""" |
| 21 | + |
| 22 | + database_url: str | None = None |
| 23 | + """Database URL for Langflow. If not provided, Langflow will use a SQLite database. |
| 24 | + The driver shall be an async one like `sqlite+aiosqlite` (`sqlite` and `postgresql` |
| 25 | + will be automatically converted to the async drivers `sqlite+aiosqlite` and |
| 26 | + `postgresql+psycopg` respectively).""" |
| 27 | + |
| 28 | + database_connection_retry: bool = False |
| 29 | + """If True, Langflow will retry to connect to the database if it fails.""" |
| 30 | + |
| 31 | + pool_size: int = 20 |
| 32 | + """The number of connections to keep open in the connection pool. |
| 33 | + For high load scenarios, this should be increased based on expected concurrent users.""" |
| 34 | + |
| 35 | + max_overflow: int = 30 |
| 36 | + """The number of connections to allow that can be opened beyond the pool size. |
| 37 | + Should be 2x the pool_size for optimal performance under load.""" |
| 38 | + |
| 39 | + db_connect_timeout: int = 30 |
| 40 | + """The number of seconds to wait before giving up on a lock to released or establishing a connection to the |
| 41 | + database.""" |
| 42 | + |
| 43 | + migration_lock_namespace: str | None = None |
| 44 | + """Optional namespace identifier for PostgreSQL advisory lock during migrations. |
| 45 | + If not provided, a hash of the database URL will be used. Useful when multiple Langflow |
| 46 | + instances share the same database and need coordinated migration locking.""" |
| 47 | + |
| 48 | + sqlite_pragmas: dict | None = {"synchronous": "NORMAL", "journal_mode": "WAL", "busy_timeout": 30000} |
| 49 | + """SQLite pragmas to use when connecting to the database.""" |
| 50 | + |
| 51 | + db_driver_connection_settings: dict | None = None |
| 52 | + """Database driver connection settings.""" |
| 53 | + |
| 54 | + db_connection_settings: dict | None = { |
| 55 | + "pool_size": 20, |
| 56 | + "max_overflow": 30, |
| 57 | + "pool_timeout": 30, |
| 58 | + "pool_pre_ping": True, |
| 59 | + "pool_recycle": 1800, |
| 60 | + "echo": False, |
| 61 | + } |
| 62 | + """Database connection settings optimized for high load scenarios. |
| 63 | + Note: These settings are most effective with PostgreSQL. For SQLite: |
| 64 | + - Reduce pool_size and max_overflow if experiencing lock contention |
| 65 | + - SQLite has limited concurrent write capability even with WAL mode |
| 66 | + - Best for read-heavy or moderate write workloads |
| 67 | +
|
| 68 | + Settings: |
| 69 | + - pool_size: Number of connections to maintain (increase for higher concurrency) |
| 70 | + - max_overflow: Additional connections allowed beyond pool_size |
| 71 | + - pool_timeout: Seconds to wait for an available connection |
| 72 | + - pool_pre_ping: Validates connections before use to prevent stale connections |
| 73 | + - pool_recycle: Seconds before connections are recycled (prevents timeouts) |
| 74 | + - echo: Enable SQL query logging (development only) |
| 75 | + """ |
| 76 | + |
| 77 | + use_noop_database: bool = False |
| 78 | + """If True, disables all database operations and uses a no-op session. |
| 79 | + Controlled by LANGFLOW_USE_NOOP_DATABASE env variable.""" |
| 80 | + |
| 81 | + @field_validator("use_noop_database", mode="before") |
| 82 | + @classmethod |
| 83 | + def set_use_noop_database(cls, value): |
| 84 | + if value: |
| 85 | + logger.info("Running with NOOP database session. All DB operations are disabled.") |
| 86 | + return value |
| 87 | + |
| 88 | + @field_validator("database_url", mode="before") |
| 89 | + @classmethod |
| 90 | + def set_database_url(cls, value, info): |
| 91 | + if value and not is_valid_database_url(value): |
| 92 | + sanitized = sanitize_database_url(value) |
| 93 | + msg = f"Invalid database_url provided: '{sanitized}'" |
| 94 | + raise ValueError(msg) |
| 95 | + |
| 96 | + if langflow_database_url := os.getenv("LANGFLOW_DATABASE_URL"): |
| 97 | + value = langflow_database_url |
| 98 | + logger.debug("Using LANGFLOW_DATABASE_URL env variable") |
| 99 | + else: |
| 100 | + if not info.data.get("config_dir"): |
| 101 | + msg = "config_dir not set, please set it or provide a database_url" |
| 102 | + raise ValueError(msg) |
| 103 | + |
| 104 | + from lfx.utils.version import get_version_info |
| 105 | + from lfx.utils.version import is_pre_release as langflow_is_pre_release |
| 106 | + |
| 107 | + version = get_version_info()["version"] |
| 108 | + is_pre_release = langflow_is_pre_release(version) |
| 109 | + |
| 110 | + if info.data["save_db_in_config_dir"]: |
| 111 | + database_dir = info.data["config_dir"] |
| 112 | + else: |
| 113 | + try: |
| 114 | + import langflow |
| 115 | + |
| 116 | + database_dir = Path(langflow.__file__).parent.resolve() |
| 117 | + except ImportError: |
| 118 | + database_dir = Path(__file__).parent.parent.parent.parent.resolve() |
| 119 | + |
| 120 | + pre_db_file_name = "langflow-pre.db" |
| 121 | + db_file_name = "langflow.db" |
| 122 | + new_pre_path = f"{database_dir}/{pre_db_file_name}" |
| 123 | + new_path = f"{database_dir}/{db_file_name}" |
| 124 | + final_path = None |
| 125 | + if is_pre_release: |
| 126 | + if Path(new_pre_path).exists(): |
| 127 | + final_path = new_pre_path |
| 128 | + elif Path(new_path).exists() and info.data["save_db_in_config_dir"]: |
| 129 | + logger.debug("Copying existing database to new location") |
| 130 | + copy2(new_path, new_pre_path) |
| 131 | + logger.debug(f"Copied existing database to {new_pre_path}") |
| 132 | + elif Path(f"./{db_file_name}").exists() and info.data["save_db_in_config_dir"]: |
| 133 | + logger.debug("Copying existing database to new location") |
| 134 | + copy2(f"./{db_file_name}", new_pre_path) |
| 135 | + logger.debug(f"Copied existing database to {new_pre_path}") |
| 136 | + else: |
| 137 | + logger.debug(f"Creating new database at {new_pre_path}") |
| 138 | + final_path = new_pre_path |
| 139 | + elif Path(new_path).exists(): |
| 140 | + final_path = new_path |
| 141 | + elif Path(f"./{db_file_name}").exists(): |
| 142 | + try: |
| 143 | + logger.debug("Copying existing database to new location") |
| 144 | + copy2(f"./{db_file_name}", new_path) |
| 145 | + logger.debug(f"Copied existing database to {new_path}") |
| 146 | + except OSError: |
| 147 | + logger.exception("Failed to copy database, using default path") |
| 148 | + new_path = f"./{db_file_name}" |
| 149 | + else: |
| 150 | + final_path = new_path |
| 151 | + |
| 152 | + if final_path is None: |
| 153 | + final_path = new_pre_path if is_pre_release else new_path |
| 154 | + |
| 155 | + value = f"sqlite:///{final_path}" |
| 156 | + |
| 157 | + return value |
0 commit comments