genji

package module
v0.15.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 17, 2023 License: MIT Imports: 15 Imported by: 0

README

Genji

Genji

Document-oriented, embedded, SQL database

Introduction

Build Status go.dev reference Status

Genji is a database that allows running SQL queries on documents.

Checkout the SQL documentation, the Go doc and the usage example in the README to get started quickly.

Genji's API is still unstable: Database compatibility is not guaranteed before reaching v1.0.0

Features

  • SQL and documents: Use a powerful SQL language designed for documents as first-class citizen.
  • Flexible schemas: Define your table with strict schemas, partial schemas, or no schemas at all.
  • Transaction support: Fully serializable transactions with multiple readers and single writer. Readers don’t block writers and writers don’t block readers.
  • Compatible with the database/sql package

Installation

Install the Genji database

go install github.com/genjidb/genji

Usage

There are two ways of using Genji, either by using Genji's API or by using the database/sql package.

Using Genji's API

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/genjidb/genji"
    "github.com/genjidb/genji/document"
    "github.com/genjidb/genji/types"
)

func main() {
    // Create a database instance, here we'll store everything on-disk
    db, err := genji.Open("mydb")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // If needed, attach context, e.g. (*http.Request).Context().
    db = db.WithContext(context.Background())

    // Create a table with a strict schema.
    // Useful to have full control of the table content.
    // Notice that it is possible to define constraint on nested documents.
    err = db.Exec(`
        CREATE TABLE user (
            id              INT     PRIMARY KEY,
            name            TEXT    NOT NULL UNIQUE,
            address (
                city        TEXT    DEFAULT "?",
                zipcode     TEXT
            ),
            friends         ARRAY
        )
    `)

    // or a partial schema, using an ellipsis.
    // Useful to apply constraints only on a few fields, while storing documents of any shape
    err = db.Exec(`
        CREATE TABLE github_issues (
            id TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            state TEXT NOT NULL,
            ...
        );

        CREATE INDEX ON github_issues (state);
    `)

    // or a schemaless table
    // Useful when you need to store data first and explore it later,
    // or if you the structure of the data is already defined somewhere else
    // (e.g. documents returned from an API)
    err = db.Exec(`CREATE TABLE twitter_tweets_v2`)

    // Create an index
    err = db.Exec("CREATE INDEX user_city_idx ON user (address.city, address.zipCode)")

    // Insert some data
    err = db.Exec("INSERT INTO user (id, name) VALUES (?, ?)", 10, "Foo1", 15)

    // Supported values can go from simple integers to richer data types like lists or documents
    err = db.Exec(`
    INSERT INTO user (id, name, age, address, friends)
    VALUES (
        11,
        'Foo2',
        20,
        {"city": "Lyon", "zipcode": "69001"},
        ["foo", "bar", "baz"]
    )`)

    // Go structures can be passed directly
    type User struct {
        ID              uint
        Name            string
        TheAgeOfTheUser float64 `genji:"age"`
        Address         struct {
            City    string
            ZipCode string
        }
    }

    // Let's create a user
    u := User{
        ID:              20,
        Name:            "foo",
        TheAgeOfTheUser: 40,
    }
    u.Address.City = "Lyon"
    u.Address.ZipCode = "69001"

    err = db.Exec(`INSERT INTO user VALUES ?`, &u)

    // Query some documents
    res, err := db.Query("SELECT id, name, age, address FROM user WHERE age >= ?", 18)
    // always close the result when you're done with it
    defer res.Close()

    // Iterate over the results
    err = res.Iterate(func(d types.Document) error {
        // When querying an explicit list of fields, you can use the Scan function to scan them
        // in order. Note that the types don't have to match exactly the types stored in the table
        // as long as they are compatible.
        var id int
        var name string
        var age int32
        var address struct {
            City    string
            ZipCode string
        }

        err = document.Scan(d, &id, &name, &age, &address)
        if err != nil {
            return err
        }

        fmt.Println(id, name, age, address)

        // It is also possible to scan the results into a structure
        var u User
        err = document.StructScan(d, &u)
        if err != nil {
            return err
        }

        fmt.Println(u)

        // Or scan into a map
        var m map[string]interface{}
        err = document.MapScan(d, &m)
        if err != nil {
            return err
        }

        fmt.Println(m)
        return nil
    })
}

In-memory database

To store data in memory, use :memory: instead of a database path:

db, err := genji.Open(":memory:")

Using database/sql

// import Genji as a blank import
import _ "github.com/genjidb/genji/driver"

