Alter SQL column names to be distinct

This commit is contained in:
Cadence Ember 2023-10-05 12:32:05 +13:00
parent a49b46381c
commit 28abdac5b6
14 changed files with 40 additions and 25 deletions

View file

@ -15,7 +15,7 @@ const api = sync.require("../../matrix/api")
* @param {import("discord-api-types/v10").APIThreadChannel} thread * @param {import("discord-api-types/v10").APIThreadChannel} thread
*/ */
async function announceThread(parentRoomID, threadRoomID, thread) { async function announceThread(parentRoomID, threadRoomID, thread) {
const creatorMxid = select("sim", "mxid", "WHERE discord_id = ?").pluck().get(thread.owner_id) const creatorMxid = select("sim", "mxid", "WHERE user_id = ?").pluck().get(thread.owner_id)
const content = await threadToAnnouncement.threadToAnnouncement(parentRoomID, threadRoomID, creatorMxid, thread, {api}) const content = await threadToAnnouncement.threadToAnnouncement(parentRoomID, threadRoomID, creatorMxid, thread, {api})

View file

@ -29,7 +29,7 @@ async function createSim(user) {
// Save chosen name in the database forever // Save chosen name in the database forever
// Making this database change right away so that in a concurrent registration, the 2nd registration will already have generated a different localpart because it can see this row when it generates // Making this database change right away so that in a concurrent registration, the 2nd registration will already have generated a different localpart because it can see this row when it generates
db.prepare("INSERT INTO sim (discord_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(user.id, simName, localpart, mxid) db.prepare("INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(user.id, simName, localpart, mxid)
// Register matrix user with that name // Register matrix user with that name
try { try {
@ -37,7 +37,7 @@ async function createSim(user) {
} catch (e) { } catch (e) {
// If user creation fails, manually undo the database change. Still isn't perfect, but should help. // If user creation fails, manually undo the database change. Still isn't perfect, but should help.
// (A transaction would be preferable, but I don't think it's safe to leave transaction open across event loop ticks.) // (A transaction would be preferable, but I don't think it's safe to leave transaction open across event loop ticks.)
db.prepare("DELETE FROM sim WHERE discord_id = ?").run(user.id) db.prepare("DELETE FROM sim WHERE user_id = ?").run(user.id)
throw e throw e
} }
return mxid return mxid
@ -51,7 +51,7 @@ async function createSim(user) {
*/ */
async function ensureSim(user) { async function ensureSim(user) {
let mxid = null let mxid = null
const existing = select("sim", "mxid", "WHERE discord_id = ?").pluck().get(user.id) const existing = select("sim", "mxid", "WHERE user_id = ?").pluck().get(user.id)
if (existing) { if (existing) {
mxid = existing mxid = existing
} else { } else {
@ -164,7 +164,7 @@ async function syncAllUsersInRoom(roomID) {
assert.ok(typeof guildID === "string") assert.ok(typeof guildID === "string")
for (const mxid of mxids) { for (const mxid of mxids) {
const userID = select("sim", "discord_id", "WHERE mxid = ?").pluck().get(mxid) const userID = select("sim", "user_id", "WHERE mxid = ?").pluck().get(mxid)
assert.ok(typeof userID === "string") assert.ok(typeof userID === "string")
/** @ts-ignore @type {Required<import("discord-api-types/v10").APIGuildMember>} */ /** @ts-ignore @type {Required<import("discord-api-types/v10").APIGuildMember>} */

View file

@ -42,7 +42,7 @@ async function removeReaction(data) {
} }
if (!lookingAtMatrixReaction && !wantToRemoveMatrixReaction) { if (!lookingAtMatrixReaction && !wantToRemoveMatrixReaction) {
// We are removing a Discord user's reaction, so we just make the sim user remove it. // We are removing a Discord user's reaction, so we just make the sim user remove it.
const mxid = select("sim", "mxid", "WHERE discord_id = ?").pluck().get(data.user_id) const mxid = select("sim", "mxid", "WHERE user_id = ?").pluck().get(data.user_id)
if (mxid === event.sender) { if (mxid === event.sender) {
await api.redactEvent(roomID, event.event_id, mxid) await api.redactEvent(roomID, event.event_id, mxid)
} }

View file

@ -22,7 +22,7 @@ async function editToChanges(message, guild, api) {
// Figure out what events we will be replacing // Figure out what events we will be replacing
const roomID = select("channel_room", "room_id", "WHERE channel_id = ?").pluck().get(message.channel_id) const roomID = select("channel_room", "room_id", "WHERE channel_id = ?").pluck().get(message.channel_id)
let senderMxid = select("sim", "mxid", "WHERE discord_id = ?").pluck().get(message.author.id) || null let senderMxid = select("sim", "mxid", "WHERE user_id = ?").pluck().get(message.author.id) || null
if (senderMxid) { if (senderMxid) {
const senderIsInRoom = select("sim_member", "mxid", "WHERE room_id = ? AND mxid = ?").get(roomID, senderMxid) const senderIsInRoom = select("sim_member", "mxid", "WHERE room_id = ? AND mxid = ?").get(roomID, senderMxid)
if (!senderIsInRoom) { if (!senderIsInRoom) {

View file

@ -35,11 +35,11 @@ const Rlottie = (async () => {
/** /**
* @param {DiscordTypes.APIStickerItem} stickerItem * @param {DiscordTypes.APIStickerItem} stickerItem
* @returns {Promise<{mxc: string, info: typeof INFO}>} * @returns {Promise<{mxc_url: string, info: typeof INFO}>}
*/ */
async function convert(stickerItem) { async function convert(stickerItem) {
const existingMxc = select("lottie", "mxc", "WHERE id = ?").pluck().get(stickerItem.id) const existingMxc = select("lottie", "mxc_url", "WHERE sticker_id = ?").pluck().get(stickerItem.id)
if (existingMxc) return {mxc: existingMxc, info: INFO} if (existingMxc) return {mxc_url: existingMxc, info: INFO}
const r = await Rlottie const r = await Rlottie
const res = await fetch(file.DISCORD_IMAGES_BASE + file.sticker(stickerItem)) const res = await fetch(file.DISCORD_IMAGES_BASE + file.sticker(stickerItem))
if (res.status !== 200) throw new Error("Sticker data file not found.") if (res.status !== 200) throw new Error("Sticker data file not found.")
@ -67,8 +67,8 @@ async function convert(stickerItem) {
} }
}) })
assert(root.content_uri) assert(root.content_uri)
db.prepare("INSERT INTO lottie (id, mxc) VALUES (?, ?)").run(stickerItem.id, root.content_uri) db.prepare("INSERT INTO lottie (sticker_id, mxc_url) VALUES (?, ?)").run(stickerItem.id, root.content_uri)
return {mxc: root.content_uri, info: INFO} return {mxc_url: root.content_uri, info: INFO}
} }
module.exports.convert = convert module.exports.convert = convert

View file

@ -19,7 +19,7 @@ function getDiscordParseCallbacks(message, useHTML) {
return { return {
/** @param {{id: string, type: "discordUser"}} node */ /** @param {{id: string, type: "discordUser"}} node */
user: node => { user: node => {
const mxid = select("sim", "mxid", "WHERE discord_id = ?").pluck().get(node.id) const mxid = select("sim", "mxid", "WHERE user_id = ?").pluck().get(node.id)
const username = message.mentions.find(ment => ment.id === node.id)?.username || node.id const username = message.mentions.find(ment => ment.id === node.id)?.username || node.id
if (mxid && useHTML) { if (mxid && useHTML) {
return `<a href="https://matrix.to/#/${mxid}">@${username}</a>` return `<a href="https://matrix.to/#/${mxid}">@${username}</a>`
@ -405,13 +405,13 @@ async function messageToEvent(message, guild, options = {}, di) {
const format = file.stickerFormat.get(stickerItem.format_type) const format = file.stickerFormat.get(stickerItem.format_type)
if (format?.mime === "lottie") { if (format?.mime === "lottie") {
try { try {
const {mxc, info} = await lottie.convert(stickerItem) const {mxc_url, info} = await lottie.convert(stickerItem)
return { return {
$type: "m.sticker", $type: "m.sticker",
"m.mentions": mentions, "m.mentions": mentions,
body: stickerItem.name, body: stickerItem.name,
info, info,
url: mxc url: mxc_url
} }
} catch (e) { } catch (e) {
return { return {

View file

@ -53,7 +53,7 @@ function userToSimName(user) {
assert.notEqual(user.discriminator, "0000", "cannot create user for a webhook") assert.notEqual(user.discriminator, "0000", "cannot create user for a webhook")
// 1. Is sim user already registered? // 1. Is sim user already registered?
const existing = select("sim", "sim_name", "WHERE discord_id = ?").pluck().get(user.id) const existing = select("sim", "sim_name", "WHERE user_id = ?").pluck().get(user.id)
if (existing) return existing if (existing) return existing
// 2. Register based on username (could be new or old format) // 2. Register based on username (could be new or old format)

View file

@ -251,7 +251,7 @@ module.exports = {
async onTypingStart(client, data) { async onTypingStart(client, data) {
const roomID = select("channel_room", "room_id", "WHERE channel_id = ?").pluck().get(data.channel_id) const roomID = select("channel_room", "room_id", "WHERE channel_id = ?").pluck().get(data.channel_id)
if (!roomID) return if (!roomID) return
const mxid = from("sim").join("sim_member", "mxid").and("WHERE discord_id = ? AND room_id = ?").pluck("mxid").get(data.user_id, roomID) const mxid = from("sim").join("sim_member", "mxid").and("WHERE user_id = ? AND room_id = ?").pluck("mxid").get(data.user_id, roomID)
if (!mxid) return if (!mxid) return
// Each Discord user triggers the notification every 8 seconds as long as they remain typing. // Each Discord user triggers the notification every 8 seconds as long as they remain typing.
// Discord does not send typing stopped events, so typing only stops if the timeout is reached or if the user sends their message. // Discord does not send typing stopped events, so typing only stops if the timeout is reached or if the user sends their message.

View file

@ -0,0 +1,15 @@
BEGIN TRANSACTION;
-- Rename mxc to mxc_url for consistency
ALTER TABLE lottie RENAME COLUMN mxc TO mxc_url;
-- Rename id to sticker_id so joins make sense in the future
ALTER TABLE lottie RENAME COLUMN id TO sticker_id;
-- Rename discord_id to user_id so joins make sense in the future
ALTER TABLE sim RENAME COLUMN discord_id TO user_id;
COMMIT;

6
db/orm-utils.d.ts vendored
View file

@ -28,8 +28,8 @@ export type Models = {
} }
lottie: { lottie: {
id: string sticker_id: string
mxc: string mxc_url: string
} }
member_cache: { member_cache: {
@ -45,7 +45,7 @@ export type Models = {
} }
sim: { sim: {
discord_id: string user_id: string
sim_name: string sim_name: string
localpart: string localpart: string
mxid: string mxid: string

View file

@ -26,6 +26,6 @@ test("orm: from: get pluck works", t => {
}) })
test("orm: from: join and pluck works", t => { test("orm: from: join and pluck works", t => {
const mxid = from("sim").join("sim_member", "mxid").and("WHERE discord_id = ? AND room_id = ?").pluck("mxid").get("771520384671416320", "!hYnGGlPHlbujVVfktC:cadence.moe") const mxid = from("sim").join("sim_member", "mxid").and("WHERE user_id = ? AND room_id = ?").pluck("mxid").get("771520384671416320", "!hYnGGlPHlbujVVfktC:cadence.moe")
t.equal(mxid, "@_ooye_bojack_horseman:cadence.moe") t.equal(mxid, "@_ooye_bojack_horseman:cadence.moe")
}) })

View file

@ -324,7 +324,7 @@ async function eventToMessage(event, guild, di) {
} }
const sender = repliedToEvent.sender const sender = repliedToEvent.sender
const senderName = sender.match(/@([^:]*)/)?.[1] || sender const senderName = sender.match(/@([^:]*)/)?.[1] || sender
const authorID = select("sim", "discord_id", "WHERE mxid = ?").pluck().get(repliedToEvent.sender) const authorID = select("sim", "user_id", "WHERE mxid = ?").pluck().get(repliedToEvent.sender)
if (authorID) { if (authorID) {
replyLine += `<@${authorID}>` replyLine += `<@${authorID}>`
} else { } else {
@ -367,7 +367,7 @@ async function eventToMessage(event, guild, di) {
// Handling mentions of Discord users // Handling mentions of Discord users
input = input.replace(/("https:\/\/matrix.to\/#\/(@[^"]+)")>/g, (whole, attributeValue, mxid) => { input = input.replace(/("https:\/\/matrix.to\/#\/(@[^"]+)")>/g, (whole, attributeValue, mxid) => {
if (!utils.eventSenderIsFromDiscord(mxid)) return whole if (!utils.eventSenderIsFromDiscord(mxid)) return whole
const userID = select("sim", "discord_id", "WHERE mxid = ?").pluck().get(mxid) const userID = select("sim", "user_id", "WHERE mxid = ?").pluck().get(mxid)
if (!userID) return whole if (!userID) return whole
return `${attributeValue} data-user-id="${userID}">` return `${attributeValue} data-user-id="${userID}">`
}) })

View file

@ -41,5 +41,5 @@ const utils = require("../m2d/converters/utils")
await api.profileSetAvatarUrl(mxid, avatarUrl) await api.profileSetAvatarUrl(mxid, avatarUrl)
// add initial rows to database, like adding the bot to sim... // add initial rows to database, like adding the bot to sim...
db.prepare("INSERT INTO sim (discord_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run("0", reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), reg.sender_localpart, mxid) db.prepare("INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run("0", reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), reg.sender_localpart, mxid)
})() })()

View file

@ -10,7 +10,7 @@ INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, custom
('1100319550446252084', '!BnKuBPCvyfOkhcUjEu:cadence.moe', 'worm-farm', NULL, NULL, NULL), ('1100319550446252084', '!BnKuBPCvyfOkhcUjEu:cadence.moe', 'worm-farm', NULL, NULL, NULL),
('297272183716052993', '!rEOspnYqdOalaIFniV:cadence.moe', 'general', NULL, NULL, NULL); ('297272183716052993', '!rEOspnYqdOalaIFniV:cadence.moe', 'general', NULL, NULL, NULL);
INSERT INTO sim (discord_id, sim_name, localpart, mxid) VALUES INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES
('0', 'bot', '_ooye_bot', '@_ooye_bot:cadence.moe'), ('0', 'bot', '_ooye_bot', '@_ooye_bot:cadence.moe'),
('820865262526005258', 'crunch_god', '_ooye_crunch_god', '@_ooye_crunch_god:cadence.moe'), ('820865262526005258', 'crunch_god', '_ooye_crunch_god', '@_ooye_crunch_god:cadence.moe'),
('771520384671416320', 'bojack_horseman', '_ooye_bojack_horseman', '@_ooye_bojack_horseman:cadence.moe'), ('771520384671416320', 'bojack_horseman', '_ooye_bojack_horseman', '@_ooye_bojack_horseman:cadence.moe'),