Skip to content
Source
Sign inSign up
TanStack/db

Qu: is it correct to assume implicit order preservation? #317

Send to my agent
Closedthruflo(GitHub profile, opens in a new tab) opened this issue 3 comments

Two questions relating to implicit ordering. I can obviously verify in code but I;m asking about this from a let's document the guarantee POV, partly so we don't accidentally change the behaviour:

  1. Is there an implicit ordering to a collection, such as by insert time or key? For example when a live query doesn't have an orderBy. If so, does this work across synced and optimistic state?

  2. Say I have a base collection that's ordered and then I derive a new collection / live query from it:

const { collection: orderedTodos } = useLiveQuery((query) =>
  query
    .from({ todo: todoCollection })
    .orderBy(({ todo }) => todo.inserted_at, 'asc')
)

const { data: pendingTodos } = useLiveQuery((query) =>
  query
    .from({ todo: orderedTodos })
    .where(({ todo }) => eq(todo.completed, false))
)

Is the second collection guaranteed to be in the same order as the first?

  1. thruflo(GitHub profile, opens in a new tab) added labelsdocumentation

  2. thruflo(GitHub profile, opens in a new tab) added labelsquestion

  3. If there is not orderBy in the query, there is no implicit order - it's essentially random.

    (Technically, it likely in insertion order, but that's a side effect with zero guarantee)

  4. Got it 👍 good to know.

  5. This is a bit awkward when it come to API responses w/ queryCollection. Many APIs return items in a natural order, and it's boilerplate to need to explicitly preserve that:

    const popularPostsCollection = createCollection(
      queryCollectionOptions({
        queryKey: () => ["posts", "popular"],
        queryFn: () =>
          fetchPopularPosts().then((posts) =>
            posts.map((post, index) => ({ ...post, _index: index }))
          ),
      })
    )
    const postsWithAuthors = createLiveQueryCollection((q) =>
      q
        .from({ post: popularPostsCollection })
        .leftJoin({ author: usersCollection }, ({ post, author }) =>
          eq(post.author_id, author.id)
        )
        .orderBy(({ post }) => post._index, `asc`)
    )

Sign in to join this conversation.