db.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import { DB } from "$sqlite/mod.ts";
  2. function prepareDB(tableName: string) {
  3. const db = new DB("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 = { ...userInsertObject, updated: new Date() };
  74. const insertQuery = db.prepareQuery(
  75. `INSERT INTO ${tableName.toLowerCase()} (${Object.keys(insertObject).join(
  76. ", "
  77. )}) VALUES (${Object.keys(insertObject)
  78. .map((key) => `:${key}`)
  79. .join(", ")})`
  80. );
  81. try {
  82. insertQuery.all(insertObject);
  83. return find(tableName, userInsertObject, ["id"], 1);
  84. } catch (e) {
  85. console.error("Insert error:", e);
  86. return [];
  87. } finally {
  88. insertQuery.finalize();
  89. db.close();
  90. }
  91. }
  92. export function update(
  93. tableName: string,
  94. id: number | string,
  95. userUpdateObject: { [key: string]: string | number | boolean }
  96. ) {
  97. const db = prepareDB(tableName);
  98. const updateObject = { ...userUpdateObject, updated: new Date() };
  99. const updateQuery = db.prepareQuery(
  100. `UPDATE ${tableName.toLowerCase()} SET ${Object.keys(updateObject)
  101. .map((updateKey) => `${updateKey} = :${updateKey}`)
  102. .join(", ")} WHERE id = :id`
  103. );
  104. try {
  105. updateQuery.all({ ...updateObject, id });
  106. return find(tableName, userUpdateObject, ["id"], 1);
  107. } catch (e) {
  108. console.error("Insert error:", e);
  109. return [];
  110. } finally {
  111. updateQuery.finalize();
  112. db.close();
  113. }
  114. }
  115. export function del(
  116. tableName: string,
  117. queryObject: { [key: string]: string | number | boolean }
  118. ) {
  119. const db = prepareDB(tableName);
  120. const deleteQuery = db.prepareQuery(
  121. `DELETE FROM ${tableName.toLowerCase()} WHERE ${Object.keys(queryObject)
  122. .map((queryKey) => `${queryKey} = :${queryKey}`)
  123. .join(" AND ")}`
  124. );
  125. try {
  126. return deleteQuery.all(queryObject);
  127. } catch (e) {
  128. console.error("Insert error:", e);
  129. return [];
  130. } finally {
  131. deleteQuery.finalize();
  132. db.close();
  133. }
  134. }