mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* perf(backend): read the nullable gallery sorts out of an index Sorting the gallery by release date, rating or HowLongToBeat time placed unset roms last with `ORDER BY <column> IS NULL, <column>`. The leading term is an expression, so MariaDB and MySQL could not read the order out of `idx_roms_<column>` and filesorted instead. PostgreSQL had the mirror problem descending: `DESC NULLS LAST` does not match the index's own order, so it fell back to a sequential scan. Neither engine paid this once. v2 window fetches send no sidecars, so each scroll window is its own `ORDER BY ... LIMIT 72 OFFSET n` over the full filtered set, and `roms` carries a JSON metadata blob per provider on every row. Each column now carries a STORED `_unset` flag with an `idx_roms_<column>_sort` pair the ascending sort leads with, and PostgreSQL gets an `idx_roms_<column>_desc` for the descending one. Row order is unchanged in both directions. Measured on PostgreSQL 16 over 120k roms, first page: ascending 30.6 ms / 8109 buffers -> 0.074 ms / 13 buffers descending 33.5 ms / 8091 buffers -> 0.112 ms / 14 buffers Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * fix(backend): rebuild a sort index MariaDB narrowed instead of dropped Testing the previous commit against MariaDB rather than PostgreSQL alone turned up a real bug in it. The two engines leave a dropped generated column in different states: PostgreSQL drops every index that reads it, while MariaDB and MySQL keep a composite one over the columns that survive. `_restore_generated_indexes` only created indexes missing by name, so on MariaDB the rebuild path in `ensure_roms_columns` (a chain predating 0123) would leave `idx_roms_<column>_sort` narrowed to the unset flag alone and the ascending gallery sort walking half an index. It now reconciles on the columns an index spans, not just its name, and `_drop_index_sql` gives the two dialects their own DROP INDEX spelling. Also corrects the flag columns' comments: MariaDB accepts no NOT NULL on a generated column in either position, so they are nullable in the DDL on both engines. `IS NULL` never evaluates to NULL, so no row carries one. Verified on MariaDB 10.11 over 120k roms. The ascending page went from `rows=116503, Using index; Using filesort` to `rows=72, Using index`, 134 ms to 6 ms, with the same plan once the rom_user join is added. Migration, schema and flag values also checked under utf8mb3_unicode_ci, the collation these expressions are most fragile under. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * style(backend): give the sort-flag rationale one home Greptile flagged the comment blocks in this PR against CLAUDE.md's comment discipline. The length was a symptom: the same explanation of why MariaDB cannot index the NULLS LAST emulation appeared in four places. It now lives once, beside `SORTABLE_NULLABLE_ROM_COLUMNS`, and the other sites say only what is local to them. No behaviour change; the migration docstrings are left as they are, matching the narrative style every recent revision uses. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * fix(backend): drop the sort indexes with the rest of the catalog Copilot pointed out that `ensure_roms_columns` installs the `_unset` columns long before 0129 runs, so a chain that stops short and then downgrades leaves them behind. Checking that turned up a real leak next to it: 0108's downgrade, which the module documents as removing whatever of the catalog such a chain still carries, was leaving two indexes. A descending sort index reads a value column this module inherited rather than added, so `drop_roms_columns` re-adds that column and the index over it survives. `_drop_sort_indexes` now takes them explicitly. PostgreSQL only, since no other engine has those indexes. The flag columns themselves are not a leak: the catalog front-loads every column it owns, so at 0127 the table already carries 0123's `generated_keywords`, `generated_themes` and `generated_rating_count` too. Verified on both engines that a 0128 to 0127 downgrade leaves the table writable with the flags still computing, and that re-upgrading restores the pair, narrowed index included. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * style(backend): tighten the teardown docstrings and the test annotation Two more from Greptile, both worth taking even though the reasoning behind each was off. `_drop_sort_indexes` and its test now carry a summary plus one line, matching `drop_roms_columns` right above them, and the parametrized metadata argument is typed instead of a bare `dict`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * perf(backend): index the remaining gallery sorts (#4644) * perf(backend): span the gallery sort indexes through the id tiebreak The gallery appends `id` to every ORDER BY, but `idx_roms_<column>_sort` stopped at the value and `idx_roms_<column>_desc` at the value alone. On PostgreSQL that leaves every tie to be sorted, and unset metadata is a single tie covering the whole bucket: a scroll window inside it fell back to a Seq Scan and an external merge sort. Both indexes now carry `id` in the sort's own direction, which InnoDB was already appending for MariaDB and MySQL. Measured on 120k roms, a window at offset 100000 (inside the unset bucket), all three columns, both directions: PostgreSQL ascending 119 ms, external merge sort -> 15 ms, index only PostgreSQL descending 92 ms, incremental sort -> 13 ms, index only MariaDB, both already index-only; unchanged No sort node remains in any of the twelve plans. Also trims the docstrings and comments this change touches to the repo's one-or-two-line rule. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * test(backend): pin the reflected order of the descending sort indexes The existing assertion read column names only, which a default ascending index satisfies just as well, and `AUTOGENERATE_EXEMPT_INDEX_NAMES` keeps the drift check away from these. Asserts the reflected `column_sorting` instead, and its absence on the ascending pair. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * fix(backend): declare the unset flags nullable, as their DDL is `Mapped[bool]` inferred NOT NULL while both engines create the column nullable, MariaDB because it takes no NOT NULL on a generated column. The four generated columns beside them already match their DDL. The annotation stays `bool`, since `IS NULL` never yields NULL. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NouZquWDxNBqxYyu2E2GF8 * fix(backend): renumber the gallery sort revisions after 0132 master gained its own 0129-0132 while this branch was open, and both chains started from 0128_hltb_main_story_column, leaving alembic with two heads (`upgrade head` fails with MultipleHeads). 0129_indexed_gallery_sorts -> 0133, now revising 0132_audit_events; 0130_gallery_sort_indexes -> 0134. No content change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VgcWNtJy6ucWRaibqNKNJC * fix(backend): re-chain the renamed gallery sort revisions onto 0132 The previous commit renamed the files but left their revision IDs and parent as they were. 0133 now revises 0132_audit_events, and both IDs match their filenames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VgcWNtJy6ucWRaibqNKNJC --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
394 lines
14 KiB
Python
394 lines
14 KiB
Python
import json
|
|
from datetime import date
|
|
from typing import Any, Sequence
|
|
from uuid import uuid4
|
|
|
|
import sqlalchemy as sa
|
|
from sqlalchemy.dialects import postgresql as sa_pg
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy.sql import ColumnElement, func
|
|
|
|
# What `Session.get_bind()` returns; these helpers only read `.engine`, which
|
|
# an Engine answers with itself.
|
|
type DatabaseBind = sa.Engine | sa.Connection
|
|
|
|
# Single-column foreign keys that MariaDB/MySQL index implicitly but PostgreSQL
|
|
# does not, so 0124 creates them there only and no model declares them.
|
|
POSTGRESQL_FK_INDEXES: tuple[tuple[str, str, str], ...] = (
|
|
("collections", "ix_collections_user_id", "user_id"),
|
|
("smart_collections", "ix_smart_collections_user_id", "user_id"),
|
|
("rom_notes", "ix_rom_notes_user_id", "user_id"),
|
|
("firmware", "ix_firmware_platform_id", "platform_id"),
|
|
("collections_roms", "ix_collections_roms_rom_id", "rom_id"),
|
|
("music_playlist_tracks", "ix_music_playlist_tracks_rom_file_id", "rom_file_id"),
|
|
("music_favorite_tracks", "ix_music_favorite_tracks_rom_file_id", "rom_file_id"),
|
|
("play_sessions", "ix_play_sessions_rom_id", "rom_id"),
|
|
("play_sessions", "ix_play_sessions_device_id", "device_id"),
|
|
("play_sessions", "ix_play_sessions_sync_session_id", "sync_session_id"),
|
|
("saves", "ix_saves_user_id", "user_id"),
|
|
("states", "ix_states_user_id", "user_id"),
|
|
("screenshots", "ix_screenshots_user_id", "user_id"),
|
|
("rom_file_user", "ix_rom_file_user_user_id", "user_id"),
|
|
("memory_cards", "ix_memory_cards_platform_id", "platform_id"),
|
|
(
|
|
"streaming_container_adoptions",
|
|
"ix_streaming_container_adoptions_decided_by_user_id",
|
|
"decided_by_user_id",
|
|
),
|
|
)
|
|
|
|
HLTB_MAIN_STORY_COLUMN = "generated_hltb_main_story"
|
|
|
|
# The nullable `roms` columns the gallery sorts on. MariaDB and MySQL have no
|
|
# NULLS LAST and cannot index the `IS NULL` term emulating it, so each column
|
|
# gets a materialized `_unset` flag the ascending sort leads with instead.
|
|
# Named here rather than in `utils.roms_columns`, which imports this module.
|
|
SORTABLE_NULLABLE_ROM_COLUMNS = (
|
|
"generated_first_release_date",
|
|
"generated_average_rating",
|
|
HLTB_MAIN_STORY_COLUMN,
|
|
)
|
|
|
|
|
|
def rom_unset_flag_column(column: str) -> str:
|
|
"""The generated flag column recording whether `column` is unset."""
|
|
return f"{column}_unset"
|
|
|
|
|
|
def rom_sort_index_name(column: str) -> str:
|
|
"""The composite index the ascending gallery sort on `column` walks."""
|
|
return f"idx_roms_{column}_sort"
|
|
|
|
|
|
def rom_desc_index_name(column: str) -> str:
|
|
"""The PostgreSQL-only index the descending gallery sort on `column` walks."""
|
|
return f"idx_roms_{column}_desc"
|
|
|
|
|
|
# Indexes that exist in some databases but cannot be declared on a model.
|
|
AUTOGENERATE_EXEMPT_INDEX_NAMES = (
|
|
frozenset(
|
|
# Search indexes built per dialect in 0084: FULLTEXT on MySQL/MariaDB,
|
|
# pg_trgm GIN on PostgreSQL. No portable model declaration exists.
|
|
{
|
|
"idx_roms_name_fs_name_fulltext",
|
|
"idx_roms_name_trgm",
|
|
"idx_roms_fs_name_trgm",
|
|
}
|
|
)
|
|
| frozenset(name for _, name, _ in POSTGRESQL_FK_INDEXES)
|
|
# `DESC NULLS LAST` is the only spelling that matches what the descending
|
|
# gallery sort asks for, and no other engine parses it.
|
|
| frozenset(rom_desc_index_name(c) for c in SORTABLE_NULLABLE_ROM_COLUMNS)
|
|
)
|
|
|
|
|
|
def CustomJSON(**kwargs: Any) -> sa.JSON:
|
|
"""Custom SQLAlchemy JSON type that uses JSONB on PostgreSQL."""
|
|
return sa.JSON(**kwargs).with_variant(sa_pg.JSONB(**kwargs), "postgresql")
|
|
|
|
|
|
def is_db_version_compatible(
|
|
conn: DatabaseBind,
|
|
min_version: tuple[int, ...] | None = None,
|
|
) -> bool:
|
|
"""Check if the database server version complies with the given version constraints."""
|
|
if min_version is None:
|
|
return True
|
|
server_version = conn.engine.dialect.server_version_info
|
|
return bool(server_version and server_version >= min_version)
|
|
|
|
|
|
def is_postgresql(
|
|
conn: DatabaseBind, min_version: tuple[int, ...] | None = None
|
|
) -> bool:
|
|
if conn.engine.name != "postgresql":
|
|
return False
|
|
return is_db_version_compatible(conn, min_version=min_version)
|
|
|
|
|
|
def is_mysql(conn: DatabaseBind, min_version: tuple[int, ...] | None = None) -> bool:
|
|
if conn.engine.name != "mysql":
|
|
return False
|
|
return is_db_version_compatible(conn, min_version=min_version)
|
|
|
|
|
|
def is_mariadb(conn: DatabaseBind, min_version: tuple[int, ...] | None = None) -> bool:
|
|
if conn.engine.name != "mariadb":
|
|
return False
|
|
return is_db_version_compatible(conn, min_version=min_version)
|
|
|
|
|
|
# Error 1419, which MariaDB and MySQL raise for every trigger statement while
|
|
# binary logging is on and the user lacks SUPER (issue #3932).
|
|
BINLOG_TRIGGER_DDL_ERRNO = 1419
|
|
|
|
|
|
def alembic_command_runs_revisions(command: str, *, pending: bool) -> bool:
|
|
"""Whether this alembic command reaches revision code, trigger DDL included.
|
|
|
|
`command` is the `fn` name alembic hands its environment, not the CLI word.
|
|
"""
|
|
return command == "downgrade" or (command == "upgrade" and pending)
|
|
|
|
|
|
def is_binlog_trigger_privilege_error(exc: BaseException) -> bool:
|
|
"""Whether `exc` is the server refusing trigger DDL under binary logging."""
|
|
orig = getattr(exc, "orig", exc)
|
|
errno = getattr(orig, "errno", None)
|
|
if errno is None:
|
|
args = getattr(orig, "args", ())
|
|
errno = args[0] if args else None
|
|
return errno == BINLOG_TRIGGER_DDL_ERRNO
|
|
|
|
|
|
def probe_trigger_name() -> str:
|
|
"""A trigger name no schema can already hold, for the privilege probe.
|
|
|
|
Trigger names are schema-wide, so a fixed one could name an operator's own
|
|
trigger and the probe would really drop it.
|
|
"""
|
|
return f"romm_trigger_ddl_probe_{uuid4().hex}"
|
|
|
|
|
|
def trigger_ddl_is_blocked(conn: sa.Connection) -> bool:
|
|
"""Whether the server refuses the trigger DDL the migrations need.
|
|
|
|
Dropping a trigger that cannot exist is the cheapest statement that still
|
|
goes through the privilege check, and the only error it can raise is the
|
|
refusal itself. Rolls `conn` back on one.
|
|
"""
|
|
if not (is_mysql(conn) or is_mariadb(conn)):
|
|
return False
|
|
|
|
try:
|
|
conn.exec_driver_sql(f"DROP TRIGGER IF EXISTS {probe_trigger_name()}")
|
|
except sa.exc.DBAPIError as exc:
|
|
conn.rollback()
|
|
return is_binlog_trigger_privilege_error(exc)
|
|
|
|
return False
|
|
|
|
|
|
def column_names(conn: sa.Connection, table: str) -> set[str]:
|
|
"""The columns `table` currently carries, for guards over a set of them.
|
|
|
|
One reflection answers the whole set; `has_column` per candidate costs one
|
|
round-trip each.
|
|
"""
|
|
return {column["name"] for column in sa.inspect(conn).get_columns(table)}
|
|
|
|
|
|
def has_column(conn: sa.Connection, table: str, column: str) -> bool:
|
|
"""Whether `table` already carries `column`, which `Inspector` cannot answer."""
|
|
return column in column_names(conn, table)
|
|
|
|
|
|
def full_path_digest_sql(conn: sa.Connection) -> str:
|
|
"""`models.rom.compute_full_path_hash` spelled in SQL, for 0126's backfill.
|
|
|
|
`test_migrations` pins this to the Python function it mirrors.
|
|
"""
|
|
# COALESCE because the Python side reads a NULL as "", while both dialects
|
|
# would fold the whole concatenation to NULL and fail 0126's NOT NULL step.
|
|
if is_postgresql(conn):
|
|
return (
|
|
"encode(sha256(convert_to(COALESCE(fs_path, '') || '/' || "
|
|
"COALESCE(fs_name, ''), 'UTF8')), 'hex')"
|
|
)
|
|
return "SHA2(CONCAT(COALESCE(fs_path, ''), '/', COALESCE(fs_name, '')), 256)"
|
|
|
|
|
|
def json_array_contains_value(
|
|
column: sa.Column | Any, value: str | int, *, session: Session
|
|
) -> ColumnElement:
|
|
"""Check if a JSON array column contains the given value."""
|
|
conn = session.get_bind()
|
|
if is_postgresql(conn):
|
|
# In PostgreSQL, string values can be checked for containment using the `?` operator.
|
|
# For other types, we use the `@>` operator.
|
|
if isinstance(value, str):
|
|
return sa.type_coerce(column, sa_pg.JSONB).has_key(value)
|
|
return sa.type_coerce(column, sa_pg.JSONB).contains(
|
|
func.cast(sa.literal(value, sa_pg.JSONB), sa_pg.JSONB)
|
|
)
|
|
elif is_mysql(conn) or is_mariadb(conn):
|
|
# In MySQL and MariaDB, JSON_CONTAINS requires a JSON-formatted string (even if it's an int).
|
|
return func.json_contains(column, json.dumps(value))
|
|
|
|
raise NotImplementedError(
|
|
f"json_array_contains_value is not implemented for engine: {conn.engine.name}"
|
|
)
|
|
|
|
|
|
def json_array_contains_any(
|
|
column: sa.Column | Any, values: Sequence[str] | Sequence[int], *, session: Session
|
|
) -> ColumnElement:
|
|
"""Check if a JSON array column contains any of the given values."""
|
|
if not values:
|
|
return sa.false()
|
|
|
|
# Optimize for single value case
|
|
if len(values) == 1:
|
|
return json_array_contains_value(column, values[0], session=session)
|
|
|
|
conn = session.get_bind()
|
|
if is_postgresql(conn):
|
|
# In PostgreSQL, string arrays can be checked for overlap using the `?|` operator.
|
|
# For other types, we combine element-wise checks with OR.
|
|
if isinstance(values[0], str):
|
|
return sa.type_coerce(column, sa_pg.JSONB).has_any(
|
|
sa.type_coerce(values, sa_pg.ARRAY(sa_pg.TEXT))
|
|
)
|
|
return sa.or_(
|
|
*[json_array_contains_value(column, v, session=session) for v in values]
|
|
)
|
|
elif is_mysql(conn) or is_mariadb(conn, min_version=(10, 9)):
|
|
# In MySQL and MariaDB, JSON_OVERLAPS requires a JSON-formatted string (even if it's an int).
|
|
return func.json_overlaps(column, json.dumps(values))
|
|
elif is_mariadb(conn):
|
|
# MariaDB before 10.9 does not have JSON_OVERLAPS, so we fall back to element-wise checks.
|
|
return sa.or_(
|
|
*[json_array_contains_value(column, v, session=session) for v in values]
|
|
)
|
|
|
|
raise NotImplementedError(
|
|
f"json_array_contains_any is not implemented for engine: {conn.engine.name}"
|
|
)
|
|
|
|
|
|
def json_array_contains_all(
|
|
column: sa.Column | Any, values: Sequence[Any], *, session: Session
|
|
) -> ColumnElement:
|
|
"""Check if a JSON array column contains all of the given values."""
|
|
if not values:
|
|
return sa.false()
|
|
|
|
conn = session.get_bind()
|
|
if is_postgresql(conn):
|
|
# In PostgreSQL, string arrays can be checked for containment using the `?&` operator.
|
|
# For other types, we combine element-wise checks with AND.
|
|
if isinstance(values[0], str):
|
|
return sa.type_coerce(column, sa_pg.JSONB).has_all(
|
|
sa.type_coerce(values, sa_pg.ARRAY(sa_pg.TEXT))
|
|
)
|
|
return sa.and_(
|
|
*[json_array_contains_value(column, v, session=session) for v in values]
|
|
)
|
|
elif is_mysql(conn) or is_mariadb(conn):
|
|
# In MySQL and MariaDB, JSON_CONTAINS requires a JSON-formatted string (even if it's an int).
|
|
return func.json_contains(column, json.dumps(values))
|
|
|
|
raise NotImplementedError(
|
|
f"json_array_contains_all is not implemented for engine: {conn.engine.name}"
|
|
)
|
|
|
|
|
|
MS_PER_DAY = 86_400_000
|
|
|
|
# Tennis for Two (1958) predates the epoch, so the oldest ranges are negative.
|
|
EARLIEST_RELEASE_YEAR = 1958
|
|
|
|
# The range union has to be finite, so "any year" stops here.
|
|
LATEST_RELEASE_YEAR = 2100
|
|
|
|
_EPOCH = date(1970, 1, 1)
|
|
|
|
|
|
def day_of_year_ranges(
|
|
month: int, day: int, *, before_year: int
|
|
) -> list[tuple[int, int]]:
|
|
"""Half-open epoch-millisecond ranges covering (month, day) in each earlier year.
|
|
|
|
Ranges rather than `MONTH()/DAY()` on the value, because they are sargable
|
|
and emit no SQL date function, so every dialect plans them the same way.
|
|
|
|
Args:
|
|
month: Calendar month, 1-12.
|
|
day: Day of the month, 1-31.
|
|
before_year: Exclusive upper bound on the years covered.
|
|
|
|
Returns:
|
|
Ascending (start, end) pairs, skipping years the date does not exist in,
|
|
so an impossible date yields none at all.
|
|
"""
|
|
ranges: list[tuple[int, int]] = []
|
|
for year in range(EARLIEST_RELEASE_YEAR, before_year):
|
|
try:
|
|
start = (date(year, month, day) - _EPOCH).days * MS_PER_DAY
|
|
except ValueError:
|
|
continue
|
|
ranges.append((start, start + MS_PER_DAY))
|
|
|
|
return ranges
|
|
|
|
|
|
def release_day_ranges(
|
|
days: Sequence[tuple[int, int]], *, before_year: int | None = None
|
|
) -> list[tuple[int, int]]:
|
|
"""Epoch-millisecond ranges covering every day in `days`, in every year.
|
|
|
|
Args:
|
|
days: (month, day) pairs to match.
|
|
before_year: Exclusive upper bound on the years covered, defaulting to
|
|
`LATEST_RELEASE_YEAR`.
|
|
|
|
Returns:
|
|
(start, end) pairs, skipping years a date does not exist in.
|
|
"""
|
|
bound = LATEST_RELEASE_YEAR if before_year is None else before_year
|
|
|
|
return [
|
|
day_range
|
|
for month, day in days
|
|
for day_range in day_of_year_ranges(month, day, before_year=bound)
|
|
]
|
|
|
|
|
|
def epoch_ms_in_ranges(
|
|
column: sa.Column | Any, ranges: Sequence[tuple[int, int]]
|
|
) -> ColumnElement:
|
|
"""Match an epoch-millisecond column against any of the given half-open ranges."""
|
|
if not ranges:
|
|
return sa.false()
|
|
|
|
return sa.or_(
|
|
*[sa.and_(column >= start, column < end) for start, end in sorted(ranges)]
|
|
)
|
|
|
|
|
|
LIKE_ESCAPE_CHAR = "\\"
|
|
|
|
|
|
def escape_like(term: str) -> str:
|
|
"""Escape LIKE wildcards so a search term matches literally (pass escape=LIKE_ESCAPE_CHAR to like())."""
|
|
return (
|
|
term.replace(LIKE_ESCAPE_CHAR, LIKE_ESCAPE_CHAR * 2)
|
|
.replace("%", f"{LIKE_ESCAPE_CHAR}%")
|
|
.replace("_", f"{LIKE_ESCAPE_CHAR}_")
|
|
)
|
|
|
|
|
|
def safe_str_to_bool(value: Any, default: bool = False) -> bool:
|
|
"""Safely convert a value to bool, returning default if conversion fails."""
|
|
try:
|
|
return value.strip().lower() in ("1", "true", "yes", "on")
|
|
except ValueError, TypeError, AttributeError:
|
|
return default
|
|
|
|
|
|
def safe_float(value: Any, default: float = 0.0) -> float:
|
|
"""Safely convert a value to float, returning default if conversion fails."""
|
|
try:
|
|
return float(value)
|
|
except ValueError, TypeError:
|
|
return default
|
|
|
|
|
|
def safe_int(value: Any, default: int = 0) -> int:
|
|
"""Safely convert a value to int, returning default if conversion fails."""
|
|
try:
|
|
return int(value)
|
|
except ValueError, TypeError:
|
|
return default
|