coreimmudb

package
v1.2.17 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2024 License: MIT Imports: 11 Imported by: 0

README

CoreImmuDB Package Guide

Steps for connecting to Immudb
  • The package provides three methods to establish a database connection. If an error occurs during the connection establishment then error is returned.
  1. coreimmudb.InitUsingJson() - Provide JSON file path to read ImmuDB config details.

    [
    	{
    		"hostName": "ImmuDbHost1",
    		"server": "127.0.0.1",
    		"port": 3322,
    		"database": "defaultdb",
    		"username": "immudb",
    		"password": "immudb",
    		"dir": "",
    		"maxRecvMsgSize: 4,
    		"isDefault": true,
    		"isDisabled": false
    		}
    ]
    
  2. coreimmudb.InitImmuDBConnections() - Provide Immudb config details in []coreimmudb.ImmuHost

    [
    		coreimmudb.ImmuHost{
    			"HostName": "ImmuDbHost1",
    			"Server": "127.0.0.1",
    			"Port": 3322,
    			"database": "defaultdb",
    			"Username": "immudb",
    			"Password": "immudb",
    			"Dir": "",
    			"MaxRecvMsgSize": 4,
    			"IsDefault": true,
    			"IsDisabled": false
    		}
    ]
    
  3. coreimmudb.AddDBConnection - Provide Immudb connection details using coreimmudb.ImmuHost

    		coreimmudb.ImmuHost{
    			"HostName": "ImmuDbHost1",
    			"Server": "127.0.0.1",
    			"Port": 3322,
    			"database": "defaultdb",
    			"Username": "immudb",
    			"Password": "immudb",
    			"Dir": "",
    			"MaxRecvMsgSize": 4,
    			"IsDefault": true,
    			"IsDisabled": false
    		}
    
    

    Parameters

    Hostname (hostName) - Hostname for the database connection.
    Server (server) - Database server address.
    Port (port) - Port on which ImmuDB running.
    Database (database) - Database name.
    Username (username) - Database username
    Password (password) - Database password
    Dir (dir) - Storing .identity (database server identity) and .state file
    MaxRecvMsgSize (maxRecvMsgSize) - Recieve message maximum size in MB (Default: 4MB)
    IsDefault (isDefault) - Default database selection
    IsDisabled (isDisabled) - Skip connection

Disconnecting ImmuDB connection

Use DeleteImmuDbSession() function to disconnect ImmuDB connection.
coreimmudb.DeleteImmuDbSession(hostName string)

  • Pass hostname as argument to the above method.
  • It will return error, if failed to disconnect ImmuDB.
Get Immudb client for specific Hostname

Use GetImmuDbConnection() function to get ImmuDB client.
coreimmudb.GetImmuDbConnection(hostName string)

  • Pass hostname as argument to the above method.
  • It returns immudb client if there are no errors else it returns an error.

Create Database

Use CreateDatabase() method to create database with specific database settings.
(i *ImmuDAO) coreimmudb.CreateDatabase(dbName string, dbSettings *schema.DatabaseNullableSettings)

  • Pass dbName and dbSettings as argument to the above method.
  • It returns (*schema.CreateDatabaseResponse, error) - If no error then it returns *schema.CreateDatabaseResponse or else an error.

Create Database User

Use CreateUser() method to create user with specific permission for a database.
(i *ImmuDAO) coreimmudb.CreateUser(username, password, dbName string, permission int)

  • Pass username, password, dbName and permission as argument to the above method.
  • It returns error - If password criteria not matched or database doesn't exists or user already exists or else the user gets created.

Read Operations

Get Options

coreimmudb.GetOptions{} is used to set additional options when reading a value with a Get call.

{
	"atTx": 4,
	"sinceTx": 0,
	"noWait": True,
	"atRevision": 0
}

AtTx (atTx) - This option is used to specify that the value read must be the one set at transaction with id given in the tx parameter.
SinceTx (sinceTx) - This option can be used to avoid waiting for the indexer to be up-to-date with the most recent transaction.
NoWait (noWait) - If this option set to true, then the server will not wait for the indexer to be up-to-date with the most recent transaction.

  • This means that the user will get the result instantly without the risk of the server wait for the indexer that may happen in case of a large spike of new transactions.

