db_utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #
  2. # Copyright (c) Daniel Sheffield 2021 - 2022
  3. #
  4. # All rights reserved
  5. #
  6. # THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
  7. from sqlite3 import Cursor
  8. import time
  9. from typing import Any, Callable
  10. from .txn_view import (
  11. get_table_statement,
  12. get_transactions_statement,
  13. get_session_transactions_statement,
  14. )
  15. from .price_view import(
  16. get_historic_prices_statement,
  17. )
  18. from dateutil.parser import parse as parse_time
  19. import pandas as pd
  20. NON_IDENTIFIER_COLUMNS = [
  21. 'ts',
  22. 'store',
  23. 'quantity',
  24. 'unit',
  25. 'price',
  26. 'organic',
  27. ]
  28. display_map = {
  29. 'ts': lambda x: f"{time.strftime('%Y-%m-%d %H:%M', (x.year, x.month, x.day, x.hour, x.minute, 0, 0, 0, 0))}",
  30. 'price': lambda x: f'{x:.4f}',
  31. 'quantity': lambda x: f'{x:.2f}',
  32. 'organic': lambda x: 'yes' if x else 'no',
  33. }
  34. display_mapper: Callable[
  35. [Any, str], str
  36. ] = lambda data, name: display_map[name](data) if name in display_map else data
  37. def cursor_as_dict(cur):
  38. _col_idx_map=dict(map(lambda col: (col[1].name, col[0]), enumerate(cur.description)))
  39. for row in map(lambda row, _map=_col_idx_map: dict([
  40. (name, row[i]) for name, i in _map.items()
  41. ]), cur.fetchall()):
  42. #print(row)
  43. yield row
  44. def get_data(cursor, statement, display):
  45. cursor.execute(statement)
  46. yield from map(lambda x: dict([
  47. (k, display(v, k)) for k,v in x.items()
  48. ]), cursor_as_dict(cursor))
  49. def get_session_transactions(cursor, statement, date, store):
  50. #print(cur.mogrify(statement).decode("utf-8"))
  51. #input()
  52. cursor.execute(statement)
  53. df = pd.DataFrame(cursor_as_dict(cursor))
  54. if df.empty:
  55. return ''
  56. return df.drop(labels=[
  57. 'id', 'ts', 'store', 'code',
  58. ], axis=1).to_string(header=[
  59. 'Description', 'Volume', 'Unit', 'Price', '$/unit', 'Total',
  60. 'Group', 'Category', 'Product', 'Organic',
  61. ], justify='justify-all', max_colwidth=60, index=False)
  62. def record_matches(record, strict=None, **kwargs):
  63. strict = strict or []
  64. for k,v in kwargs.items():
  65. if not v:
  66. continue
  67. if k in strict and v.lower() != record[k].lower():
  68. return False
  69. if v.lower() not in record[k].lower():
  70. return False
  71. return True
  72. def unique_suggestions(cur, statement, name, display, exclude=NON_IDENTIFIER_COLUMNS, **kwargs):
  73. exclude = filter(
  74. lambda x: x != name or name == 'ts',
  75. exclude,
  76. )
  77. [ kwargs.pop(k) for k in exclude if k in kwargs]
  78. items = suggestions(cur, statement, name, display, exclude=exclude, **kwargs)
  79. ret = sorted(set(map(lambda x: x[name], items)))
  80. tables = {
  81. 'product',
  82. 'category',
  83. 'group',
  84. 'unit',
  85. 'store',
  86. }
  87. if len(ret) > 0 or name not in tables:
  88. return ret
  89. items = (i for i in filter(lambda x: record_matches(x, **{ name: kwargs[name] }),
  90. get_data(cur, get_table_statement(name), display)))
  91. return sorted(set(map(lambda x: x[name], items)))
  92. def suggestions(cur, statement, name, display, exclude=NON_IDENTIFIER_COLUMNS, **kwargs):
  93. exclude = filter(
  94. lambda x: x != name or name == 'ts',
  95. exclude,
  96. )
  97. [ kwargs.pop(k) for k in exclude if k in kwargs]
  98. yield from filter(lambda x: record_matches(
  99. x, strict=[ k for k in kwargs if k != name ], **kwargs
  100. ), get_data(cur, statement, display))
  101. def get_insert_product_statement(product, category, group):
  102. return f'CALL insert_product($prod${product}$prod$, $category${category}$category$, $group${group}$group$)'
  103. class QueryManager(object):
  104. def __init__(self, cursor: Cursor, display: Callable[
  105. [Any, str], str
  106. ]):
  107. self.display = display
  108. self.cursor = cursor
  109. def get_historic_prices(self, rating_cb, sort, product, unit, organic=None, limit='365 days'):
  110. statement = get_historic_prices_statement(sort, product, unit, organic=organic, limit=limit)
  111. #print(self.cursor.mogrify(statement).decode('utf-8'))
  112. #input()
  113. df = pd.DataFrame(get_data(self.cursor, statement, self.display))
  114. if df.empty:
  115. rating_cb(None, None, None)
  116. return ''
  117. _avg, _min, _max = [ x for x in df[['avg','min','max']].iloc[0].apply(float) ]
  118. rating_cb(_avg, _min, _max)
  119. return df.drop(labels=[
  120. 'id', 'avg', 'min', 'max'
  121. ], axis=1).to_string(header=[
  122. 'Date', 'Store', '$/unit', 'Org',
  123. ], justify='justify-all', max_colwidth=16, index=False)
  124. def get_session_transactions(self, date, store):
  125. return get_session_transactions(
  126. self.cursor, get_session_transactions_statement(
  127. parse_time(date), store, full_name=True, exact_time=True
  128. ), date, store)
  129. def unique_suggestions(self, name, **kwargs):
  130. statement = get_transactions_statement()
  131. return unique_suggestions(self.cursor, statement, name, self.display, **kwargs)
  132. def insert_new_product(self, product, category, group):
  133. self.cursor.execute(get_insert_product_statement(product, category, group))