utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import sqlite3
  2. def migrate_db(conn, cursor):
  3. cursor.execute(
  4. """
  5. CREATE TABLE IF NOT EXISTS messages (
  6. message TEXT,
  7. user TEXT,
  8. channel TEXT,
  9. timestamp TEXT,
  10. UNIQUE(channel, timestamp) ON CONFLICT REPLACE
  11. )
  12. """
  13. )
  14. cursor.execute(
  15. """
  16. CREATE TABLE IF NOT EXISTS users (
  17. name TEXT,
  18. id TEXT,
  19. avatar TEXT,
  20. UNIQUE(id) ON CONFLICT REPLACE
  21. )"""
  22. )
  23. cursor.execute(
  24. """
  25. CREATE TABLE IF NOT EXISTS channels (
  26. name TEXT,
  27. id TEXT,
  28. is_private BOOLEAN NOT NULL CHECK (is_private IN (0,1)),
  29. UNIQUE(id) ON CONFLICT REPLACE
  30. )"""
  31. )
  32. cursor.execute(
  33. """
  34. CREATE TABLE IF NOT EXISTS members (
  35. channel TEXT,
  36. user TEXT,
  37. FOREIGN KEY (channel) REFERENCES channels(id),
  38. FOREIGN KEY (user) REFERENCES users(id)
  39. )
  40. """
  41. )
  42. conn.commit()
  43. # Add `is_private` to channels for dbs that existed in v0.1
  44. try:
  45. cursor.execute(
  46. """
  47. ALTER TABLE channels
  48. ADD COLUMN is_private BOOLEAN default 1
  49. NOT NULL CHECK (is_private IN (0,1))
  50. """
  51. )
  52. conn.commit()
  53. except:
  54. pass
  55. def db_connect(database_path):
  56. conn = sqlite3.connect(database_path)
  57. cursor = conn.cursor()
  58. return conn, cursor