ostafen / clover

A lightweight document-oriented NoSQL database written in pure Golang.
MIT License
680 stars 55 forks source link

FindById() not working as expected #5

Closed xxxserxxx closed 2 years ago

xxxserxxx commented 2 years ago

I may be doing something wrong; if so, please point it out. However, after closing and re-opening a database, FindById() does not find any documents.

package main

import (
    c "github.com/ostafen/clover"
    "log"
)

func main() {
        // This part is out of the README
    db, _ := c.Open("clover-db")
    db.CreateCollection("myCollection")

    doc := c.NewDocument()
    doc.Set("hello", "clover!")

    docId, _ := db.InsertOne("myCollection", doc)
    log.Printf("created document %s\n", docId)

    doc, _ = db.Query("myCollection").FindById(docId)
    log.Println(doc.Get("hello"))

        // Now, close the document, re-open it, and try to FindByID()
    db.Close()

    db, _ = c.Open("clover-db")
        // First, find by the ID created above
    doc, _ = db.Query("myCollection").FindById(docId)
    if doc == nil {
        log.Printf("didn't find the document %s\n", docId)
    }
        // That fails, so now find the document manually, get the ID from it, and try to find it
    ds, _ := db.Query("myCollection").FindAll()
    if len(ds) == 0 {
        log.Printf("didn't find any documents")
    }
    newDocId := ds[0].ObjectId()
    if docId != newDocId {
        log.Printf("the ids changed (%s != %s)\n", docId, newDocId)
    }
    doc, _ = db.Query("myCollection").FindById(newDocId)
    if doc == nil {
        log.Printf("didn't find the document (%s) I just loaded\n", newDocId)
    }
    db.Close()
}

What I do here is:

  1. Tutorial code from README
  2. Close the DB
  3. Re-open it
  4. Try to find the document previously inserted with FindById()
  5. Find the document with FindAll(), and get the ID from it
  6. Try to find the document using FindById() using the ID in step 5

On my end, once I close the DB no documents are able to be referenced by ID.

10126» go run . 
2022/03/12 09:39:59 created document ca7e8241-52ff-4f17-84b6-cb947acbe581
2022/03/12 09:39:59 clover!
2022/03/12 09:39:59 didn't find the document ca7e8241-52ff-4f17-84b6-cb947acbe581
2022/03/12 09:39:59 didn't find the document (ca7e8241-52ff-4f17-84b6-cb947acbe581) I just loaded

Clover: github.com/ostafen/clover v0.0.0-20220302164508-28d538d46bc1
Go: go version go1.17.8 linux/amd64

Edit

I believe this is because the collection index is never updated except when documents are inserted. Specifically, the index is never refreshed when the collection is loaded -- or, at least, I can't find where this happens.

ostafen commented 2 years ago

Hi, thank you for signaling this problem. As you correctly pointed out, the index was never reloaded from disk. My last commit should fix the problem.

Let me know if it works!

xxxserxxx commented 2 years ago

Looks good; thanks for the quick fix!