// Create a sql/database DB instance
db, err := sql.Open("genji", "mydb")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Then use db as usual
res, err := db.ExecContext(...)
res, err := db.Query(...)
res, err := db.QueryRow(...)

// use the driver.Scanner to scan into a struct
var u User
err = res.Scan(driver.Scanner(&u))

Genji shell

The genji command line provides an SQL shell that can be used to create, modify and consult Genji databases.

Make sure the Genji command line is installed:

go install github.com/genjidb/genji/cmd/genji@latest

Example:

# Opening an in-memory database:
genji

# Opening a database on disk:
genji dirName

Contributing

Contributions are welcome!

Thank you, contributors!

Made with contrib.rocks.

If you have any doubt, join the Gophers Slack channel or open an issue.

Documentation

Overview

Package genji implements a document-oriented, embedded SQL database.

Example
package main

import (
	"fmt"

	"github.com/genjidb/genji"
	"github.com/genjidb/genji/document"
	"github.com/genjidb/genji/types"
)

type User struct {
	ID      int64
	Name    string
	Age     uint32
	Address struct {
		City    string
		ZipCode string
	}
}

func main() {
	// Create a database instance, here we'll store everything in memory
	db, err := genji.Open(":memory:")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	// Create a table. Genji tables are schemaless by default, you don't need to specify a schema.
	err = db.Exec("CREATE TABLE user (name text, ...)")
	if err != nil {
		panic(err)
	}

	// Create an index.
	err = db.Exec("CREATE INDEX idx_user_name ON user (name)")
	if err != nil {
		panic(err)
	}

	// Insert some data
	err = db.Exec("INSERT INTO user (id, name, age) VALUES (?, ?, ?)", 10, "foo", 15)
	if err != nil {
		panic(err)
	}

	// Insert some data using document notation
	err = db.Exec(`INSERT INTO user VALUES {id: 12, "name": "bar", age: ?, address: {city: "Lyon", zipcode: "69001"}}`, 16)
	if err != nil {
		panic(err)
	}

	// Structs can be used to describe a document
	err = db.Exec("INSERT INTO user VALUES ?, ?", &User{ID: 1, Name: "baz", Age: 100}, &User{ID: 2, Name: "bat"})
	if err != nil {
		panic(err)
	}

	// Query some documents
	stream, err := db.Query("SELECT * FROM user WHERE id > ?", 1)
	if err != nil {
		panic(err)
	}
	// always close the result when you're done with it
	defer stream.Close()

	// Iterate over the results
	err = stream.Iterate(func(d types.Document) error {
		var u User

		err = document.StructScan(d, &u)
		if err != nil {
			return err
		}

		fmt.Println(u)
		return nil
	})
	if err != nil {
		panic(err)
	}

}
Output:

{10 foo 15 { }}
{12 bar 16 {Lyon 69001}}
{2 bat 0 { }}

Index

Examples

Constants

This section is empty.

Variables

View Source
var IsNotFoundError = errs.IsNotFoundError

IsNotFoundError determines if the given error is a NotFoundError. NotFoundError is returned when the requested table, index, document or sequence doesn't exist.

Functions

func IsAlreadyExistsError added in v0.15.1

func IsAlreadyExistsError(err error) bool

IsAlreadyExistsError determines if the error is returned as a result of a conflict when attempting to create a table, an index, a document or a sequence with a name that is already used by another resource.

Types

type DB

type DB struct {
	DB *database.Database
	// contains filtered or unexported fields
}

DB represents a collection of tables.

func Open

func Open(path string) (*DB, error)

Open creates a Genji database at the given path. If path is equal to ":memory:" it will open an in-memory database, otherwise it will create an on-disk database.

func (*DB) Begin

func (db *DB) Begin(writable bool) (*Tx, error)

Begin starts a new transaction. The returned transaction must be closed either by calling Rollback or Commit.

func (*DB) Close

func (db *DB) Close() error

Close the database.

func (*DB) Exec

func (db *DB) Exec(q string, args ...interface{}) error

Exec a query against the database without returning the result.

func (*DB) Prepare added in v0.13.0

func (db *DB) Prepare(q string) (*Statement, error)

Prepare parses the query and returns a prepared statement.

func (*DB) Query

func (db *DB) Query(q string, args ...interface{}) (*Result, error)

Query the database and return the result. The returned result must always be closed after usage.

func (*DB) QueryDocument

func (db *DB) QueryDocument(q string, args ...interface{}) (types.Document, error)

QueryDocument runs the query and returns the first document. If the query returns no error, QueryDocument returns errs.ErrDocumentNotFound.

