20241223103044_visits_user_id.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @param { import("knex").Knex } knex
  3. * @returns { Promise<void> }
  4. */
  5. async function up(knex) {
  6. const hasUserIDColumn = await knex.schema.hasColumn("visits", "user_id");
  7. if (hasUserIDColumn) return;
  8. await knex.schema.alterTable("visits", function(table) {
  9. table
  10. .integer("user_id")
  11. .unsigned();
  12. table
  13. .foreign("user_id")
  14. .references("id")
  15. .inTable("users")
  16. .onDelete("CASCADE")
  17. .withKeyName("visits_user_id_foreign");
  18. });
  19. const [{ count }] = await knex("visits").count("* as count");
  20. if (count < 1_000_000) {
  21. const last_visit = await knex("visits").orderBy("id", "desc").first();
  22. const size = 100_000;
  23. const loops = Math.floor(last_visit.id / size) + 1;
  24. await Promise.all(
  25. new Array(loops).fill(null).map((_, i) => {
  26. return knex("visits")
  27. .fromRaw(knex.raw("visits v"))
  28. .update({ user_id: knex.ref("links.user_id") })
  29. .updateFrom("links")
  30. .where("links.id", knex.ref("link_id"))
  31. .andWhereBetween("v.id", [i * size, (i * size) + size]);
  32. })
  33. );
  34. } else {
  35. console.warn(
  36. "MIGRATION WARN:" +
  37. "Skipped adding user_id to visits due to high volume of visits and the potential risk of locking the database.\n" +
  38. "Please refer to Kutt's migration guide for more information."
  39. );
  40. }
  41. };
  42. /**
  43. * @param { import("knex").Knex } knex
  44. * @returns { Promise<void> }
  45. */
  46. async function down(knex) {};
  47. module.exports = {
  48. up,
  49. down,
  50. }