File size: 6,634 Bytes
06aad61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | """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)
|