1
0

sqlite3.py 3.0 KB

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