Skip to content

Commit

Permalink
Fix bugs: tag trim.
Browse files Browse the repository at this point in the history
  • Loading branch information
ralgond committed Dec 5, 2024
1 parent d185614 commit 1dab66c
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 14 deletions.
5 changes: 4 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ def main():
# sql, param_list = mm.update("testSet", {'category': "banana", "price": 500, "name":"a"})
# print(sql, param_list)

sql, param_list = mm.select("testStringReplace", {'id':1, 'date':"20241204"})
# sql, param_list = mm.select("testStringReplace", {'id':1, 'date':"20241204"})
# print(sql, param_list)

sql, param_list = mm.insert("testInsertSelective", {'name': 'Candy', 'category': "C", 'price':500})
print(sql, param_list)

# cur.execute(sql, param_list, multi=True)
Expand Down
30 changes: 30 additions & 0 deletions example_profile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from flask import Flask
import mysql.connector
from mybatis import Mybatis
import json

app = Flask(__name__)


# 连接到 MySQL 数据库
conn = mysql.connector.connect(
host="localhost", # MySQL 主机地址
user="mybatis", # MySQL 用户名
password="mybatis", # MySQL 密码
database="mybatis" # 需要连接的数据库
)

mb = Mybatis(conn, "mapper", cache_memory_limit=50*1024*1024)

@app.route('/')
def hello():
ret = mb.select_one("testBasic1", {'id':1})
return json.dumps(ret)


def main():
for i in range(100000):
hello()

if __name__ == "__main__":
main()
26 changes: 26 additions & 0 deletions mapper/test.xml
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,30 @@
<select id="testBasic1">
SELECT * from fruits where id=#{id}
</select>

<insert id="testInsertSelective">
insert into fruits
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="'name' in params">
name,
</if>
<if test="'category' in params">
category,
</if>
<if test="'price' in params">
price,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="'name' in params">
#{name},
</if>
<if test="'category' in params">
#{category},
</if>
<if test="'price' in params">
#{price},
</if>
</trim>
</insert>
</mapper>
80 changes: 67 additions & 13 deletions mybatis/mapper_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,53 @@ def read_mapper_xml_file(self, mapper_xml_file_path):
self.id_2_element_map[child_id] = child


# @staticmethod
# def _trim_prefix(s : str, prefixes : Set[str]):
# l = [term.strip() for term in s.split()]
# idx = 0
# for term in l:
# if term in prefixes:
# idx += 1
# continue
# else:
# break
#
# return " ".join(l[idx:])

@staticmethod
def _trim_prefix(s : str, prefixes : Set[str]):
def _trim_prefix(s: str, prefixes: Set[str]):
p = [term[0] for term in sorted([(prefix, len(prefix)) for prefix in prefixes], key=lambda x: x[1], reverse=True)]
l = [term.strip() for term in s.split()]
idx = 0
for term in l:
if term in prefixes:
idx += 1
continue
else:
s = " ".join(l)
while True:
to_break = True
for prefix in p:
if s.startswith(prefix):
s = s[len(prefix):].strip()
to_break = False
break
if to_break:
break

return s.strip()

@staticmethod
def _trim_suffix(s: str, suffixes: Set[str]):
suffixes = [term[0] for term in
sorted([(suffix, len(suffix)) for suffix in suffixes], key=lambda x: x[1], reverse=True)]
l = [term.strip() for term in s.split()]
s = " ".join(l)
while True:
to_break = True
for suffix in suffixes:
if s.endswith(suffix):
s = s[:-1*len(suffix)].strip()
to_break = False
break
if to_break:
break

return " ".join(l[idx:])
return s.strip()

def parse_element(self, element : et.Element, param: dict) -> str:
# print ("++++>", element)
Expand Down Expand Up @@ -86,9 +121,23 @@ def parse_element(self, element : et.Element, param: dict) -> str:
else:
return "WHERE " + ' '.join(l[idx:])
elif element.tag == "trim":
prefix = element.attrib['prefix']
prefix_overrides_set = set()
[prefix_overrides_set.add(term.strip()) for term in element.attrib['prefixOverrides'].split("|")]
prefix = ""
if 'prefix' in element.attrib:
prefix = element.attrib['prefix']

suffix = ""
if 'suffix' in element.attrib:
suffix = element.attrib['suffix']

if 'prefixOverrides' in element.attrib:
prefix_overrides_set = set([term.strip() for term in element.attrib['prefixOverrides'].split("|")])
else:
prefix_overrides_set = set()

if 'suffixOverrides' in element.attrib:
suffix_overrides_set = set([term.strip() for term in element.attrib['suffixOverrides'].split("|")])
else:
suffix_overrides_set = set()

ret = ""
if element.text is not None:
Expand All @@ -97,8 +146,13 @@ def parse_element(self, element : et.Element, param: dict) -> str:
ret += self.parse_element(child, param)
ret += child.tail

ret = MapperManager._trim_prefix(ret, prefix_overrides_set)
return prefix + " " + ret
if len(prefix_overrides_set) > 0:
ret = MapperManager._trim_prefix(ret, prefix_overrides_set)

if len(suffix_overrides_set) > 0:
ret = MapperManager._trim_suffix(ret, suffix_overrides_set)

return prefix + " " + ret + " " + suffix

elif element.tag == "set":
prefix_overrides_set = set()
Expand Down
11 changes: 11 additions & 0 deletions test/test_mapper_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ def test_trim():
sql, param_list = mm.select("testTrim", {'names': [1, 2, 3, 4]})
assert sql == "SELECT name, category, price FROM fruits WHERE category = 'apple' OR price = 200 AND (type = 1 OR type= 0)"

def test_trim2():
mm = MapperManager()
mm.read_mapper_xml_file("mapper/test.xml")

sql, param_list = mm.insert("testInsertSelective", {'name': 'Candy', 'category': "C", 'price': 500})
assert sql == "insert into fruits ( name, category, price ) values ( ?, ?, ? )"
assert len(param_list) == 3
assert param_list[0] == "Candy"
assert param_list[1] == 'C'
assert param_list[2] == 500

def test_set():
mm = MapperManager()
mm.read_mapper_xml_file("mapper/test.xml")
Expand Down

0 comments on commit 1dab66c

Please sign in to comment.