simdb

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2020 License: GPL-3.0 Imports: 13 Imported by: 0

README

simdb

A simple JSON database in Go.

This is a fork from sonyarouje/simdb. It was forked to add support for Go Modules, and made a few tweaks.

Reasoning

I needed a simple way to query and persist data to JSON files. This was a great starting point.

Original Reasoning

I sometimes write programs for RaspberryPi using nodejs and use a json file as a data storage. There are so many libraries in nodejs to deal with json file as a data storage. I could'nt find a similar library in GO to use in GO based RPi projects. So decided to write one.

Keep in mind this library can be used in less data intensive applications. I normally use these kind of json data to store execution rules for sensors, etc.

Go Doc https://godoc.org/github.com/sonyarouje/simdb/db

What it does? This library enables to store, retrieve, update and delete data from the json db.

Usage Let's have a look at, how to store some data and manipulate them using simd.

package main

import "github.com/adampresley/simdb"

type Customer struct {
	CustID string `json:"custid"`
	Name string `json:"name"`
	Address string `json:"address"`
	Contact Contact
}

type Contact struct {
	Phone string `json:"phone"`
	Email string `json:"email"`
}

/*
ID any struct that needs to persist should implement this function defined 
in Entity interface.
*/
func (c Customer) ID() (string, interface{}) {
	return "custid", c.CustID
}

func main() {
	var err error
	var driver *simdb.Driver

	if driver, err = simdb.New("data"); err != nil {
		panic(err)
	}
 
	customer:=Customer {
		CustID:"CUST1",
		Name:"sarouje",
		Address: "address",
		Contact: Contact {
			Phone:"45533355",
			Email:"someone@gmail.com",
		},
	}    

	/*
	 * Creates a new Customer file inside the directory passed as the parameter to New()
	 * if the Customer file already exist then insert operation will add the customer data to the array
	 */
	if err = driver.Insert(customer); err != nil {
		panic(err)
	}
  
	/*
	 * GET ALL Customer
	 * opens the customer json file and filter all the customers with name sarouje.
	 * AsEntity takes a pointer to Customer array and fills the result to it.
	 * we can loop through the customers array and retireve the data.
	 */
	var customers []Customer

	if err = driver.Open(Customer{}).Where("name", "=", "sarouje").Get().AsEntity(&customers); err != nil {
		panic(err)
	}
  
	/*
	 * GET ONE Customer
	 * First() will return the first record from the results 
	 * AsEntity takes a pointer to Customer variable (not an array pointer)
	 */
	var customerFrist Customer

	if err = driver.Open(Customer{}).Where("custid", "=", "CUST1").First().AsEntity(&customerFrist); err != nil {
		panic(err)
	}

	/*
	 * Update function uses the ID() to get the Id field/value to find the record and update the data.
	 */
	customerFrist.Name = "Sony Arouje"

	if err=driver.Update(customerFrist); err != nil {
		panic(err)
	}

	/*
	 * Delete
	 */
	toDelete := Customer{
		CustID:"CUST1",
	}

	if err=driver.Delete(toDel); err != nil {
		panic(err)
	}
}

Started as a library to learn GO.

Some of the code to apply JSON filtering are borrowed from https://github.com/thedevsaddam/gojsonq.

Documentation

Overview

Package db A simple library to persist structs in json file and perform queries and CRUD operations

Index

Constants

This section is empty.

Variables

View Source
var ErrTooManyRecords = fmt.Errorf("Too many records returned when 1 was expected")
View Source
var ErrZeroRecords = fmt.Errorf("No records found")

Functions

This section is empty.

Types

type Driver

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

Driver contains all the state of the db.

func New

func New(fs afero.Fs, dir string) (*Driver, error)

New creates a new database driver. Accepts the directory name to store the db files. If the passed directory not exist then will create one. driver, err:=db.New("customer")

func (*Driver) AsEntity