AtRevision (atRevision) - This option is used to request specific revision for given key.

  • The way revision is interpreted depends on the value:
    • if rev = 0, returns current value.
    • if rev > 0, returns nth revision value.
    • if rev < 0, returns nth revision value from the end.
Combination of coreimmudb.GetOptions which will work together.
AtTx SinceTx NoWait AtRevision Applies
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 0 1 1
1 1 1 0
1 1 1 1

Note :- These Options only work with GetKeyData() and GetVerifiedKeyData() and does not work with GetAllKeysData() and GetKeyHistory().

Get key data

Use GetKeyData() method to fetch data for key.
(i *ImmuDAO) coreimmudb.GetKeyData(key []byte)

  • Pass key as argument to the above method.
  • It returns (*schema.Entry, error) - If no error then it returns *schema.Entry or else an error.

Get key data with additional server-provided proof validation

Use GetVerifiedKeyData() method to fetch data for key with additional server-provided proof validation.
(i *ImmuDAO) coreimmudb.GetVerifiedKeyData(key []byte)

  • Pass key as argument to the above method.
  • It returns (*schema.Entry, error)- If no error then it returns *schema.Entry or else an error.

Get data for all provided keys

Use GetAllKeysData() method to fetch data for all provided keys.
(i *ImmuDAO) coreimmudb.GetAllKeysData(keys [][]byte)

  • Pass arrays of keys as argument to the above method.
  • It returns (*schema.Entries, error) - If no error then it returns *schema.Entries or else an error.

Get history for single key

Use GetKeyHistory() method to get history(all values) of a key.
(i *ImmuDAO) GetKeyHistory(key []byte, offset uint64, limit int32, desc bool)

  • Pass Key, offset, limit, desc as argument to the above method.
  • It returns (*schema.Entries, error) - If no error then it returns *schema.Entries or else an error.

Write Operations

Set key and value

Use SetKeyData() method to set value against key.
(i *ImmuDAO) coreimmudb.SetKeyData(key, value []byte)

  • Pass key and value as argument to the above method.
  • It returns (*schema.TxHeader, error) - If no error then it returns *schema.TxHeader or else an error.

Set key and value with additional server-provided proof validation

Use SetVerifiedKeyData() method to set value against key with additional server-provided proof validation..
(i *ImmuDAO) coreimmudb.SetVerifiedKeyData(key, value []byte)

  • Pass key and value as argument to the above method.
  • It returns (*schema.TxHeader, error) - If no error then it returns *schema.TxHeader or else an error.

Set multiple key and value pairs

Use SetAllKeysData() method to set multiple key, value pairs.
(i *ImmuDAO) coreimmudb.SetAllKeysData(kv []KeyValue)

  • Pass array of key and value as argument to the above method.
  • It returns (*schema.TxHeader, error) - If no error then it returns *schema.TxHeader or else an error.

Set key and value with expiry time

Use ExpirableKeySet() method to set value against key with expiration time.
(i *ImmuDAO) coreimmudb.ExpirableKeySet(key, value []byte, expiresAt time.Time)

  • Pass key, value and expiresAt as argument to the above method.
  • It returns (*schema.TxHeader, error) - If no error then it returns *schema.TxHeader or else an error.

Delete Operations

Logically(soft) delete key and value

Use DeleteKey() method to soft delete key and its associated value.
(i *ImmuDAO) coreimmudb.DeleteKey(keys [][]byte)

  • Pass array of keys as argument to the above method.
  • It returns (*schema.TxHeader, error) - If no error then it returns *schema.TxHeader or else an error.

Delete Database

Use DeleteDatabase() method to remove database from ImmuDB.
(i *ImmuDAO) coreimmudb.DeleteDatabase(dbName string)

  • Pass dbName as argument to the above method.
  • It returns (*schema.DeleteDatabaseResponse, error) - If no error then it returns *schema.DeleteDatabaseResponse or else an error.

