224 lines
6.3 KiB
Python
224 lines
6.3 KiB
Python
import sqlite3
|
|
|
|
import UtilPack as util
|
|
import MgrSQLiteDB as MyDB
|
|
|
|
class MgrCalibreDB(MyDB.MgrSQLiteDB):
|
|
def __init__(self, path: str):
|
|
super().__init__(path)
|
|
self.init()
|
|
|
|
def init(self):
|
|
# 데이터베이스 연결 (파일이 없으면 새로 생성됨)
|
|
self.conn = sqlite3.connect(self.path)
|
|
self.conn.create_function("title_sort", 1, self._title_sort )
|
|
self.cursor = self.conn.cursor()
|
|
|
|
#
|
|
def _title_sort(self, value):
|
|
return 0
|
|
|
|
|
|
# 테이블의 마지막 인덱스를 가져온다. 잘못되면 -1
|
|
def GetLastIndexID(self, strTableName: str) -> int :
|
|
if True == util.IsEmptyStr(strTableName):
|
|
return -1
|
|
|
|
strSQL = f"SELECT MAX(id) FROM \'{strTableName}\';"
|
|
listMaxID = self.SQLExecute_Get(self.cursor, strSQL)
|
|
if listMaxID is None or 0 >= len(listMaxID):
|
|
util.DbgOut("Error : Invalid Table Name")
|
|
return -1
|
|
|
|
return listMaxID[0][0] + 1
|
|
|
|
#
|
|
def GetBookTitleByID(self, nID: int) -> str:
|
|
if 0 >= nID:
|
|
return ""
|
|
|
|
listRet = self.GetValuesOneCondition("books", "title", "id", str(nID))
|
|
if 0 >= len(listRet):
|
|
return ""
|
|
|
|
return listRet[0]
|
|
|
|
|
|
#
|
|
def GetAuthorByID(self, nID: int ) -> str:
|
|
if 0 >= nID:
|
|
return ""
|
|
|
|
listRet = self.GetValuesOneCondition("authors", "name", "id", f"{nID}")
|
|
if 0 >= len(listRet):
|
|
return ""
|
|
|
|
return listRet[0]
|
|
|
|
|
|
#
|
|
def GetAuthorsByBookID(self, nID: int ) -> list[str]:
|
|
if 0 >= nID:
|
|
return []
|
|
|
|
listAuthorID = self.GetValuesOneCondition("books_authors_link", "author", "book", f"{nID}")
|
|
print(f"GetAuthorsByBookID : {listAuthorID}")
|
|
|
|
if 0 >= len(listAuthorID):
|
|
return []
|
|
|
|
listRet = list[str]()
|
|
for strAuthorID in listAuthorID:
|
|
if True == util.IsEmptyStr(strAuthorID):
|
|
continue
|
|
|
|
nAuthorID = int(strAuthorID)
|
|
strAuthorName = self.GetAuthorByID(nAuthorID)
|
|
if True == util.IsEmptyStr(strAuthorName):
|
|
continue
|
|
|
|
listRet.append(strAuthorName)
|
|
|
|
return listRet
|
|
|
|
#
|
|
def GetDataByBookID(self, nID: int ) -> tuple[str, int, str]:
|
|
if 0 >= nID:
|
|
return ("", 0, "")
|
|
|
|
strSQL = f"SELECT format, uncompressed_size, name FROM data WHERE book = {nID};"
|
|
listRet = self.SQLExecute_Get(self.cursor, strSQL)
|
|
if listRet is None or 0 >= len(listRet):
|
|
return ("", 0, "")
|
|
|
|
return listRet[0]
|
|
|
|
#
|
|
def GetTagByID(self, strTag: str) -> int:
|
|
if True == util.IsEmptyStr(strTag):
|
|
return -1
|
|
|
|
listRet = self.GetValuesOneCondition("tags", "id", "name", strTag)
|
|
if 0 >= len(listRet):
|
|
return -1
|
|
|
|
return int(listRet[0])
|
|
|
|
|
|
# title, author, cover, ext(path), id
|
|
# id, title, has_cover, path, And author
|
|
def GetBookListforUI_ArcList(self) -> list[tuple[str, str, str, str, str]]:
|
|
strSQL = f"Select id, title, path, has_cover from books;"
|
|
listResult = self.SQLExecute_Get(self.cursor, strSQL)
|
|
if listResult is None or 0 >= len(listResult):
|
|
return []
|
|
|
|
listRet = list[tuple[str, str, str, str, str]]()
|
|
for item in listResult:
|
|
nID = item[0]
|
|
strTitle = item[1]
|
|
strPath = item[2]
|
|
nHasCover = item[3]
|
|
|
|
if 0 >= nID:
|
|
continue
|
|
|
|
listAuthors = self.GetAuthorsByBookID(nID)
|
|
strAuthor = ", ".join(listAuthors) if listAuthors else "Unknown"
|
|
|
|
listRet.append((strTitle, strAuthor, str(nHasCover), strPath, str(nID)))
|
|
|
|
return listRet
|
|
|
|
#
|
|
def InsertAuthor(self, strAuthor: str):
|
|
if True == util.IsEmptyStr(strAuthor):
|
|
return
|
|
|
|
strTableName = "authors"
|
|
nMaxID = self.GetLastIndexID(strTableName)
|
|
if 0 >= nMaxID:
|
|
util.DbgOut("Error : Invalid Table Name")
|
|
return
|
|
|
|
strAuthorSort = strAuthor.replace(" ", ",")
|
|
strSQL = f"INSERT OR IGNORE INTO \'{strTableName}\' VALUES ({nMaxID}, \'{strAuthor}\',\'{strAuthorSort}\', \'\');"
|
|
self.SQLExecute(self.cursor, strSQL, True)
|
|
|
|
|
|
#
|
|
def InsertTag(self, strTag: str):
|
|
if True == util.IsEmptyStr(strTag):
|
|
return
|
|
|
|
strTableName = "tags"
|
|
nMaxID = self.GetLastIndexID(strTableName)
|
|
if 0 >= nMaxID:
|
|
util.DbgOut("Error : Invalid Table Name")
|
|
return
|
|
|
|
strSQL = f"INSERT OR IGNORE INTO \'{strTableName}\' VALUES ({nMaxID}, \'{strTag}\', \'\');"
|
|
self.SQLExecute(self.cursor, strSQL, True)
|
|
|
|
|
|
""" #Example usage
|
|
def main():
|
|
db = MgrCalibreDB("/Users/minarinari/캘리버 서재/metadata.db")
|
|
db.init()
|
|
|
|
#db.UpdateTableValue("books", 3, "title", "삭막")
|
|
db.InsertAuthor("Oyster")
|
|
listValues = db.GetTableAllData("authors")
|
|
print(listValues)
|
|
|
|
db.InsertTag("female:Bondage")
|
|
listValues2 = db.GetTableAllData("Tags")
|
|
print(listValues2)
|
|
|
|
# For Main Loop
|
|
if __name__ == '__main__':
|
|
main()
|
|
"""
|
|
|
|
#coments table
|
|
# 자체 id, book id, 코멘트...<- 여기다 json 을 넣자.
|
|
# id, book ,comment
|
|
|
|
# data table
|
|
# 자체 id, book id, 파일 포멧, cbz, 크기, 파일 이름
|
|
# id, book, format, uncompressed_size, name
|
|
|
|
# 테이블 생성
|
|
#cursor.execute('''CREATE TABLE IF NOT EXISTS users
|
|
# (id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
# name TEXT NOT NULL,
|
|
# age INTEGER,
|
|
# email TEXT)''')
|
|
|
|
# 데이터 삽입
|
|
#cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)",
|
|
# ("Alice", 30, "alice@example.com"))
|
|
#conn.commit()
|
|
|
|
# 데이터 조회
|
|
# cursor.execute("SELECT * FROM books")
|
|
# rows = cursor.fetchall()
|
|
# for nRow in range(0, len(rows)):
|
|
# row = rows[nRow]
|
|
# for nCol in range(0,len(row)):
|
|
# item = row[nCol]
|
|
|
|
# print(f"{nRow}:{nCol} -> {item}")
|
|
|
|
# print("\r\n")
|
|
|
|
# 데이터 업데이트
|
|
#cursor.execute("UPDATE users SET age = ? WHERE name = ?", (31, "Alice"))
|
|
#conn.commit()
|
|
|
|
# 데이터 삭제
|
|
#cursor.execute("DELETE FROM users WHERE name = ?", ("Alice",))
|
|
#conn.commit()
|
|
|
|
# 연결 닫기
|
|
#conn.close() |