func (d *Driver) AsEntity(output interface{}) (err error)

AsEntity will converts the map to the passed structure pointer. should call this function after calling Get() or First(). This function will convert the result of Get or First operation to the passed structure type 'output' variable should be a pointer to a structure or stucture array. Function returns error in case of any errors in conversion.

First()

var custOut Customer
err:=driver.Open(Customer{}).First().AsEntity(&custOut)
fmt.Printf("%#v", custOut)
this function will fill the custOut with the values from the map

Get()

var customers []Customer
err:=driver.Open(Customer{}).Get().AsEntity(&customers)

func (*Driver) Delete

func (d *Driver) Delete(entity Entity) (err error)

Delete the record from the json db based on the id field/value pair

  custToDelete:=Customer {
	   CustID:"CUST1",
  }
  err:=driver.Delete(custToDelete)

func (*Driver) Errors

func (d *Driver) Errors() []error

Errors will return errors encountered while performing any operations

func (*Driver) First

func (d *Driver) First() *Driver

First return the first record matching the condtion.

driver.Open(Customer{}).Where("custid","=","CUST1").First()

func (*Driver) Get

func (d *Driver) Get() *Driver

Get the result from the json db as an array. If no where condition then return all the data from json db

Get based on a where condition

driver.Open(Customer{}).Where("name","=","sarouje").Get()

Get all records

driver.Open(Customer{}).Get()

func (*Driver) GetNextNumericID added in v1.0.2

func (d *Driver) GetNextNumericID() int

func (*Driver) GetNextStringID added in v1.0.2

func (d *Driver) GetNextStringID() string

func (*Driver) Insert

func (d *Driver) Insert(entity Entity) (err error)

Insert the entity to the json db. Insert will identify the type of the entity and insert the entity to the specific json file based on the type of the entity. If the db file not exist then will create a new db file

	customer:=Customer {
		CustID:"CUST1",
		Name:"sarouje",
		Address: "address",
		Contact: Contact {
			Phone:"45533355",
			Email:"someone@gmail.com",
		},
	}
 err:=driver.Insert(customer)

func (*Driver) Open

func (d *Driver) Open(entity Entity) *Driver

Open will open the json db based on the entity passed. Once the file is open you can apply where conditions or get operation. driver.Open(Customer{}) Open returns a pointer to Driver, so you can chain methods like Where(), Get(), etc

func (*Driver) Raw

func (d *Driver) Raw() interface{}

Raw will return the data in map type

func (*Driver) RawArray

func (d *Driver) RawArray() []interface{}

RawArray will return the data in map array type

func (*Driver) Update

func (d *Driver) Update(entity Entity) (err error)

Update the json data based on the id field/value pair

customerToUpdate:=driver.Open(Customer{}).Where("custid","=","CUST1").First()
customerToUpdate.Name="Sony Arouje"
err:=driver.Update(customerToUpdate)

Should not change the ID field when updating the record.

func (*Driver) Where

func (d *Driver) Where(key, cond string, val interface{}) *Driver

Where builds a where clause to filter the records.

driver.Open(Customer{}).Where("custid","=","CUST1")

type Entity

type Entity interface {
	ID() (jsonField string, value interface{})
}

* Entity any structure wanted to persist to json db should implement this interface function ID(). * ID and Field will be used while doing update and delete operation. * ID() return the id value and field name that stores the id * * Sample Struct * type Customer struct { * CustID string `json:"custid"` * Name string `json:"name"` * Address string `json:"address"` * Contact Contact * } * type Contact struct { * Phone string `json:"phone"` * Email string `json:"email"` * } * func (c Customer) ID() (jsonField string, value interface{}) { * value=c.CustID * jsonField="custid" * return * }

type QueryFunc

type QueryFunc func(x, y interface{}) (bool, error)

QueryFunc describes a conditional function which perform comparison

Jump to

Keyboard shortcuts

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