Documentation

Index

Examples

Constants

View Source
const (
	AdminPermission     = auth.PermissionAdmin
	ReadPermission      = auth.PermissionR
	ReadWritePermission = auth.PermissionRW
)

Variables

View Source
var (
	DefaultHostName string // Holds default hostname

)

Functions

func AddDBConnection added in v1.2.11

func AddDBConnection(host ImmuHost) error

AddDBConnection - Initializes single connection of ImmuDB server using ImmuHost data

Example
host1 := ImmuHost{HostName: "Host1", Server: "127.0.0.1", Port: 3322, Database: "defaultdb", Username: "username", Password: "password", Dir: "./immudb", IsDefault: true}
// Establishing database connection for above host details
err := AddDBConnection(host1)
if err != nil {
	loggermdl.LogError(err)
	return
}
loggermdl.LogInfo("Immudb single connection successfully established!")
Output:

func DeleteImmuDbSession

func DeleteImmuDbSession(hostName string) error

DeleteImmuDbSession - Disconnecting Immu Database connection

Example
// Connecting to the Immudb
host1 := ImmuHost{HostName: "Host1", Server: "127.0.0.1", Port: 3322, Database: "defaultdb", Username: "username", Password: "password", Dir: "./immudb", IsDefault: true}
// Establishing database connection
err := InitImmuDBConnections([]ImmuHost{host1})
if err != nil {
	loggermdl.LogError(err)
	return
}

// Closing database connection (session)
err = DeleteImmuDbSession(host1.HostName)
if err != nil {
	loggermdl.LogError(err)
	return
}
loggermdl.LogInfo(host1.HostName + " connection closed!")
Output:

func GetImmuDbConnection

func GetImmuDbConnection(hostName string) (immudb.ImmuClient, error)

Get ImmuDB connection - immudb.ImmuClient

Example
// Establishing connection to Immudb
host1 := ImmuHost{HostName: "Host1", Server: "127.0.0.1", Port: 3322, Database: "defaultdb", Username: "username", Password: "password", Dir: "./immudb", IsDefault: true}
err := InitImmuDBConnections([]ImmuHost{host1})
if err != nil {
	loggermdl.LogError(err)
	return
}

// Getting immudb.ImmuClient
client, err := GetImmuDbConnection(host1.HostName)
if err != nil {
	loggermdl.LogError(err)
	return
}

_ = client
Output:

func InitImmuDBConnections

func InitImmuDBConnections(hosts []ImmuHost) error

InitNewImmuDbSession - Initializes connection to ImmuDB server using []ImmuHost data

Example
host1 := ImmuHost{HostName: "Host1", Server: "127.0.0.1", Port: 3322, Database: "defaultdb", Username: "username", Password: "password", Dir: "./immudb", IsDefault: true}
host2 := ImmuHost{HostName: "Host2", Server: "127.0.0.1", Port: 3322, Database: "database1", Username: "username", Password: "password", Dir: "./immudb"}
// Establishing database connection
err := InitImmuDBConnections([]ImmuHost{host1, host2})
if err != nil {
	loggermdl.LogError(err)
	return
}
loggermdl.LogInfo("Immudb connection established!")
Output:

func InitUsingJson

func InitUsingJson(filePath string) error

InitUsingJsonFile - Initializes connection to ImmuDB server using json config file

Example
filePath := "./dbconfig.json"
// Establishing connection using JSON file
err := InitUsingJson(filePath)
if err != nil {
	loggermdl.LogError(err)
	return
}
loggermdl.LogInfo("Immudb connection successfully established!")
Output:

func TestDbConnection

func TestDbConnection(host ImmuHost) error

TestImmuDbConnection - Connects to Immudb with provided Database host details, if failed then error is returned or else nil.

Example
host1 := ImmuHost{HostName: "Host1", Server: "127.0.0.1", Port: 3322, Database: "defaultdb", Username: "username", Password: "password", Dir: "./immudb", IsDefault: true}
err := TestDbConnection(host1)
if err != nil {
	loggermdl.LogError(err)
	return
}

