2

My Supabase JS client performs an INSERT on the messages table using the following.

import { createClient } from "@supabase/supabase-js";

const supabase = createClient(
    "MY SUPABASE URL",
    "MY ANON KEY"
);

async function insertMessage(sender, content, file, parent) {
    return await supabase.from("messages").insert({
        id: uuidv4(),
        date: Date.now(),
        sender: sender,
        content: content || null,
        file: file || null,
        parent: parent,
    });
}

I have some old messages in the table from previous work, but as you can see below, the new entries are being inserted "above" the older messages, but still "below" one another. demo

My expectation would be that each new entry would be written at the bottom of the table always, so I'm trying to understand why is this. And how do I prevent it?

I haven't been able to find anything about this. Nobody else seems to have had the issue.

Zacoons
  • 71
  • 1
  • 6
  • 4
    Unless you use the `order by` clause there is **no predictable** sequence of the rows returned. According to documentation *If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce.* See [Select](https://www.postgresql.org/docs/current/sql-select.html#SQL-ORDERBY) – Belayer Apr 10 '23 at 01:59

2 Answers2

1

As @Belayer has said in the comments, the default order of the rows would be random. You can order the rows by whatever you want by clicking on the sort button of the table editor.

enter image description here

dshukertjr
  • 15,244
  • 11
  • 57
  • 94
1

The comment by @Belayer led me to find a solution by adding .order("date") to my getMessages query. I changed getMessages to resemble the following

async function getMessages(parent, fromIdx, maxResults) {
    return await supabase
        .from("messages")
        .select("*, users(avatarBase64, name)")
        .eq("parent", parent)
        .range(fromIdx, fromIdx + maxResults)
        .order("date"); // added this line
}

insertMessages didn't change

async function insertMessage(sender, content, file, parent) {
    return await supabase.from("messages").insert({
        id: uuidv4(),
        date: Date.now(),
        sender: sender,
        content: content || null,
        file: file || null,
        parent: parent,
    });
}
Zacoons
  • 71
  • 1
  • 6