Files
TJWaterServerBinary/app/native/wndb/model/energy.py
T
jiang fa188af0b1 refactor(db)!: adopt project-routed pooled databases
Reorganize WNDB by responsibility and remove legacy scheme endpoints.\n\nRoute analysis and time-series access through project pools, preserve transactional realtime replacement, and refresh GIS materialized views after writes.\n\nAdd database architecture documentation, live pooling coverage, API contract updates, and executable container verification.\n\nBREAKING CHANGE: legacy scheme APIs and flat app.native.wndb module imports are removed.
2026-08-25 18:35:05 +08:00

221 lines
7.9 KiB
Python

from typing import Any
from ..core.database import (
ChangeSet,
DatabaseCommand,
execute_command,
g_update_prefix,
read_all,
sql_literal,
try_read,
)
element_schema = {'type': 'str' , 'optional': True , 'readonly': False}
def get_energy_schema(name: str) -> dict[str, dict[str, Any]]:
return { 'GLOBAL PRICE' : element_schema,
'GLOBAL PATTERN' : element_schema,
'GLOBAL EFFIC' : element_schema,
'DEMAND CHARGE' : element_schema }
def get_energy(name: str) -> dict[str, Any]:
ts = read_all(name, "select key, value from network.energy_settings")
d = {}
for e in ts:
d[e['key']] = str(e['value'])
return d
def _set_energy(name: str, cs: ChangeSet) -> DatabaseCommand:
new = {}
new_dict = cs.operations[0]
schema = get_energy_schema(name)
for key in schema.keys():
if key in new_dict:
new[key] = str(new_dict[key])
change = g_update_prefix | { 'type' : 'energy' }
statement = ''
for key, value in new.items():
if statement != '':
statement += '\n'
statement += f"update network.energy_settings set value = {sql_literal(value)} where key = {sql_literal(key)};"
change |= { key: value }
return DatabaseCommand(statement, [change])
def set_energy(name: str, cs: ChangeSet) -> ChangeSet:
return execute_command(name, _set_energy(name, cs))
def get_pump_energy_schema(name: str) -> dict[str, dict[str, Any]]:
return { 'pump' : {'type': 'str' , 'optional': False , 'readonly': True },
'price' : {'type': 'float' , 'optional': True , 'readonly': False},
'pattern' : {'type': 'str' , 'optional': True , 'readonly': False},
'effic' : {'type': 'str' , 'optional': True , 'readonly': False} }
def get_pump_energy(name: str, pump: str) -> dict[str, Any]:
d = {}
d['pump'] = pump
pe = try_read(name, "select price, pattern_id as pattern, efficiency_curve_id as effic from network.pump_energy_settings where pump_id = %s", (pump,))
d['price'] = float(pe['price']) if pe is not None and pe['price'] is not None else None
d['pattern'] = str(pe['pattern']) if pe is not None and pe['pattern'] is not None else None
d['effic'] = str(pe['effic']) if pe is not None and pe['effic'] is not None else None
return d
class PumpEnergy(object):
def __init__(self, input: dict[str, Any]) -> None:
self.type = 'pump_energy'
self.pump = str(input['pump'])
self.price = float(input['price']) if 'price' in input and input['price'] != None else None
self.pattern = str(input['pattern']) if 'pattern' in input and input['pattern'] != None else None
self.effic = str(input['effic']) if 'effic' in input and input['effic'] != None else None
self.f_type = sql_literal(self.type)
self.f_pump = sql_literal(self.pump)
self.f_price = sql_literal(self.price)
self.f_pattern = sql_literal(self.pattern)
self.f_effic = sql_literal(self.effic)
def as_dict(self) -> dict[str, Any]:
return { 'type': self.type, 'pump': self.pump, 'price': self.price, 'pattern': self.pattern, 'effic': self.effic }
def _set_pump_energy(name: str, cs: ChangeSet) -> DatabaseCommand:
raw_new = get_pump_energy(name, cs.operations[0]['pump'])
new_dict = cs.operations[0]
schema = get_pump_energy_schema(name)
for key, value in schema.items():
if key in new_dict and not value['readonly']:
raw_new[key] = new_dict[key]
new = PumpEnergy(raw_new)
statement = f"delete from network.pump_energy_settings where pump_id = {new.f_pump};"
if new.price is not None or new.pattern is not None or new.effic is not None:
statement += f"\ninsert into network.pump_energy_settings (pump_id, efficiency_curve_id, pattern_id, price) values ({new.f_pump}, {new.f_effic}, {new.f_pattern}, {new.f_price});"
change = g_update_prefix | new.as_dict()
return DatabaseCommand(statement, [change])
def set_pump_energy(name: str, cs: ChangeSet) -> ChangeSet:
return execute_command(name, _set_pump_energy(name, cs))
#--------------------------------------------------------------
# [EPA2][EPA3][IN][OUT]
# GLOBAL {PRICE/PATTERN/EFFIC} value
# PUMP id {PRICE/PATTERN/EFFIC} value
# DEMAND CHARGE value
#--------------------------------------------------------------
def inp_in_energy(line: str) -> str:
tokens = line.split()
if tokens[0].upper() == 'PUMP':
pump = tokens[1]
key = tokens[2].lower()
value = tokens[3]
if key == 'price':
value = float(value)
if key == 'efficiency':
key = 'effic'
column = {'price': 'price', 'pattern': 'pattern_id', 'effic': 'efficiency_curve_id'}[key]
return str(f"insert into network.pump_energy_settings (pump_id, {column}) values ({sql_literal(pump)}, {sql_literal(value)}) on conflict (pump_id) do update set {column} = excluded.{column};")
else:
line = line.upper().strip()
for key in get_energy_schema('').keys():
if line.startswith(key):
value = line.removeprefix(key).strip()
# exception here
if line.startswith('GLOBAL EFFICIENCY'):
value = line.removeprefix('GLOBAL EFFICIENCY').strip()
return str(f"update network.energy_settings set value = {sql_literal(value)} where key = {sql_literal(key)};")
return str('')
def inp_out_energy(name: str) -> list[str]:
lines = []
objs = read_all(name, "select key, value from network.energy_settings order by key")
for obj in objs:
key = obj['key']
value = obj['value']
if value.strip() != '':
lines.append(f'{key} {value}')
objs = read_all(name, "select pump_id as pump, price, pattern_id as pattern, efficiency_curve_id as effic from network.pump_energy_settings order by pump_id")
for obj in objs:
pump = obj['pump']
if obj['price'] is not None:
lines.append(f"PUMP {pump} PRICE {obj['price']}")
if obj['pattern'] is not None:
lines.append(f"PUMP {pump} PATTERN {obj['pattern']}")
if obj['effic'] is not None:
lines.append(f"PUMP {pump} EFFIC {obj['effic']}")
return lines
def delete_pump_energy_by_pump(name: str, pump: str) -> ChangeSet:
row = try_read(
name,
"select pump_id from network.pump_energy_settings where pump_id = %s",
(pump,),
)
if row is None:
return ChangeSet()
return ChangeSet(g_update_prefix | {'type': 'pump_energy', 'pump' : pump, 'price': None, 'pattern': None, 'effic': None})
def unset_pump_energy_by_pattern(name: str, pattern: str) -> ChangeSet:
cs = ChangeSet()
rows = read_all(
name,
"select pump_id as pump, price, efficiency_curve_id as effic "
"from network.pump_energy_settings where pattern_id = %s",
(pattern,),
)
for row in rows:
pump = row['pump']
price = float(row['price']) if row['price'] is not None else None
effic = str(row['effic']) if row['effic'] is not None else None
cs.append(g_update_prefix | {'type': 'pump_energy', 'pump' : pump, 'price': price, 'pattern': None, 'effic': effic})
return cs
def unset_pump_energy_by_curve(name: str, curve: str) -> ChangeSet:
cs = ChangeSet()
rows = read_all(
name,
"select pump_id as pump, price, pattern_id as pattern "
"from network.pump_energy_settings where efficiency_curve_id = %s",
(curve,),
)
for row in rows:
pump = row['pump']
price = float(row['price']) if row['price'] is not None else None
pattern = str(row['pattern']) if row['pattern'] is not None else None
cs.append(g_update_prefix | {'type': 'pump_energy', 'pump' : pump, 'price': price, 'pattern': pattern, 'effic': None})
return cs