chatServer/modules/db.py

97 lines
2.2 KiB
Python

global json
import json
global dbGet
def dbGet(dbPath,table,key):
if not os.path.isfile(dbPath): return False
config = [[],[]]
with open(dbPath,"r",encoding="utf-8") as dbFile:
config = json.loads(dbFile.read())
tableIndex = -1
try:
tableIndex = config[0].index(table)
except:
return False
keyIndex = -1
try:
keyIndex = config[1][tableIndex][0].index(key)
except:
return False
return config[1][tableIndex][1][keyIndex]
global dbGetTable
def dbGetTable(dbPath,table):
if not os.path.isfile(dbPath): return False
config = [[],[]]
with open(dbPath,"r",encoding="utf-8") as dbFile:
config = json.loads(dbFile.read())
tableIndex = -1
try:
tableIndex = config[0].index(table)
except:
return False
return config[1][tableIndex]
global dbSet
def dbSet(dbPath,table,key,value):
config = [[],[]]
if os.path.isfile(dbPath):
with open(dbPath,"r",encoding="utf-8") as dbFile:
config = json.loads(dbFile.read())
elif not os.path.isdir(pUp(dbPath)): os.makedirs(pUp(dbPath))
tableIndex = -1
try:
tableIndex = config[0].index(table)
except:
pass
if tableIndex == -1:
config[0].append(table)
config[1].append([[],[]])
tableIndex = len(config[0]) - 1
keyIndex = -1
try:
keyIndex = config[1][tableIndex][0].index(key)
except:
pass
if keyIndex == -1:
config[1][tableIndex][0].append(key)
config[1][tableIndex][1].append("")
keyIndex = len(config[1][tableIndex][0]) - 1
config[1][tableIndex][1][keyIndex] = value
with open(dbPath,"w+",encoding="utf-8") as dbFile:
dbFile.write(json.dumps(config))
global dbSetTable
def dbSetTable(dbPath,table,value):
config = [[],[]]
if os.path.isfile(dbPath):
with open(dbPath,"r",encoding="utf-8") as dbFile:
config = json.loads(dbFile.read())
elif not os.path.isdir(pUp(dbPath)): os.makedirs(pUp(dbPath))
tableIndex = -1
try:
tableIndex = config[0].index(table)
except:
pass
if tableIndex == -1:
config[0].append(table)
config[1].append([[],[]])
tableIndex = len(config[0]) - 1
config[1][tableIndex] = value
with open(dbPath,"w+",encoding="utf-8") as dbFile:
dbFile.write(json.dumps(config))