node.jstypescriptsqlite

SQLite3 Discord ID Precision Issue in TypeScript


I'm working on a Discord bot using TypeScript and SQLite3 as the database. When querying a Users table with:

SELECT * FROM Users;

I encounter a strange issue: the returned Discord ID has 3 numbers replaced, leading to an incorrect value.

For example:

You can see that only the last 3 digits differ.

Here's the schema for my Users table:

CREATE TABLE IF NOT EXISTS Users (
    _id INTEGER PRIMARY KEY AUTOINCREMENT,
    id TEXT NOT NULL UNIQUE,         -- Discord ID stored as TEXT
    xp INTEGER DEFAULT 0,
    level INTEGER DEFAULT 0,
    balance REAL DEFAULT 0.00,
    market_items TEXT DEFAULT NULL,  -- JSON array of item IDs
    last_level_up TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

The id field, which holds the Discord ID, is stored as TEXT to avoid any integer overflow issues, since Discord IDs are large numbers.

Despite storing the correct ID in the database, querying it results in incorrect values with slight differences. The data stored in SQLite is correct, but the issue occurs during retrieval.

If needed I can provide the bot I am working on.

What I Tried

What I Expected

I expected that when I query the Users table, the Discord IDs retrieved would exactly match the IDs stored in the database, without any alterations to the digits. Specifically, the retrieved ID should be 1248626823638552701, the same as the one stored, rather than 1248626823638552600.

EDIT

I have gotten it to work, turns out I was not properly casting it as a string. Thanks to:


Solution

  • Trying to parse each column as JSON is the cause of this.

    const parsed = JSON.parse(row[key as keyof typeof row]);
    (row as any)[key] = parsed;
    

    The original query will return row = { id: "1248626823638552701", ... }, but JSON.parse("1248626823638552701") is 1248626823638552600.