1
0

db_model.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import json
  2. import sqlite3
  3. DB_PATH = '.data/youtube.db'
  4. def init_db ( path = DB_PATH ):
  5. db = sqlite3.connect(path)
  6. cur = db.cursor()
  7. table_exists = cur.execute(f"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='youtube_videos'").fetchone()[0]
  8. if not table_exists:
  9. print(f'creating DB {path}')
  10. cur.execute("""
  11. create table youtube_videos (
  12. id text,
  13. ts timestamp default current_timestamp,
  14. auth_user_id text,
  15. data blob
  16. )
  17. """)
  18. cur.connection.commit()
  19. cur.close()
  20. def store_video_infos (vid_infos, auth_user_id=None, db_path=DB_PATH):
  21. db = sqlite3.connect(db_path)
  22. cur = db.cursor()
  23. for vid_info in vid_infos:
  24. video_id = vid_info['id']
  25. cur.execute("""
  26. INSERT INTO youtube_videos (id, auth_user_id, data) VALUES(?,?,?)
  27. """, [video_id, auth_user_id, json.dumps(vid_info, indent=2)])
  28. cur.connection.commit()
  29. cur.close()
  30. def load_video_infos (video_ids, auth_user_id=None, db_path=DB_PATH):
  31. db = sqlite3.connect(db_path)
  32. cur = db.cursor()
  33. params = [auth_user_id] + video_ids
  34. values_sql = ','.join(['?'] * (len(video_ids)))
  35. yt_video_rows = cur.execute(f"""
  36. SELECT data
  37. FROM youtube_videos
  38. WHERE
  39. (auth_user_id = ? or auth_user_id is null)
  40. and id IN ({values_sql})
  41. """, params).fetchall()
  42. cur.close()
  43. vid_infos = list(map(lambda row: json.loads(row[0]), yt_video_rows))
  44. return vid_infos