db.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 ${
  55. Object.keys(queryObject)
  56. .map((queryKey) => `${queryKey} = :${queryKey}`)
  57. .join(" AND ")
  58. } ORDER BY updated DESC ${limit ? ` LIMIT ${limit}` : ""}`,
  59. );
  60. try {
  61. return findQuery.all(queryObject);
  62. } catch (e) {
  63. console.error("Find error:", e);
  64. return [];
  65. } finally {
  66. findQuery.finalize();
  67. db.close();
  68. }
  69. }
  70. export function insert(
  71. tableName: string,
  72. userInsertObject: { [key: string]: string | number | boolean },
  73. ) {
  74. const db = prepareDB(tableName);
  75. const insertObject = {
  76. ...userInsertObject,
  77. updated: new Date().toISOString().slice(0, 19).replace("T", " "),
  78. };
  79. const insertQuery = db.prepareQuery(
  80. `INSERT INTO ${tableName.toLowerCase()} (${
  81. Object.keys(insertObject).join(
  82. ", ",
  83. )
  84. }) VALUES (${
  85. Object.keys(insertObject)
  86. .map((key) => `:${key}`)
  87. .join(", ")
  88. })`,
  89. );
  90. try {
  91. insertQuery.all(insertObject);
  92. return find(tableName, userInsertObject, ["id"], 1);
  93. } catch (e) {
  94. console.error("Insert error:", e);
  95. return [];
  96. } finally {
  97. insertQuery.finalize();
  98. db.close();
  99. }
  100. }
  101. export function update(
  102. tableName: string,
  103. id: number | string,
  104. userUpdateObject: { [key: string]: string | number | boolean },
  105. ) {
  106. const db = prepareDB(tableName);
  107. const updateObject = {
  108. ...userUpdateObject,
  109. updated: new Date().toISOString().slice(0, 19).replace("T", " "),
  110. };
  111. const updateQuery = db.prepareQuery(
  112. `UPDATE ${tableName.toLowerCase()} SET ${
  113. Object.keys(updateObject)
  114. .map((updateKey) => `${updateKey} = :${updateKey}`)
  115. .join(", ")
  116. } WHERE id = :id`,
  117. );
  118. try {
  119. updateQuery.all({ ...updateObject, id });
  120. return find(tableName, userUpdateObject, ["id"], 1);
  121. } catch (e) {
  122. console.error("Insert error:", e);
  123. return [];
  124. } finally {
  125. updateQuery.finalize();
  126. db.close();
  127. }
  128. }
  129. export function del(
  130. tableName: string,
  131. queryObject: { [key: string]: string | number | boolean },
  132. ) {
  133. const db = prepareDB(tableName);
  134. const deleteQuery = db.prepareQuery(
  135. `DELETE FROM ${tableName.toLowerCase()} WHERE ${
  136. Object.keys(queryObject)
  137. .map((queryKey) => `${queryKey} = :${queryKey}`)
  138. .join(" AND ")
  139. }`,
  140. );
  141. try {
  142. deleteQuery.all(queryObject);
  143. return true;
  144. } catch (e) {
  145. console.error("Delete error:", e);
  146. return false;
  147. } finally {
  148. deleteQuery.finalize();
  149. db.close();
  150. }
  151. }