loggermdl.LogInfo("Test connection successful!")
Output:

Types

type GetOptions

type GetOptions struct {
	AtTx       uint64 `json:"atTx"`
	SinceTx    uint64 `json:"sinceTx"`
	NoWait     bool   `json:"noWait"`
	AtRevision int64  `json:"atRevision"`
}

type ImmuDAO

type ImmuDAO struct {
	HostName string
	MetaData MetaData
}

func GetImmuDAOWithHost

func GetImmuDAOWithHost(hostname string) *ImmuDAO

GetImmuDAOWithHost - return Immu DAO instance for provided host

For default ImmuDB DAO:
	Pass empty string - coreimmudb.GetImmuDAOWithHost("")
								OR
	Use DefaultHostName - coreimmudb.DefaultHostName
Example
// Establishing connection to Immudb
host1 := ImmuHost{HostName: "Host1", Server: "127.0.0.1", Port: 3322, Database: "defaultdb", Username: "username", Password: "password", Dir: "./immudb", IsDefault: true}
err := InitImmuDBConnections([]ImmuHost{host1})
if err != nil {
	loggermdl.LogError(err)
	return
}

// For getting specific connection immudb Data Access Object(DAO), just provide connection hostname.
immuDAO := GetImmuDAOWithHost(host1.HostName)

// For getting default connection Data Access Object(DAO)
immuDAO = GetImmuDAOWithHost(DefaultHostName)

_ = immuDAO
Output:

func (*ImmuDAO) CreateDatabase

func (i *ImmuDAO) CreateDatabase(dbName string, dbSettings *schema.DatabaseNullableSettings) (*schema.CreateDatabaseResponse, error)

CreateDatabase - Creates new database in ImmuDB, current database user requires SysAdmin permission level.

func (*ImmuDAO) CreateUser

func (i *ImmuDAO) CreateUser(username, password, dbName string, permission int) error

CreateUser - Creates new user

username - Username of the new user password - Password of the new user (Password must have between 8 and 32 letters, digits and special characters of which at least 1 uppercase letter, 1 digit and 1 special character.) dbName - Database name

permission: 1 (coreimmudb.ReadPermission) - read-only access 2 (coreimmudb.ReadWritePermission) - read-write access 254 (coreimmudb.AdminPermission) - read-write with admin rights

func (*ImmuDAO) DeleteDatabase

func (i *ImmuDAO) DeleteDatabase(dbName string) (*schema.DeleteDatabaseResponse, error)

DeleteDatabase - Removes existing database from ImmuDB

func (*ImmuDAO) DeleteKey

func (i *ImmuDAO) DeleteKey(keys [][]byte) (*schema.TxHeader, error)

DeleteKey - Key is deleted logically from Database, physically it is present in database

func (*ImmuDAO) ExpirableKeySet

func (i *ImmuDAO) ExpirableKeySet(key, value []byte, expiresAt time.Time) (*schema.TxHeader, error)

ExpirableKeySet - Sets value for the key with expiration time

func (*ImmuDAO) GetActiveKeys

func (i *ImmuDAO) GetActiveKeys() (*schema.Entries, error)

GetActiveKeys - List all avaliable keys from active database, this function does not retrive deleted keys

- Use scan options for advance filtering as shown below

immuDAO.MetaData.ScanOpts = schema.ScanRequest{Desc: true, Limit: 10}
NOTE: 'immuDAO' is Data access object; To get Data access object use coreimmudb.GetImmuDAOWithHost("hostname")

Scan options field description:

SeekKey - List all keys which were inserted/saved after the specified key, include specified key in result if InclusiveSeek = True
EndKey - List all keys which were inserted/saved before the specified key, include specified key in result if InclusiveEnd = True
Prefix - List all keys which are perfixed with given character(s)
Desc - Sorting in descending order
Limit - Maximum numbers of entries to return
SinceTx - Used to avoid waiting for the indexer to be up-to-date with the most recent transaction
NoWait (True/False) - If set to true, then the server will not wait for the indexer to	be up-to-date with the most recent transaction
InclusiveSeek (True/False)
InclusiveEnd (True/False)
Offset - Number of entries to skip

