Skip to content

Commit

Permalink
Release 0.0.9: add decorator.
Browse files Browse the repository at this point in the history
  • Loading branch information
ralgond committed Dec 6, 2024
1 parent 8e96b29 commit 42b56a9
Show file tree
Hide file tree
Showing 5 changed files with 411 additions and 2 deletions.
45 changes: 45 additions & 0 deletions example_decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import mysql.connector
from mybatis import Mybatis

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)

@mb.SelectOne("SELECT * FROM fruits WHERE id=#{id}")
def get_one(id:int):
pass

@mb.SelectMany("SELECT * FROM fruits")
def get_many():
pass

@mb.Insert("INSERT INTO fruits (name, category, price) VALUES (#{name}, #{category}, #{price})")
def insert():
pass

@mb.Delete("DELETE FROM fruits WHERE id=#{id}")
def delete(id:int):
pass

@mb.Update("UPDATE fruits SET name='Amazon' WHERE id=#{id}")
def update(id:int):
pass

print(get_one(id=1))

print(delete(id=4))

print(get_many())

print(insert(name="Dating", category="D", price=20))

print(get_many())

print(update(id=1))

print(get_many())
139 changes: 139 additions & 0 deletions mybatis/mybatis.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,12 @@ def select_many(self, id:str, params:dict) -> Optional[List[Dict]]:
d[item] = row[idx]
res_list.append(d)

if len(res_list) == 0:
res_list = None

if self.cache is not None:
self.cache.put(CacheKey(sql, param_list), res_list)

return res_list

def update(self, id:str, params:dict) -> int:
Expand Down Expand Up @@ -112,3 +116,138 @@ def insert(self, id:str, params:dict) -> int:
self.conn.commit()
last_id = cursor.lastrowid
return last_id


def SelectOne(self, unparsed_sql:str) -> Optional[Dict]:
def decorator(func):
def wrapper(*args, **kwargs):
params = {}
for key, value in kwargs.items():
params[key] = value

sql, param_list = self.mapper_manager._to_prepared_statement(unparsed_sql, params)
sql = self.mapper_manager._to_replace(sql, params)

if self.cache is not None:
res = self.cache.get(CacheKey(sql, param_list))
if res is not None:
return res

with self.conn.cursor(prepared=True) as cursor:
cursor.execute(sql, param_list)
ret = cursor.fetchone()
if ret is None:
return None

column_name = [item[0] for item in cursor.description]
res = {}
for idx, item in enumerate(column_name):
res[item] = ret[idx]

if self.cache is not None:
self.cache.put(CacheKey(sql, param_list), res)

return res

return wrapper
return decorator

def SelectMany(self, unparsed_sql:str) -> Optional[List[Dict]]:
def decorator(func):
def wrapper(*args, **kwargs):
params = {}
for key, value in kwargs.items():
params[key] = value

sql, param_list = self.mapper_manager._to_prepared_statement(unparsed_sql, params)
sql = self.mapper_manager._to_replace(sql, params)

if self.cache is not None:
res = self.cache.get(CacheKey(sql, param_list))
if res is not None:
return res

with self.conn.cursor(prepared=True) as cursor:
cursor.execute(sql, param_list)

res_list = []
column_name = [item[0] for item in cursor.description]

ret = cursor.fetchall()
for row in ret:
d = {}
for idx, item in enumerate(column_name):
d[item] = row[idx]
res_list.append(d)

if len(res_list) == 0:
res_list = None

if self.cache is not None:
self.cache.put(CacheKey(sql, param_list), res_list)

return res_list
return wrapper
return decorator

def Insert(self, unparsed_sql:str) -> int:
def decorator(func):
def wrapper(*args, **kwargs):
params = {}
for key, value in kwargs.items():
params[key] = value

sql, param_list = self.mapper_manager._to_prepared_statement(unparsed_sql, params)
sql = self.mapper_manager._to_replace(sql, params)

res = self.cache.clear()

with self.conn.cursor(prepared=True) as cursor:
cursor.execute(sql, param_list)
self.conn.commit()
last_id = cursor.lastrowid
return last_id
return wrapper
return decorator

def Delete(self, unparsed_sql:str) -> int:
def decorator(func):
def wrapper(*args, **kwargs):
params = {}
for key, value in kwargs.items():
params[key] = value

sql, param_list = self.mapper_manager._to_prepared_statement(unparsed_sql, params)
sql = self.mapper_manager._to_replace(sql, params)

res = self.cache.clear()

with self.conn.cursor(prepared=True) as cursor:
cursor.execute(sql, param_list)
affected_rows = cursor.rowcount
self.conn.commit()
return affected_rows
return wrapper
return decorator

def Update(self, unparsed_sql:str) -> int:
def decorator(func):
def wrapper(*args, **kwargs):
params = {}
for key, value in kwargs.items():
params[key] = value

sql, param_list = self.mapper_manager._to_prepared_statement(unparsed_sql, params)
sql = self.mapper_manager._to_replace(sql, params)

res = self.cache.clear()

with self.conn.cursor(prepared=True) as cursor:
cursor.execute(sql, param_list)
affected_rows = cursor.rowcount
self.conn.commit()
return affected_rows

return wrapper

return decorator
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='mybatis',
version='0.0.8',
version='0.0.9',
description='A python ORM like mybatis.',
long_description=open('README.md').read(),
long_description_content_type='text/markdown', # 如果你使用的是Markdown格式的README
Expand Down
2 changes: 1 addition & 1 deletion test/test_mybatis.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def test_select_many(db_connection):
def test_select_many_none(db_connection):
mb = Mybatis(db_connection, "mapper")
ret = mb.select_many('testBasicNone', {})
assert len(ret) == 0
assert ret is None

def test_update(db_connection):
mb = Mybatis(db_connection, "mapper")
Expand Down
Loading

0 comments on commit 42b56a9

Please sign in to comment.