Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download platform/core/database_setup.py from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/platform/core/database_setup.py
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/platform/core/database_setup.py
-
curl -L -o database_setup.py https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/platform/core/database_setup.py
6.63 kB
| """Durable, tenant-scoped setup for one database. | |
| The document is deliberately separate from a saved View. A View arranges one person's | |
| reading of records; a database setup names a property every Map of that database must share. | |
| The first section is ``map.latField`` + ``map.lonField``: the two actual database columns used | |
| to plot records. Future database-owned setup sections extend the record below rather than adding | |
| another per-View preference. | |
| Document shape:: | |
| {"<database key>": {"map": {"latField": "latitude", "lonField": "longitude"}}} | |
| An absent map section means "try the database's built-in ``lat``/``lon`` transport values". | |
| That is an honest default for every database: a Map can always open; only records without a | |
| usable location fail to produce pins. | |
| """ | |
| STORE_KEY = "database_setup" | |
| COORDINATE_FIELD_TYPES = frozenset({ | |
| "text", "int", "currency", "pct", "rating", "number", "float", "decimal", | |
| }) | |
| _LEGACY_COMPOSITE_FIELD_TYPES = frozenset({"text", "url", "email"}) | |
| MAX_FIELD_KEY = 160 | |
| class DatabaseSetupRefused(ValueError): | |
| """A setup input that cannot become a durable database setting.""" | |
| def coordinate_fields(fields): | |
| """The fields that can carry one latitude or longitude value. | |
| The caller supplies its served field contract, so a hidden or removed field can never be | |
| exposed by this small configuration record. A coordinate can be a numeric cell or text that | |
| parses as one; status and choice values remain deliberately excluded. | |
| """ | |
| out = [] | |
| seen = set() | |
| for field in fields or (): | |
| if not isinstance(field, dict): | |
| continue | |
| key = field.get("key") | |
| if not isinstance(key, str) or not key or key in seen: | |
| continue | |
| if field.get("type") not in COORDINATE_FIELD_TYPES: | |
| continue | |
| seen.add(key) | |
| out.append({"key": key, | |
| "label": str(field.get("label") or key), | |
| "type": str(field.get("type") or "text")}) | |
| return out | |
| def _read(st): | |
| """Read this tenant's setup document; callers always provide their tenant runtime.""" | |
| if st is None: | |
| raise DatabaseSetupRefused("a tenant store handle is required") | |
| doc = st.get(STORE_KEY) | |
| return doc if isinstance(doc, dict) else {} | |
| def map_for(database_key, fields, *, st): | |
| """The currently usable Map setup for a served field contract. | |
| A stale setup is ignored rather than guessed. If either configured field was removed or | |
| hidden, Map falls back to its built-in pair until an editor chooses another source. | |
| """ | |
| allowed = {field["key"]: field for field in coordinate_fields(fields)} | |
| if not allowed: | |
| return {} | |
| try: | |
| entry = _read(st).get(str(database_key)) | |
| except Exception: | |
| # A setup read is additive display metadata. The grid remains usable and Map retains | |
| # its historical lat/lon fallback while the store is unavailable. | |
| return {} | |
| bag = entry.get("map") if isinstance(entry, dict) else None | |
| if not isinstance(bag, dict): | |
| return {} | |
| lat_field, lon_field = bag.get("latField"), bag.get("lonField") | |
| if (isinstance(lat_field, str) and isinstance(lon_field, str) | |
| and lat_field != lon_field and lat_field in allowed and lon_field in allowed): | |
| return {"latField": lat_field, "lonField": lon_field} | |
| # A short-lived prerelease used one composite text field. Keep reading it so no tenant loses | |
| # pins, but new setup always saves the explicit pair above. | |
| legacy = bag.get("coordField") | |
| if (isinstance(legacy, str) and legacy in allowed | |
| and allowed[legacy].get("type") in _LEGACY_COMPOSITE_FIELD_TYPES): | |
| return {"coordField": legacy} | |
| return {} | |
| def set_map(database_key, lat_field, lon_field, fields, *, st): | |
| """Atomically set or clear one database's custom Map latitude/longitude pair. | |
| Both values as ``None`` clear the custom override and restore the built-in lat/lon fallback. | |
| The updater | |
| preserves every other database and any future setup section, so this first setting establishes | |
| a stable per-database setup home rather than another one-off bucket. | |
| """ | |
| key = str(database_key or "").strip() | |
| if not key: | |
| raise DatabaseSetupRefused("a database key is required") | |
| def clean_field(value, label): | |
| if value is None: | |
| return None | |
| if not isinstance(value, str): | |
| raise DatabaseSetupRefused(f"the {label} field must be text or null") | |
| value = value.strip() | |
| if not value: | |
| return None | |
| if len(value) > MAX_FIELD_KEY: | |
| raise DatabaseSetupRefused(f"the {label} field name is too long") | |
| return value | |
| lat_field = clean_field(lat_field, "latitude") | |
| lon_field = clean_field(lon_field, "longitude") | |
| if (lat_field is None) != (lon_field is None): | |
| raise DatabaseSetupRefused("choose both latitude and longitude fields, or use built-in coordinates") | |
| if lat_field is not None and lat_field == lon_field: | |
| raise DatabaseSetupRefused("latitude and longitude must use different fields") | |
| allowed = {field["key"] for field in coordinate_fields(fields)} | |
| if lat_field is not None and (lat_field not in allowed or lon_field not in allowed): | |
| raise DatabaseSetupRefused("choose latitude and longitude fields from this database") | |
| if st is None: | |
| raise DatabaseSetupRefused("a tenant store handle is required") | |
| def update(raw): | |
| document = dict(raw) if isinstance(raw, dict) else {} | |
| entry = dict(document.get(key) or {}) if isinstance(document.get(key), dict) else {} | |
| map_bag = dict(entry.get("map") or {}) if isinstance(entry.get("map"), dict) else {} | |
| # Also remove the prerelease composite shape: one save migrates the database to its | |
| # explicit coordinate pair while preserving any unrelated future Map settings. | |
| map_bag.pop("coordField", None) | |
| if lat_field is None: | |
| map_bag.pop("latField", None) | |
| map_bag.pop("lonField", None) | |
| else: | |
| map_bag["latField"] = lat_field | |
| map_bag["lonField"] = lon_field | |
| if map_bag: | |
| entry["map"] = map_bag | |
| else: | |
| entry.pop("map", None) | |
| if entry: | |
| document[key] = entry | |
| else: | |
| document.pop(key, None) | |
| return document | |
| try: | |
| st.update(STORE_KEY, update, flush="sync") | |
| except Exception as exc: | |
| raise DatabaseSetupRefused("the database setup could not be saved") from exc | |
| return map_for(key, fields, st=st) | |