Sequelize `Model.update()` not updating database records

Viewed 65

I am trying to update a record in my SQLite database using Sequelize. The weird thing is that a log message for setting the value is generated - but if the value is re-fetched, no changes seem to be present.

Code that I am using to update database values:

import { MessageEmbed } from 'discord.js';
import { DisableSlashCommandData as slashCommandData } from '../SlashCommandData/disable.js';

export default {
    slashCommandData,
    name: 'disable',
    async execute(client, interaction) {
        if (!interaction.member.permissions.has('ADMINISTRATOR')) {
            return await interaction.reply({
                content: 'You must have the `ADMINISTRATOR` permission in order to use this command!',
                ephemeral: true,
            });
        }

        const channel = await client.data.Channels.findByPk(interaction.channel.id);

        // The code is stuck in this if statement, because its condition always returns true, as there is no change in 'channel'.
        if ((!channel) || !channel.get('disabled')) {
            /* Not disabled - disable in current channel */
            await client.data.Channels.update({
                disabled: true,
            }, {
                where: {
                    id: interaction.channel.id,
                },
            });

            return await interaction.reply({
                embeds: [
                    new MessageEmbed()
                        .setColor(client.config.colors.red)
                        .setAuthor({
                            name: interaction.user.tag,
                            iconURL: interaction.user.displayAvatarURL({ dynamic: true }),
                        })
                        .setDescription(`Interactions will now be ignored in this channel (${interaction.channel.toString()})`)
                        .setTimestamp(),
                ],
            });
        }
        else {
            /* Commands already disabled - enable them! */

            await client.data.Channels.update({
                disabled: false,
            }, {
                where: {
                    id: interaction.channel.id,
                },
            });

            return await interaction.reply({
                embeds: [
                    new MessageEmbed()
                        .setColor(client.config.colors.green)
                        .setAuthor({
                            name: interaction.user.tag,
                            iconURL: interaction.user.displayAvatarURL({ dynamic: true }),
                        })
                        .setDescription(`Interactions will no longer be ignored in this channel (${interaction.channel.toString()})`)
                        .setTimestamp(),
                ],
            });
        }
    },
};

It seems that the value isn't updating in my database. This issue only seems to be happening in regard to this particular table.

Definitions

Definition of client.data:

{
  sequelize: <ref *1> Sequelize {
    options: {
      dialect: 'sqlite',
      dialectModule: null,
      dialectModulePath: null,
      protocol: 'tcp',
      define: {},
      query: {},
      sync: {},
      timezone: '+00:00',
      standardConformingStrings: true,
      logging: [Function: log],
      omitNull: false,
      native: false,
      replication: false,
      ssl: undefined,
      pool: {},
      quoteIdentifiers: true,
      hooks: {},
      retry: [Object],
      transactionType: 'DEFERRED',
      isolationLevel: null,
      databaseVersion: 0,
      typeValidation: false,
      benchmark: false,
      minifyAliases: false,
      logQueryParameters: true,
      storage: 'C:\\Users\\User\\Documents\\GitHub\\Project\\assets\\db\\database.sqlite'
    },
    config: {
      database: 'database',
      username: 'user',
      password: 'password',
      host: 'localhost',
      port: undefined,
      pool: {},
      protocol: 'tcp',
      native: false,
      ssl: undefined,
      replication: false,
      dialectModule: null,
      dialectModulePath: null,
      keepDefaultTimezone: undefined,
      dialectOptions: undefined
    },
    dialect: SqliteDialect {
      sequelize: [Circular *1],
      connectionManager: [ConnectionManager],
      queryGenerator: [SQLiteQueryGenerator],
      queryInterface: [SQLiteQueryInterface]
    },
    queryInterface: SQLiteQueryInterface {
      sequelize: [Circular *1],
      queryGenerator: [SQLiteQueryGenerator]
    },
    models: { cases: cases, user: user, channels: channels },
    modelManager: ModelManager { models: [Array], sequelize: [Circular *1] },
    connectionManager: ConnectionManager {
      sequelize: [Circular *1],
      config: [Object],
      dialect: [SqliteDialect],
      versionPromise: null,
      pool: [Pool],
      connections: [Object],
      lib: [Object]
    }
  },
  Cases: cases,
  Users: user,
  Channels: channels
}

Code of file that creates client.data:

/**
 * Starts the database and defines models.
 */

import Sequelize from 'sequelize';
import { join } from 'node:path';

import { Case } from '../../models/Case.js';
import { User } from '../../models/User.js';
import { Channel } from '../../models/Channel.js';

export function initDb() {
    const sequelize = new Sequelize('database', 'user', 'password', {
        host: 'localhost',
        dialect: 'sqlite',
        storage: join(process.cwd(), 'assets', 'db', 'database.sqlite'),
        logging: console.log,
        logQueryParameters: true,
    });

    const Cases = Case(sequelize);
    const Users = User(sequelize);
    const Channels = Channel(sequelize);

    if (process.argv.includes('--syncdb')) {
        // necessary to construct tables
        console.info('[Sequelize] Syncing database...');
        const start = Date.now();
        sequelize.sync({ force: true });
        console.info(`[Sequelize] Successfully synced sequelize database in ${start - Date.now()} ms`);
    }

    return Object.freeze({
        sequelize,
        Cases,
        Users,
        Channels,
    });
}

The returned object is client.data.

Models

'Channel' model definition:

import { DataTypes } from 'sequelize';

/**
 * Defines the 'channel' model and returns it
 * @param {import("sequelize").Sequelize} sequelize Sequelize instance
 * @returns {import("sequelize").Model}
 */
export function Channel(sequelize) {
    return sequelize.define('channels', {
        id: {
            unique: true,
            primaryKey: true,
            allowNull: false,
            type: DataTypes.STRING,
        },
        disabled: {
            type: DataTypes.STRING,
            allowNull: false,
            defaultValue: '0',
        },
    }, {
        timestamps: true,
    });
}

SQLite logs

Executing (default): SELECT `id`, `disabled`, `createdAt`, `updatedAt` FROM `channels` AS `channels` WHERE `channels`.`id` = '985789702302994432';
Executing (default): UPDATE `channels` SET `disabled`=$1,`updatedAt`=$2 WHERE `id` = $3; {"$1":true,"$2":"2022-07-22 18:17:16.651 +00:00","$3":"985789702302994432"}

Dependency Versions

Project@1.0.0 C:\Users\User\Documents\GitHub\Project
├── @discordjs/rest@0.5.0
├── discord-api-types@0.34.0
├── discord.js@13.8.0
├── dotenv@16.0.1
├── erlpack@0.1.4
├── eslint@8.17.0
├── sequelize@6.20.1
├── sqlite3@5.0.8
├── utf-8-validate@5.0.9
└── zlib-sync@0.1.7

As said earlier, this only seems to be happening on this particular model; everything else on a different model/table will work perfectly fine.

Any help would be appreciated.

0 Answers
Related