db.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import { DB } from "$sqlite/mod.ts";
  2. function prepareDB(tableName: string) {
  3. const db = new DB("data/postdown.db");
  4. switch (tableName) {
  5. case "User":
  6. db.execute(`
  7. CREATE TABLE IF NOT EXISTS user (
  8. id INTEGER PRIMARY KEY AUTOINCREMENT,
  9. name VARCHAR(128),
  10. email VARCHAR(128),
  11. password TEXT,
  12. created DATETIME DEFAULT CURRENT_TIMESTAMP,
  13. updated DATETIME,
  14. UNIQUE(name)
  15. )
  16. `);
  17. break;
  18. case "Token":
  19. db.execute(`
  20. CREATE TABLE IF NOT EXISTS token (
  21. id INTEGER PRIMARY KEY AUTOINCREMENT,
  22. user_id INTEGER,
  23. token VARCHAR(128),
  24. created DATETIME DEFAULT CURRENT_TIMESTAMP,
  25. updated DATETIME
  26. )
  27. `);
  28. break;
  29. case "Post":
  30. db.execute(`
  31. CREATE TABLE IF NOT EXISTS post (
  32. id VARCHAR(64) PRIMARY KEY,
  33. user_id INTEGER,
  34. title VARCHAR(256),
  35. content TEXT,
  36. shared BOOLEAN,
  37. created DATETIME DEFAULT CURRENT_TIMESTAMP,
  38. updated DATETIME
  39. )
  40. `);
  41. }
  42. return db;
  43. }
  44. export function find(
  45. tableName: string,
  46. queryObject: { [key: string]: string | number | boolean },
  47. targetKeys: string[] = [],
  48. limit?: number
  49. ) {
  50. const db = prepareDB(tableName);
  51. const findQuery = db.prepareQuery(
  52. `SELECT ${
  53. targetKeys.length > 0 ? targetKeys.join(", ") : "*"
  54. } FROM ${tableName.toLowerCase()} WHERE ${Object.keys(queryObject)
  55. .map((queryKey) => `${queryKey} = :${queryKey}`)
  56. .join(" AND ")} ORDER BY updated DESC ${limit ? ` LIMIT ${limit}` : ""}`
  57. );
  58. try {
  59. return findQuery.all(queryObject);
  60. } catch (e) {
  61. console.error("Find error:", e);
  62. return [];
  63. } finally {
  64. findQuery.finalize();
  65. db.close();
  66. }
  67. }
  68. export function insert(
  69. tableName: string,
  70. userInsertObject: { [key: string]: string | number | boolean }
  71. ) {
  72. const db = prepareDB(tableName);
  73. const insertObject = {
  74. ...userInsertObject,
  75. updated: new Date().toISOString().slice(0, 19).replace("T", " "),
  76. };
  77. const insertQuery = db.prepareQuery(
  78. `INSERT INTO ${tableName.toLowerCase()} (${Object.keys(insertObject).join(
  79. ", "
  80. )}) VALUES (${Object.keys(insertObject)
  81. .map((key) => `:${key}`)
  82. .join(", ")})`
  83. );
  84. try {
  85. insertQuery.all(insertObject);
  86. return find(tableName, userInsertObject, ["id"], 1);
  87. } catch (e) {
  88. console.error("Insert error:", e);
  89. return [];
  90. } finally {
  91. insertQuery.finalize();
  92. db.close();
  93. }
  94. }
  95. export function update(
  96. tableName: string,
  97. id: number | string,
  98. userUpdateObject: { [key: string]: string | number | boolean }
  99. ) {
  100. const db = prepareDB(tableName);
  101. const updateObject = {
  102. ...userUpdateObject,
  103. updated: new Date().toISOString().slice(0, 19).replace("T", " "),
  104. };
  105. const updateQuery = db.prepareQuery(
  106. `UPDATE ${tableName.toLowerCase()} SET ${Object.keys(updateObject)
  107. .map((updateKey) => `${updateKey} = :${updateKey}`)
  108. .join(", ")} WHERE id = :id`
  109. );
  110. try {
  111. updateQuery.all({ ...updateObject, id });
  112. return find(tableName, userUpdateObject, ["id"], 1);
  113. } catch (e) {
  114. console.error("Insert error:", e);
  115. return [];
  116. } finally {
  117. updateQuery.finalize();
  118. db.close();
  119. }
  120. }
  121. export function del(
  122. tableName: string,
  123. queryObject: { [key: string]: string | number | boolean }
  124. ) {
  125. const db = prepareDB(tableName);
  126. const deleteQuery = db.prepareQuery(
  127. `DELETE FROM ${tableName.toLowerCase()} WHERE ${Object.keys(queryObject)
  128. .map((queryKey) => `${queryKey} = :${queryKey}`)
  129. .join(" AND ")}`
  130. );
  131. try {
  132. deleteQuery.all(queryObject);
  133. return true;
  134. } catch (e) {
  135. console.error("Delete error:", e);
  136. return false;
  137. } finally {
  138. deleteQuery.finalize();
  139. db.close();
  140. }
  141. }