func (*DB) Update

func (db *DB) Update(fn func(tx *Tx) error) error

Update starts a read-write transaction, runs fn and automatically commits it.

func (*DB) View

func (db *DB) View(fn func(tx *Tx) error) error

View starts a read only transaction, runs fn and automatically rolls it back.

func (DB) WithContext added in v0.9.0

func (db DB) WithContext(ctx context.Context) *DB

WithContext creates a new database handle using the given context for every operation.

type Result added in v0.13.0

type Result struct {
	// contains filtered or unexported fields
}

Result of a query.

func (*Result) Close added in v0.13.0

func (r *Result) Close() (err error)

Close the result stream.

func (*Result) Fields added in v0.13.0

func (r *Result) Fields() []string

func (*Result) Iterate added in v0.13.0

func (r *Result) Iterate(fn func(d types.Document) error) error

type Statement added in v0.13.0

type Statement struct {
	// contains filtered or unexported fields
}

Statement is a prepared statement. If Statement has been created on a Tx, it will only be valid until Tx closes. If it has been created on a DB, it is valid until the DB closes. It's safe for concurrent use by multiple goroutines.

func (*Statement) Exec added in v0.13.0

func (s *Statement) Exec(args ...interface{}) (err error)

Exec a query against the database without returning the result.

func (*Statement) Query added in v0.13.0

func (s *Statement) Query(args ...interface{}) (*Result, error)

Query the database and return the result. The returned result must always be closed after usage.

func (*Statement) QueryDocument added in v0.13.0

func (s *Statement) QueryDocument(args ...interface{}) (d types.Document, err error)

QueryDocument runs the query and returns the first document. If the query returns no error, QueryDocument returns errs.ErrDocumentNotFound.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx represents a database transaction. It provides methods for managing the collection of tables and the transaction itself. Tx is either read-only or read/write. Read-only can be used to read tables and read/write can be used to read, create, delete and modify tables.

Example
db, err := genji.Open(":memory:")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

tx, err := db.Begin(true)
if err != nil {
	panic(err)
}
defer tx.Rollback()

err = tx.Exec("CREATE TABLE IF NOT EXISTS user")
if err != nil {
	log.Fatal(err)
}

err = tx.Exec("INSERT INTO user (id, name, age) VALUES (?, ?, ?)", 10, "foo", 15)
if err != nil {
	log.Fatal(err)
}

d, err := tx.QueryDocument("SELECT id, name, age FROM user WHERE name = ?", "foo")
if err != nil {
	panic(err)
}

var u User
err = document.StructScan(d, &u)
if err != nil {
	panic(err)
}

fmt.Println(u)

var id uint64
var name string
var age uint8

err = document.Scan(d, &id, &name, &age)
if err != nil {
	panic(err)
}

fmt.Println(id, name, age)

err = tx.Commit()
if err != nil {
	panic(err)
}
Output:

{10 foo 15 { }}
10 foo 15

func (*Tx) Commit added in v0.13.0

func (tx *Tx) Commit() error

Commit the transaction. Calling this method on read-only transactions will return an error.

func (*Tx) Exec

func (tx *Tx) Exec(q string, args ...interface{}) (err error)

Exec a query against the database within tx and without returning the result.

func (*Tx) Prepare added in v0.13.0

func (tx *Tx) Prepare(q string) (*Statement, error)

Prepare parses the query and returns a prepared statement.

func (*Tx) Query

func (tx *Tx) Query(q string, args ...interface{}) (*Result, error)

Query the database withing the transaction and returns the result. Closing the returned result after usage is not mandatory.

func (*Tx) QueryDocument

func (tx *Tx) QueryDocument(q string, args ...interface{}) (types.Document, error)

QueryDocument runs the query and returns the first document. If the query returns no error, QueryDocument returns errs.ErrDocumentNotFound.

func (*Tx) Rollback added in v0.13.0

func (tx *Tx) Rollback() error

Rollback the transaction. Can be used safely after commit.

Directories

Path Synopsis
cmd
genji Module
Package document defines types to manipulate and compare documents and values.
Package document defines types to manipulate and compare documents and values.
engine
badgerengine Module
fuzz module
internal
database
Package database provides database primitives such as tables, transactions and indexes.
Package database provides database primitives such as tables, transactions and indexes.
expr/glob
Package glob implements wildcard pattern matching algorithms for strings.
Package glob implements wildcard pattern matching algorithms for strings.
kv
lock
Package lock implements two-phase locking (2PL).
Package lock implements two-phase locking (2PL).
lib

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL