introduce SafeIntegerField to avoid overflow

This commit is contained in:
JerryXiao 2019-11-07 14:32:10 +08:00
parent 6ed39d984f
commit 71a2d4fdf3
Signed by: Jerry
GPG key ID: 9D9CE43650FF2BAA

37
data.py
View file

@ -2,18 +2,41 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from peewee import * from peewee import *
SQLITE_MAX_INT: int = 2**63 -1
SQLITE_MIN_INT: int = -2**63
SQLITE_MAX_INT = int(SQLITE_MAX_INT/2)
SQLITE_MIN_INT = int(SQLITE_MIN_INT/2)
db = SqliteDatabase('tgmsbot.db', pragmas={ db = SqliteDatabase('tgmsbot.db', pragmas={
'journal_mode': 'wal', 'journal_mode': 'wal',
'cache_size': -32 * 1000}) 'cache_size': -32 * 1000})
class SafeIntegerField(IntegerField):
field_type = 'INT'
def adapt(self, value):
try:
ivalue = int(value)
if ivalue > SQLITE_MAX_INT:
rvalue = SQLITE_MAX_INT
elif ivalue < SQLITE_MIN_INT:
rvalue = SQLITE_MIN_INT
else:
rvalue = value
return rvalue
except ValueError:
return value
class Player(Model): class Player(Model):
user_id = IntegerField(unique=True, primary_key=True) user_id = SafeIntegerField(unique=True, primary_key=True)
mines = IntegerField() mines = SafeIntegerField()
death = IntegerField() death = SafeIntegerField()
wins = IntegerField() wins = SafeIntegerField()
restricted_until = IntegerField() restricted_until = SafeIntegerField()
immunity_cards = IntegerField() immunity_cards = SafeIntegerField()
permission = IntegerField() permission = SafeIntegerField()
class Meta: class Meta:
database = db database = db