Files

82 lines
2.3 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.
# -*- coding: utf-8 -*-
"""演示用内存 DB:实现 pymysql 连接对象的最小接口
(cursor / execute / fetchall / commit / rollback / close)。
只做一件事:把 "select ... from <table>" 映射到内置合成数据表,
让 dao 层与用例在没有真实 MySQL 的环境下开箱可跑。
"""
import re
_TABLES = {
'mes_user': {
'columns': ['id', 'account_num', 'name', 'organization_id', 'del_flag'],
'rows': [
(1, 'demo_user', '张三', 10, 0),
(2, 'operator01', '李四', 11, 0),
],
},
'mes_device': {
'columns': ['id', 'name', 'del_flag'],
'rows': [(101, '注塑机-01', 0), (102, '注塑机-02', 0)],
},
'mes_mold': {
'columns': ['id', 'name', 'del_flag'],
'rows': [(201, '模具-A', 0), (202, '模具-B', 0)],
},
'mes_quality_inspection_point': {
'columns': ['id', 'name', 'del_flag'],
'rows': [(301, '外观缺陷', 0), (302, '尺寸不良', 0)],
},
'mes_quality_inspection_type': {
'columns': ['id', 'name', 'del_flag'],
'rows': [(401, '首检', 0)],
},
'mes_work_order': {
'columns': ['id', 'product_id', 'plan_yield', 'del_flag'],
'rows': [(501, 601, 300, 0)],
},
}
class FakeCursor:
def __init__(self):
self.description = None
self._rows = []
self._sql = ''
def execute(self, sql, params=None):
self._sql = sql
m = re.search(r'from\s+(\w+)', sql, re.IGNORECASE)
table = _TABLES.get(m.group(1) if m else '', None)
if table is None:
self.description = None
self._rows = []
return 0
self.description = [(c,) for c in table['columns']]
self._rows = list(table['rows'])
# 支持演示所需的最小 WHERE 过滤:account_num = %s
if params and 'account_num' in sql:
idx = table['columns'].index('account_num')
self._rows = [r for r in self._rows if r[idx] == params[0]]
return len(self._rows)
def fetchall(self):
return self._rows
def close(self):
pass
class FakeDB:
def cursor(self):
return FakeCursor()
def commit(self):
pass
def rollback(self):
pass
def close(self):
pass