func (*ImmuDAO) GetAllKeysData

func (i *ImmuDAO) GetAllKeysData(keys [][]byte) (*schema.Entries, error)

GetAllKeysData - Getting all keys data

GetAllKeysData retrives value for provided keys,
values will be nil, for those keys which are not present in immudb

func (*ImmuDAO) GetKeyData

func (i *ImmuDAO) GetKeyData(key []byte) (*schema.Entry, error)

GetKeyData - Get single value for provided key

Use GetOptions for advance filtering as show below;

immuDAO.MetaData.GetOpts = coreimmudb.GetOptions{AtTx: 0, AtRevision: 0, SinceTx: 0, NoWait: true}

NOTE: 'immuDAO' is Data access object; To get Data access object use coreimmudb.GetImmuDAOWithHost("hostname")

func (*ImmuDAO) GetKeyHistory

func (i *ImmuDAO) GetKeyHistory(key []byte, offset uint64, limit int32, desc bool) (*schema.Entries, error)

GetKeyHistory - Get history of single key

Offset - Number of entries to skip
Limit - Maximum numbers of entries to return
Desc - Sorting in descending order

func (*ImmuDAO) GetVerifiedKeyData

func (i *ImmuDAO) GetVerifiedKeyData(key []byte) (*schema.Entry, error)

GetVerifiedKeyData - Get single value for provided key with additional server-provided proof validation.

Use GetOptions for advance filtering as show below;

immuDAO.MetaData.GetOpts = coreimmudb.GetOptions{AtTx: 0, AtRevision: 0, SinceTx: 0, NoWait: true}

NOTE: 'immuDAO' is Data access object; To get Data access object use coreimmudb.GetImmuDAOWithHost("hostname")

func (*ImmuDAO) ListDatabases

func (i *ImmuDAO) ListDatabases() (*schema.DatabaseListResponseV2, error)

ListDatabases - returns a list of databases the user has access.

func (*ImmuDAO) ListUsers

func (i *ImmuDAO) ListUsers() (*schema.UserList, error)

ListUsers - List all database of user

This call requires Admin or SysAdmin permission level.

When called as a SysAdmin user, all users in the database are returned. When called as an Admin user, users for currently selected database are returned.

func (*ImmuDAO) SetAllKeysData

func (i *ImmuDAO) SetAllKeysData(kv []KeyValue) (*schema.TxHeader, error)

SetAllKeysData - Set multiple keys with their values in a single transaction.

func (*ImmuDAO) SetKeyData

func (i *ImmuDAO) SetKeyData(key, value []byte) (*schema.TxHeader, error)

SetKeyData - Commits provided value for provided key

func (*ImmuDAO) SetVerifiedKeyData

func (i *ImmuDAO) SetVerifiedKeyData(key, value []byte) (*schema.TxHeader, error)

SetVerifiedKeyData - Commits provided value for provided key and also requests a server-generated proof

type ImmuHost

type ImmuHost struct {
	HostName       string `json:"hostName"`       // Connection name
	Server         string `json:"server"`         // Database server address
	Port           int    `json:"port"`           // Database port
	Database       string `json:"database"`       // Database name
	Username       string `json:"username"`       // Database username
	Password       string `json:"password"`       // Database password
	Dir            string `json:"dir"`            // Storing .identity (database server identity) and .state file
	MaxRecvMsgSize int    `json:"maxRecvMsgSize"` // Recieve message maximum size in MB (Default: 4MB)
	IsDefault      bool   `json:"isDefault"`      // Default ImmuDB connection
	IsDisabled     bool   `json:"isDisabled"`     // If true connection then connection to database server is skipped
}

type KeyValue

type KeyValue struct {
	Key   []byte `json:"key"`
	Value []byte `json:"value"`
}

For setting multiple keys - to know more see SetAllKeysData

type MetaData

type MetaData struct {
	GetOpts  GetOptions
	ScanOpts schema.ScanRequest
}

Jump to

Keyboard shortcuts

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