Documentation
¶
Index ¶
- Constants
- Variables
- func ConvertSQLCommands(lines []string) []string
- func Debug(msg string, fields ...Field)
- func FormatError(err error) string
- func Info(msg string, fields ...Field)
- func InterfaceToSQLString(interfaceVal interface{}) string
- func IsORMError(err error) bool
- func LogError(msg string, fields ...Field)
- func LogErrorWithContext(err error, fields ...Field)
- func NewError(message, operation, table string) error
- func PrintDebug(msg string)
- func SecondToMs(s float64) float64
- func SecondToMsString(s float64) string
- func SetDefaultLogger(logger Logger)
- func ToInsertSQLRawFromSlice(records []DBRecord) []string
- func TotalTimeElapsedInSecond(reses []BasicSQLResult) float64
- func ValidateFieldName(fieldName string) error
- func ValidateOperator(operator string) error
- func ValidateTableName(tableName string) error
- func Warn(msg string, fields ...Field)
- func WrapConnectionError(err error) error
- func WrapDeleteError(err error, table string) error
- func WrapError(err error, operation, table string) error
- func WrapErrorWithFields(err error, operation, table string, fields map[string]interface{}) error
- func WrapErrorWithQuery(err error, operation, table, query string) error
- func WrapInsertError(err error, table string) error
- func WrapSelectError(err error, table string) error
- func WrapTransactionError(err error, operation string) error
- func WrapUpdateError(err error, table string) error
- type BasicSQLResult
- type CommonTableExpression
- type ComplexQuery
- type Condition
- type DBRecord
- type DBRecords
- type DataStruct
- type Database
- type DefaultLogger
- func (l *DefaultLogger) Debug(msg string, fields ...Field)
- func (l *DefaultLogger) Error(msg string, fields ...Field)
- func (l *DefaultLogger) Info(msg string, fields ...Field)
- func (l *DefaultLogger) SetLevel(level LogLevel)
- func (l *DefaultLogger) Warn(msg string, fields ...Field)
- func (l *DefaultLogger) With(fields ...Field) Logger
- type ErrorContext
- type Field
- func Any(key string, value interface{}) Field
- func Bool(key string, value bool) Field
- func Duration(key string, d time.Duration) Field
- func Error(err error) Field
- func F(key string, value interface{}) Field
- func Float64(key string, value float64) Field
- func Int(key string, value int) Field
- func Int64(key string, value int64) Field
- func String(key, value string) Field
- type Join
- type JoinType
- type LogLevel
- type Logger
- type NodeStatusStruct
- type NoopLogger
- func (n *NoopLogger) Debug(msg string, fields ...Field)
- func (n *NoopLogger) Error(msg string, fields ...Field)
- func (n *NoopLogger) Info(msg string, fields ...Field)
- func (n *NoopLogger) SetLevel(level LogLevel)
- func (n *NoopLogger) Warn(msg string, fields ...Field)
- func (n *NoopLogger) With(fields ...Field) Logger
- type ORMError
- type ParametereizedSQL
- type SchemaStruct
- type StatusStruct
- type TableStruct
- type Transaction
Constants ¶
const ( DEFAULT_PAGINATION_LIMIT = 50 DEFAULT_MAX_MULTIPLE_INSERTS = 100 // Maximum number of rows to insert in a single SQL statement )
Variables ¶
var ( // Some global vars are needed so we can change this on the fly later on. // For example: we read the MAX_MULTIPLE_INSERTS from db.settings then // it will be changed on the fly when function that need this variable got called! ErrSQLNoRows medaerror.MedaError = medaerror.MedaError{Message: "select returns no rows"} ErrSQLMoreThanOneRow medaerror.MedaError = medaerror.MedaError{Message: "select returns more than 1 rows"} MAX_MULTIPLE_INSERTS int = DEFAULT_MAX_MULTIPLE_INSERTS // Security: SQL Injection Protection ErrInvalidFieldName medaerror.MedaError = medaerror.MedaError{Message: "invalid field name: must contain only alphanumeric characters and underscores"} ErrInvalidOperator medaerror.MedaError = medaerror.MedaError{Message: "invalid SQL operator: not in allowed list"} ErrEmptyTableName medaerror.MedaError = medaerror.MedaError{Message: "table name cannot be empty"} ErrInvalidTableName medaerror.MedaError = medaerror.MedaError{Message: "invalid table name: must contain only alphanumeric characters and underscores"} ErrEmptyConditionField medaerror.MedaError = medaerror.MedaError{Message: "condition field cannot be empty when operator is specified"} ErrMissingPrimaryKey medaerror.MedaError = medaerror.MedaError{Message: "missing primary key in record data"} ErrSQLMultipleRows medaerror.MedaError = medaerror.MedaError{Message: "query returned multiple rows when expecting one"} )
Functions ¶
func ConvertSQLCommands ¶
Convert the .sql file into each individual sql commands Input is []string which are the content of the .sql file Output is []string of each sql commands.
func FormatError ¶ added in v0.0.4
FormatError formats an error for logging with all available context
func InterfaceToSQLString ¶
func InterfaceToSQLString(interfaceVal interface{}) string
func IsORMError ¶ added in v0.0.4
IsORMError checks if an error is an ORMError
func LogErrorWithContext ¶ added in v0.0.4
LogError logs an error with the default logger
func NewError ¶ added in v0.0.4
NewError creates a new medaerror with a message and wraps it with ORM context
func SecondToMs ¶
func SecondToMsString ¶
func SetDefaultLogger ¶ added in v0.0.4
func SetDefaultLogger(logger Logger)
SetDefaultLogger sets the global default logger used by SimpleORM
func ToInsertSQLRawFromSlice ¶
ToInsertSQLRawFromSlice converts a slice of DBRecord to a slice of raw SQL statements by converting to DBRecords first
func TotalTimeElapsedInSecond ¶
func TotalTimeElapsedInSecond(reses []BasicSQLResult) float64
Get all sum timing
func ValidateFieldName ¶ added in v0.0.4
ValidateFieldName validates a field/column name to prevent SQL injection. It checks that the name contains only alphanumeric characters and underscores. The name must start with a letter or underscore.
Usage:
if err := ValidateFieldName("user_id"); err != nil {
return err
}
Returns: error if validation fails, nil otherwise
func ValidateOperator ¶ added in v0.0.4
ValidateOperator validates a SQL operator against a whitelist to prevent SQL injection. It checks if the operator is in the allowed list of safe SQL operators.
Usage:
if err := ValidateOperator("="); err != nil {
return err
}
Returns: error if validation fails, nil otherwise
func ValidateTableName ¶ added in v0.0.4
ValidateTableName validates a table name to prevent SQL injection. It checks that the name is not empty and contains only alphanumeric characters and underscores. The name must start with a letter or underscore.
Usage:
if err := ValidateTableName("users"); err != nil {
return err
}
Returns: error if validation fails, nil otherwise
func WrapConnectionError ¶ added in v0.0.4
WrapConnectionError wraps a connection-related error
func WrapDeleteError ¶ added in v0.0.4
WrapDeleteError wraps a DELETE operation error
func WrapErrorWithFields ¶ added in v0.0.4
WrapErrorWithFields wraps an error with additional field context
func WrapErrorWithQuery ¶ added in v0.0.4
WrapErrorWithQuery wraps an error with context including the SQL query
func WrapInsertError ¶ added in v0.0.4
WrapInsertError wraps an INSERT operation error
func WrapSelectError ¶ added in v0.0.4
WrapSelectError wraps a SELECT operation error
func WrapTransactionError ¶ added in v0.0.4
WrapTransactionError wraps a transaction-related error
func WrapUpdateError ¶ added in v0.0.4
WrapUpdateError wraps an UPDATE operation error
Types ¶
type BasicSQLResult ¶
mostly used for rawSQL execution, this is the return, empty if it's not applicable This is not for query where we return usually DBRecord or DBRecords / []DBRecord
type CommonTableExpression ¶ added in v0.1.0
type CommonTableExpression struct {
Name string `json:"name"` // CTE name (required)
Columns []string `json:"columns,omitempty"` // Optional column list
Query *ComplexQuery `json:"query,omitempty"` // Structured query for CTE
RawSQL string `json:"raw_sql,omitempty"` // Raw SQL for complex CTEs
Recursive bool `json:"recursive,omitempty"` // Whether this is a recursive CTE
}
CommonTableExpression represents a CTE (WITH clause) in SQL. CTEs allow you to define temporary named result sets that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement.
Example:
cte := CommonTableExpression{
Name: "active_users",
Query: &ComplexQuery{
Select: []string{"id", "name", "email"},
From: "users",
Where: &Condition{Field: "status", Operator: "=", Value: "active"},
},
}
func (*CommonTableExpression) ToSQL ¶ added in v0.1.0
func (cte *CommonTableExpression) ToSQL() (string, []interface{}, error)
ToSQL converts a CTE to its SQL representation
type ComplexQuery ¶ added in v0.1.0
type ComplexQuery struct {
Select []string `json:"select,omitempty"` // Fields to select (default: ["*"])
Distinct bool `json:"distinct,omitempty"` // Add DISTINCT keyword
From string `json:"from"` // Main table name (required)
FromAlias string `json:"from_alias,omitempty"` // Alias for main table
Joins []Join `json:"joins,omitempty"` // JOIN clauses
Where *Condition `json:"where,omitempty"` // WHERE conditions
GroupBy []string `json:"group_by,omitempty"` // GROUP BY fields
Having string `json:"having,omitempty"` // HAVING clause (raw SQL)
OrderBy []string `json:"order_by,omitempty"` // ORDER BY fields
Limit int `json:"limit,omitempty"` // LIMIT value
Offset int `json:"offset,omitempty"` // OFFSET value
CTEs []CommonTableExpression `json:"ctes,omitempty"` // Structured CTEs (recommended)
CTERaw string `json:"cte_raw,omitempty"` // Raw CTE string (for backward compatibility)
}
ComplexQuery represents a complex SQL query structure that supports: - Custom SELECT fields (not just SELECT *) - Multiple table JOINs - Complex WHERE conditions (using Condition struct) - GROUP BY with HAVING clauses - ORDER BY, LIMIT, OFFSET - DISTINCT, CTEs (structured and raw), and subqueries
Example usage:
query := ComplexQuery{
Select: []string{"users.id", "users.name", "COUNT(orders.id) as order_count"},
From: "users",
Joins: []Join{
{Type: LeftJoin, Table: "orders", Condition: "users.id = orders.user_id"},
},
Where: &Condition{
Field: "users.status",
Operator: "=",
Value: "active",
},
GroupBy: []string{"users.id", "users.name"},
Having: "COUNT(orders.id) > 5",
OrderBy: []string{"order_count DESC"},
Limit: 10,
}
func (*ComplexQuery) ToSQL ¶ added in v0.1.0
func (cq *ComplexQuery) ToSQL() (string, []interface{}, error)
ToSQL converts a ComplexQuery to a SQL query string with parameterized values. Security: Validates table names, field names, and uses parameterized queries.
Returns:
- string: Complete SQL query with placeholders
- []interface{}: Values for the parameterized query
- error: Validation error if any field is invalid
type Condition ¶
type Condition struct {
Field string `json:"field,omitempty" db:"field"`
Operator string `json:"operator,omitempty" db:"operator"`
Value interface{} `json:"value,omitempty" db:"value"`
Logic string `json:"logic,omitempty" db:"logic"` // "AND" or "OR"
Nested []Condition `json:"nested,omitempty" db:"nested"` // For nested conditions
OrderBy []string `json:"order_by,omitempty" db:"order_by"` // Fields to order by
GroupBy []string `json:"group_by,omitempty" db:"group_by"` // Fields to group by
Limit int `json:"limit,omitempty" db:"limit"` // Limit for pagination
Offset int `json:"offset,omitempty" db:"offset"` // Offset for pagination
}
Condition struct for query filtering with JSON and DB tags This struct is used to define conditions for filtering data in queries. It supports various operations like AND, OR, and nested conditions. Sample usage:
// Simple condition
condition := Condition{
Field: "age",
Operator: ">",
Value: 18,
}
// Output: WHERE age > 18
// Nested condition with AND logic
condition := Condition{
Logic: "AND",
Nested: []Condition{
Condition{Field: "age", Operator: ">", Value: 18},
Condition{Field: "status", Operator: "=", Value: "active"},
},
}
// Output: WHERE (age > 18 AND status = 'active')
// Nested condition with OR logic
condition := Condition{
Logic: "OR",
Nested: []Condition{
Condition{Field: "status", Operator: "=", Value: "pending"},
Condition{Field: "status", Operator: "=", Value: "review"},
},
}
// Output: WHERE (status = 'pending' OR status = 'review')
// Complex condition with nested AND and OR
condition := Condition{
Logic: "OR",
Nested: []Condition{
Condition{
Logic: "AND",
Nested: []Condition{
Condition{Field: "age", Operator: ">", Value: 18},
Condition{Field: "country", Operator: "=", Value: "USA"},
},
},
Condition{
Logic: "AND",
Nested: []Condition{
Condition{Field: "status", Operator: "=", Value: "active"},
Condition{Field: "role", Operator: "=", Value: "admin"},
},
},
},
}
// Output: WHERE ((age > 18 AND country = 'USA') OR (status = 'active' AND role = 'admin'))
func (*Condition) And ¶
And creates a new Condition with AND logic for the given conditions. This method allows chaining multiple conditions together with AND logic. Usage:
condition.And(
Condition{Field: "age", Operator: ">", Value: 18},
Condition{Field: "status", Operator: "=", Value: "active"}
)
Returns: A new Condition with nested conditions joined by AND
func (*Condition) Or ¶
Or creates a new Condition with OR logic for the given conditions. This method allows chaining multiple conditions together with OR logic. Usage:
condition.Or(
Condition{Field: "status", Operator: "=", Value: "pending"},
Condition{Field: "status", Operator: "=", Value: "review"}
)
Returns: A new Condition with nested conditions joined by OR
func (*Condition) ToSelectString ¶
ToSelectString generates a complete SELECT SQL query string with WHERE, GROUP BY, ORDER BY, and LIMIT/OFFSET clauses based on the Condition struct. Security: Validates table name and delegates to ToWhereString for field/operator validation. Usage:
query, values, err := condition.ToSelectString("users")
if err != nil {
return "", nil, err
}
Returns:
- string: Complete SELECT query (e.g., "SELECT * FROM users WHERE age > ? ORDER BY name LIMIT 10")
- []interface{}: Slice of values for the parameterized query
- error: Validation error if table name, field name, or operator is invalid
func (*Condition) ToWhereString ¶
ToWhereString converts a Condition struct into a WHERE clause string and parameter values. It handles nested conditions recursively and supports both AND/OR logic. Security: Validates field names and operators to prevent SQL injection attacks. Usage:
whereClause, values, err := condition.ToWhereString()
if err != nil {
return "", nil, err
}
Returns:
- string: SQL WHERE clause with parameterized queries (e.g., "field1 = ? AND (field2 > ?)")
- []interface{}: Slice of values corresponding to the parameters
- error: Validation error if field name or operator is invalid
type DBRecord ¶
func TableStructToDBRecord ¶
func TableStructToDBRecord(obj TableStruct) (DBRecord, error)
func (*DBRecord) FromStruct ¶
func (d *DBRecord) FromStruct(obj TableStruct) error
FromStruct converts a TableStruct object to a DBRecord. It maps the struct fields to the DBRecord's Data map and sets the table name. Usage:
var record DBRecord record.FromStruct(userStruct)
Returns: error if conversion fails
func (*DBRecord) ToInsertSQLParameterized ¶
Convert DBRecord to SQL Insert string and values but with placeholder (parameterized) ToInsertSQLParameterized converts a single DBRecord to a parameterized INSERT SQL statement. Usage:
sql, values := record.ToInsertSQLParameterized()
Returns:
- string: Parameterized INSERT query (e.g., "INSERT INTO table (col1, col2) VALUES (?, ?)")
- []interface{}: Slice of values for the parameters
func (*DBRecord) ToInsertSQLRaw ¶
Convert DBRecord to SQL Insert string and values ToInsertSQLRaw converts a single DBRecord to a raw INSERT SQL statement with values. Usage:
sql, values := record.ToInsertSQLRaw()
Returns:
- string: Complete INSERT query with values (e.g., "INSERT INTO table (col1, col2) VALUES ('value1', 2)")
- []interface{}: Slice of original values (for reference)
type DBRecords ¶
type DBRecords []DBRecord
func DBRecordsFromSlice ¶
DBRecordsFromSlice converts a slice of DBRecord to DBRecords type and uses the DBRecords methods
func (*DBRecords) Append ¶
Append adds a new DBRecord to the DBRecords slice. Usage:
records.Append(newRecord)
func (DBRecords) ToInsertSQLParameterized ¶
func (records DBRecords) ToInsertSQLParameterized() []ParametereizedSQL
NOTE: For not same tables that are in DBRecords then use the DBRecord.ToInsertSQLParameterized() function for each record in DBRecords.
BULK inserts, one is parameterized and non-parameterized (just plain raw SQL) This is always for same table only, not for different tables!
ToInsertSQLParameterized converts multiple DBRecords to a slice of parameterized INSERT statements. It automatically batches inserts according to MAX_MULTIPLE_INSERTS limit. Usage:
statements := records.ToInsertSQLParameterized()
Returns: Slice of ParametereizedSQL containing batched INSERT statements and their values
func (DBRecords) ToInsertSQLRaw ¶
ToInsertSQLRaw converts multiple DBRecords to a slice of raw INSERT SQL statements. It automatically batches inserts according to MAX_MULTIPLE_INSERTS limit. Usage:
statements := records.ToInsertSQLRaw()
Returns: Slice of strings containing complete INSERT statements with values
type DataStruct ¶
type DataStruct struct {
TypeDef string // string | int | bool | etc
Value interface{}
Empty bool // this to replace the nil value if data is not set
}
TODO: replace the DBRecord.Data to be map[string]DataStruct . this will be more robust and flexible
type Database ¶
type Database interface {
GetSchema(bool, bool) []SchemaStruct
Status() (NodeStatusStruct, error)
SelectOne(string) (DBRecord, error) // This is almost unusable, very rare case
SelectMany(string) (DBRecords, error) // This is almost unusable, very rare case (this is like select ALL rows from the table)
SelectOneWithCondition(string, *Condition) (DBRecord, error)
SelectManyWithCondition(string, *Condition) ([]DBRecord, error)
SelectManyComplex(*ComplexQuery) ([]DBRecord, error) // Complex queries with JOINs, custom fields, GROUP BY, etc.
SelectOneComplex(*ComplexQuery) (DBRecord, error) // Complex query that must return exactly one row
SelectOneSQL(string) (DBRecords, error) // select using one sql statement
SelectManySQL([]string) ([]DBRecords, error) // select using many sql statements
SelectOnlyOneSQL(string) (DBRecord, error) // select only returning 1 row, and also check if actually more than 1 return errors
SelectOneSQLParameterized(ParametereizedSQL) (DBRecords, error) // select using one parameterized sql statement
SelectManySQLParameterized([]ParametereizedSQL) ([]DBRecords, error) // select using many parameterized sql statements
SelectOnlyOneSQLParameterized(ParametereizedSQL) (DBRecord, error) // select only returning 1 row, and also check if actually more than 1 return errors
ExecOneSQL(string) BasicSQLResult
ExecOneSQLParameterized(ParametereizedSQL) BasicSQLResult
ExecManySQL([]string) ([]BasicSQLResult, error)
ExecManySQLParameterized([]ParametereizedSQL) ([]BasicSQLResult, error)
InsertOneDBRecord(DBRecord, bool) BasicSQLResult
InsertManyDBRecords([]DBRecord, bool) ([]BasicSQLResult, error)
InsertManyDBRecordsSameTable([]DBRecord, bool) ([]BasicSQLResult, error)
// TableStruct is less practical
InsertOneTableStruct(TableStruct, bool) BasicSQLResult
InsertManyTableStructs([]TableStruct, bool) ([]BasicSQLResult, error)
// Status and Health check
IsConnected() bool
Leader() (string, error) // this was originally for RQLite, if not then just return empty string or "not implemented"
Peers() ([]string, error) // this was originally for RQLite, if not then just return empty string or "not implemented"
// Transaction management
BeginTransaction() (Transaction, error) // Begin a new transaction
}
type DefaultLogger ¶ added in v0.0.4
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger is a simple implementation of the Logger interface It uses Go's standard log package with structured field formatting
func NewDefaultLogger ¶ added in v0.0.4
func NewDefaultLogger(minLevel LogLevel) *DefaultLogger
NewDefaultLogger creates a new default logger with the specified minimum level
func (*DefaultLogger) Debug ¶ added in v0.0.4
func (l *DefaultLogger) Debug(msg string, fields ...Field)
Debug logs a debug-level message
func (*DefaultLogger) Error ¶ added in v0.0.4
func (l *DefaultLogger) Error(msg string, fields ...Field)
Error logs an error-level message
func (*DefaultLogger) Info ¶ added in v0.0.4
func (l *DefaultLogger) Info(msg string, fields ...Field)
Info logs an info-level message
func (*DefaultLogger) SetLevel ¶ added in v0.0.4
func (l *DefaultLogger) SetLevel(level LogLevel)
SetLevel sets the minimum log level
func (*DefaultLogger) Warn ¶ added in v0.0.4
func (l *DefaultLogger) Warn(msg string, fields ...Field)
Warn logs a warning-level message
func (*DefaultLogger) With ¶ added in v0.0.4
func (l *DefaultLogger) With(fields ...Field) Logger
With creates a new logger with pre-populated fields
type ErrorContext ¶ added in v0.0.4
type ErrorContext struct {
Operation string // The operation that failed (e.g., "SELECT", "INSERT")
Table string // The table involved (if applicable)
Query string // The SQL query (if applicable)
Fields map[string]interface{} // Additional context fields
}
ErrorContext provides additional context for errors
func GetErrorContext ¶ added in v0.0.4
func GetErrorContext(err error) (ErrorContext, bool)
GetErrorContext extracts the error context if the error is an ORMError
type Field ¶ added in v0.0.4
type Field struct {
Key string
Value interface{}
}
Field represents a structured logging field (key-value pair)
type Join ¶ added in v0.1.0
type Join struct {
Type JoinType `json:"type"` // Type of join (INNER, LEFT, RIGHT, FULL, CROSS)
Table string `json:"table"` // Table to join
Alias string `json:"alias,omitempty"` // Optional table alias
Condition string `json:"condition,omitempty"` // Join condition (e.g., "users.id = orders.user_id")
}
Join represents a SQL JOIN clause
type JoinType ¶ added in v0.1.0
type JoinType string
JoinType represents the type of SQL JOIN operation
type LogLevel ¶ added in v0.0.4
type LogLevel int
LogLevel represents the severity level of a log message
type Logger ¶ added in v0.0.4
type Logger interface {
// Debug logs a debug-level message with optional fields
Debug(msg string, fields ...Field)
// Info logs an info-level message with optional fields
Info(msg string, fields ...Field)
// Warn logs a warning-level message with optional fields
Warn(msg string, fields ...Field)
// Error logs an error-level message with optional fields
Error(msg string, fields ...Field)
// With creates a new logger with the given fields pre-populated
With(fields ...Field) Logger
// SetLevel sets the minimum log level
SetLevel(level LogLevel)
}
Logger is the interface for structured logging in SimpleORM Implementations can use any logging library (zap, logrus, zerolog, etc.)
func GetDefaultLogger ¶ added in v0.0.4
func GetDefaultLogger() Logger
GetDefaultLogger returns the current default logger
func NewNoopLogger ¶ added in v0.0.4
func NewNoopLogger() Logger
NewNoopLogger creates a logger that doesn't log anything (useful for testing)
type NodeStatusStruct ¶
type NodeStatusStruct struct {
StatusStruct
Peers map[int]StatusStruct // all peers including the leader
}
NodeStatusStruct is a struct that contains the status of a node, including its peers (if has peers) It is mostly derived from the SettingsTable but is used for response. Mode is : r , w, or rw (for read only, write only and read and write) Example of how to use it:
var nodeStatus NodeStatusStruct
nodeStatus.StatusStruct = StatusStruct{...}
nodeStatus.Peers = map[int]StatusStruct{...}
Output:
{
"url": "http://localhost:4001",
"version": "3.5.0",
"start_time": "2022-01-01T00:00:00Z",
"uptime": "24h0m0s",
"dir_size": 1024,
"db_size": 2048,
"node_id": "node1",
"is_leader": true,
"leader": "node1",
"last_backup": "2022-01-01T00:00:00Z",
"mode": "standalone",
"nodes": 1,
"node_number": 1,
"peers": {
2: {
"url": "http://localhost:4002",
"version": "3.5.0",
"start_time": "2022-01-01T00:00:00Z",
"uptime": "24h0m0s",
"dir_size": 1024,
"db_size": 2048,
"node_id": "node2",
"is_leader": false,
"leader": "node1",
"last_backup": "2022-01-01T00:00:00Z",
"mode": "r",
"nodes": 2,
"node_number": 2
}
}
}
func (*NodeStatusStruct) PrintPretty ¶
func (s *NodeStatusStruct) PrintPretty()
This function is used to print the status of the node in a pretty format, including its peers. Example of how to use it: s.PrintPretty() Output: A formatted string representation of the node's status and its peers. This is mainly for debugging and logging
type NoopLogger ¶ added in v0.0.4
type NoopLogger struct{}
NoopLogger is a logger that doesn't log anything
func (*NoopLogger) Debug ¶ added in v0.0.4
func (n *NoopLogger) Debug(msg string, fields ...Field)
func (*NoopLogger) Error ¶ added in v0.0.4
func (n *NoopLogger) Error(msg string, fields ...Field)
func (*NoopLogger) Info ¶ added in v0.0.4
func (n *NoopLogger) Info(msg string, fields ...Field)
func (*NoopLogger) SetLevel ¶ added in v0.0.4
func (n *NoopLogger) SetLevel(level LogLevel)
func (*NoopLogger) Warn ¶ added in v0.0.4
func (n *NoopLogger) Warn(msg string, fields ...Field)
func (*NoopLogger) With ¶ added in v0.0.4
func (n *NoopLogger) With(fields ...Field) Logger
type ORMError ¶ added in v0.0.4
type ORMError struct {
Err error
Context ErrorContext
}
ORMError wraps an error with additional context
type ParametereizedSQL ¶
type ParametereizedSQL struct {
Query string `json:"query"`
Values []interface{} `json:"values,omitempty"`
}
func SQLAndValuesToParameterized ¶
func SQLAndValuesToParameterized(q string, p []interface{}) ParametereizedSQL
func ToInsertSQLParameterizedFromSlice ¶
func ToInsertSQLParameterizedFromSlice(records []DBRecord) []ParametereizedSQL
ToInsertSQLParameterizedFromSlice converts a slice of DBRecord to a slice of ParametereizedSQL by converting to DBRecords first
type SchemaStruct ¶
type SchemaStruct struct {
ObjectType string `json:"type" db:"type"`
ObjectName string `json:"name" db:"name"`
TableName string `json:"tbl_name" db:"tbl_name"`
RootPage int `json:"rootpage" db:"rootpage"`
SQLCommand string `json:"sql" db:"sql"`
Hidden bool `json:"hidden" db:"hidden"`
}
Struct to get the schema from sqlite_master table in SQLite
func (SchemaStruct) PrintDebug ¶
func (s SchemaStruct) PrintDebug(sql bool)
PrintDebug prints debug information about a database schema object. If sql parameter is true, it includes the SQL command in the output. Usage:
schema.PrintDebug(true)
Output Example:
Object [table] : users[users_table] - CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)
type StatusStruct ¶
type StatusStruct struct {
URL string `json:"url,omitempty" db:"url"` // URL (host + port)
Version string `json:"version,omitempty" db:"version"` // version of the DMBS
DBMS string `json:"dbms,omitempty" db:"dbms"` // version of the DMBS
DBMSDriver string `json:"dbms_driver,omitempty" db:"dbms_driver"` // version of the DMBS
StartTime time.Time `json:"start_time,omitempty" db:"start_time"`
Uptime time.Duration `json:"uptime,omitempty" db:"uptime"`
DirSize int64 `json:"dir_size,omitempty" db:"dir_size"` // if applicable
DBSize int64 `json:"db_size,omitempty" db:"db_size"` // if applicable
NodeID string `json:"node_id,omitempty" db:"node_id"` // DBMS node ID, was rqlite node_id from status
IsLeader bool `json:"is_leader,omitempty" db:"is_leader"`
Leader string `json:"leader,omitempty" db:"leader"` // complete address (including protocol, ie: https://...)
LastBackup time.Time `json:"last_backup,omitempty" db:"last_backup"` // if applicable
Mode string `json:"mode,omitempty" db:"mode"` // options are r, w, or rw
Nodes int `json:"nodes,omitempty" db:"nodes"` // total number of nodes in the cluster
NodeNumber int `json:"node_number,omitempty" db:"node_number"` // this node number, actually this is not applicable in rqlite, because NodeID is string
MaxPool int `json:"max_pool,omitempty" db:"max_pool"` // if applicable
}
Struct to use as per-node status, information mostly from SettingsTable, but this is used for response
func (*StatusStruct) PrintPretty ¶
func (s *StatusStruct) PrintPretty(indent, title string)
This function is used to print the status of a node in a pretty format, mainly for debugging and logging purposes. Example usage: nodeStatus.PrintPretty("", "Node Status") Output: A formatted string representation of the node's status, including URL, version, start time, uptime, directory size, database size, node ID, leadership status, leader ID, last backup time, mode, number of nodes, and node number. This is mainly for debugging and logging
type TableStruct ¶
type TableStruct interface {
TableName() string
}
Make sure other table struct that you use implement this method
type Transaction ¶ added in v0.2.0
type Transaction interface {
// Transaction control
Commit() error // Commit the transaction
Rollback() error // Rollback the transaction
// Execute operations (non-query SQL like INSERT, UPDATE, DELETE)
ExecOneSQL(string) BasicSQLResult
ExecOneSQLParameterized(ParametereizedSQL) BasicSQLResult
ExecManySQL([]string) ([]BasicSQLResult, error)
ExecManySQLParameterized([]ParametereizedSQL) ([]BasicSQLResult, error)
// Select operations (query SQL that returns rows)
SelectOneSQL(string) (DBRecords, error)
SelectOnlyOneSQL(string) (DBRecord, error)
SelectOneSQLParameterized(ParametereizedSQL) (DBRecords, error)
SelectOnlyOneSQLParameterized(ParametereizedSQL) (DBRecord, error)
// Insert operations
InsertOneDBRecord(DBRecord) BasicSQLResult
InsertManyDBRecords([]DBRecord) ([]BasicSQLResult, error)
InsertManyDBRecordsSameTable([]DBRecord) ([]BasicSQLResult, error)
InsertOneTableStruct(TableStruct) BasicSQLResult
InsertManyTableStructs([]TableStruct) ([]BasicSQLResult, error)
}
Transaction provides transaction control similar to database/sql and sqlx It allows explicit control over transaction lifecycle with Commit() and Rollback()