tradingSystem/app/core/strategy_book.py

61 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""策略账本范围。默认原策略,全账户范围只允许读取。"""
import contextlib
import contextvars
import re
ORIGINAL = 'original'
MICRO = 'micro30'
CURRENT = contextvars.ContextVar('strategy_book', default=ORIGINAL)
TABLES = frozenset({'pms_command', 'pms_plan', 'pms_position', 'pms_lot',
'pms_instruction', 'pms_proposal', 'pms_action_ledger', 'pms_cash_flow', 'pms_strategy'})
@contextlib.contextmanager
def scope(book):
if book not in (ORIGINAL, MICRO, 'all'):
raise ValueError('未知策略账本')
token = CURRENT.set(book)
try:
yield
finally:
CURRENT.reset(token)
def scoped_sql(sql, book=None):
"""只改既有单表语句的顶层条件,字符串与括号内部不参与定位。"""
book = book or CURRENT.get()
if book not in (ORIGINAL, MICRO, 'all'):
raise ValueError('未知策略账本')
match = re.search(r'\b(?:FROM|UPDATE|INTO)\s+(pms_\w+)\b', sql, re.I)
if not match or match.group(1) not in TABLES:
return sql
verb = sql.lstrip().split()[0].upper()
if verb not in ('SELECT', 'INSERT', 'UPDATE', 'DELETE'):
return sql
if book == 'all':
if verb != 'SELECT':
raise ValueError('全账户范围禁止直接写入策略账本')
return sql
if verb == 'INSERT':
m = re.match(r'(\s*INSERT\s+INTO\s+pms_\w+\s*\()([^)]*)(\)\s*VALUES\s*\()', sql, re.I)
if not m or re.search(r'\bbook_id\b', m.group(2), re.I):
raise ValueError('策略账本INSERT形状不受支持或重复指定归属')
return m.group(1)+'book_id, '+m.group(2)+m.group(3)+"'"+book+"', "+sql[m.end():]
# 屏蔽引号,不改变字符下标。顶层WHERE整体包裹,避免OR越过账本条件。
masked = re.sub(r"'(?:''|\\.|[^'])*'|\"(?:\\.|[^\"])*\"", lambda m: ' '*len(m.group()), sql)
depth, tokens = 0, []
for m in re.finditer(r'\(|\)|\b(?:WHERE|GROUP\s+BY|ORDER\s+BY|LIMIT|FOR\s+UPDATE)\b', masked, re.I):
if m.group() == '(':
depth += 1
elif m.group() == ')':
depth -= 1
elif depth == 0:
tokens.append((m.group().upper(), m.start(), m.end()))
where = next((t for t in tokens if t[0] == 'WHERE'), None)
tail = next((t for t in tokens if t[0] != 'WHERE'), None)
end = tail[1] if tail else len(sql)
condition = "book_id = '"+book+"'"
if where:
return sql[:where[1]]+'WHERE '+condition+' AND ('+sql[where[2]:end].strip()+') '+sql[end:]
return sql[:end].rstrip()+' WHERE '+condition+' '+sql[end:]