sqlite3.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. # -*- encoding: utf-8 -*-
  3. # Author: MoeClub.org
  4. import aiosqlite
  5. import asyncio
  6. class SQLite3:
  7. def __init__(self, name, table):
  8. aiosqlite.core.LOG.disabled = True
  9. self.table = table
  10. self._path = os.path.join(os.path.dirname(os.path.abspath(__file__)), name)
  11. self._queue = asyncio.Queue(maxsize=1)
  12. self._queueInit(queue=self._queue)
  13. print("Data:", self._path)
  14. def _queueInit(self, queue):
  15. try:
  16. assert queue.maxsize > 0
  17. for _ in range(queue.maxsize):
  18. queue.put_nowait(None)
  19. except:
  20. pass
  21. async def execute(self, sql, write=False):
  22. value = db = cursor = field = None
  23. try:
  24. if write is True:
  25. await self._queue.get()
  26. db = await aiosqlite.connect(database=self._path, check_same_thread=False, timeout=60)
  27. cursor = await db.execute(sql)
  28. await db.commit()
  29. else:
  30. db = await aiosqlite.connect(database=self._path, check_same_thread=False, timeout=60)
  31. cursor = await db.execute(sql)
  32. if cursor.description:
  33. field = [i[0] for i in cursor.description]
  34. records = await cursor.fetchall()
  35. if field:
  36. value = [dict(zip(field, i)) for i in records]
  37. except Exception as e:
  38. raise Exception(e)
  39. finally:
  40. if cursor is not None:
  41. await cursor.close()
  42. if db is not None:
  43. await db.close()
  44. if write is True:
  45. await self._queue.put(None)
  46. return value
  47. async def Init(self, tbl='(row0 text primary key, row1 text, row2 text)'):
  48. try:
  49. vacuum = await self.execute('''PRAGMA auto_vacuum;''')
  50. if vacuum[0]['auto_vacuum'] == 0:
  51. await self.execute('''PRAGMA auto_vacuum = 1;''', True)
  52. await self.execute('''PRAGMA encoding = "UTF-8";''', True)
  53. await self.execute('''PRAGMA journal_mode = WAL;''', True)
  54. await self.execute('''PRAGMA temp_store = MEMORY;''', True)
  55. await self.execute('''PRAGMA synchronous = NORMAL;''', True)
  56. await self.execute('''PRAGMA page_size = 4096;''', True)
  57. create_tbl = '''create table %s %s''' % (self.table, tbl)
  58. await self.execute(create_tbl, True)
  59. except Exception as e:
  60. if 'already exists' not in str(e):
  61. print("init:", e)
  62. if __name__ == "__main__":
  63. SQL = SQLite3("MoeClub.db", "MoeClub")
  64. loop = asyncio.get_event_loop()
  65. loop.run_until_complete(SQL.Init())
  66. asyncio.run(SQL.execute("select * from MoeClub;"))