simdb

package module
v0.0.0-...-f3d266f Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2022 License: GPL-3.0 Imports: 11 Imported by: 0

README

simdb

A simple json db in GO

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

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 db "github.com/sonyarouje/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() (jsonField string, value interface{}) {
	value=c.CustID
	jsonField="custid"
	return
}

func main() {
    driver, err:=db.New("data")
    if 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
  err=driver.Insert(customer)
  if 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
  err=driver.Open(Customer{}).Where("name","=","sarouje").Get().AsEntity(&customers)
  if 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
  err=driver.Open(Customer{}).Where("custid","=","CUST1").First().AsEntity(&customerFrist)
  if 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"
  err=driver.Update(customerFrist)
  if err!=nil {
    panic(err)
  }
  
  //Delete
  toDel:=Customer{
     CustID:"CUST1",
  }
  err=driver.Delete(toDel)
}
  

Started as a library to learn GO.

Some of the codes 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

View Source
const (
	IdentifierKey = "ID"
)

Variables

View Source
var ErrRecordNotFound = errors.New("record not found")
View Source
var ErrUpdateFailed = errors.New("update failed, no record(s) to update")

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(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 elemental.Identifiable) (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) Insert

func (d *Driver) Insert(entity elemental.Identifiable) (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 elemental.Identifiable) *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 elemental.Identifiable) (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) Upsert

func (d *Driver) Upsert(entity elemental.Identifiable) (err error)

Upsert function will try updating the passed entity. If no records to update then do the Insert operation.

   	customer := Customer{
		CustID:  "CU4",
		Name:    "Sony Arouje",
		Address: "address",
		Contact: Contact{
			Phone: "45533355",
			Email: "someone@gmail.com",
		},
	}
 driver.Upsert(customer)

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 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