gnolang / hackerspace

Tinker, build, explore Gno - without the monorepo!
11 stars 8 forks source link

Release the auto-merkelized state persistency feature as a standalone library. #6

Open moul opened 1 year ago

moul commented 1 year ago

The idea would be to reduce the size and complexity of https://github.com/gnolang/gno/tree/master/gnovm/pkg/gnolang the state management system into its own library, i.e., github.com/gnolang/gno/gnovm/pkg/gomerkleizer.

It could be used by Go programmers to replace sqlite for some projects.

Example in sqlite

package main

import (
    "database/sql"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    db, err := sql.Open("sqlite3", "./example.db")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    _, err = db.Exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER);")
    if err != nil {
        panic(err)
    }

    _, err = db.Exec("INSERT INTO users (name, age) VALUES (?, ?);", "John Doe", 30)
    if err != nil {
        panic(err)
    }

    rows, err := db.Query("SELECT id, name, age FROM users;")
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    for rows.Next() {
        var id, age int
        var name string
        err = rows.Scan(&id, &name, &age)
        if err != nil {
            panic(err)
        }
        fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, name, age)
    }

    err = rows.Err()
    if err != nil {
        panic(err)
    }
}

Example in gomerkleizer

package main

import (
    "github.com/gnolang/gno/gnovm/pkg/gomerkeleizer"
)

type User struct {
    Name string
    Age int
}

type DB struct {
    Users []User
    // ...
}

func main() {
    var db DB
    err := gomerkeleizer.Open("./state.db", &db)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    db.Users = append(db.Users, User{"John Doe", 30})

    for _, user := range db.Users {
        fmt.Printf("Name: %s", Age: %d\n", user.Name, user.Age)
    }
}