bdatamatrix

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: MIT Imports: 9 Imported by: 0

README

BDataMatrix - Structured Tabular Data Management in Go

License Go Report Card

BDataMatrix is a lightweight Go library for managing structured tabular data efficiently. It provides functions to add, update, delete, sort, and query data, along with various export options such as CSV, TSV, JSON, and YAML.

Installation

To install BDataMatrix, run:

go get github.com/bearaujus/bdatamatrix

Import

import "github.com/bearaujus/bdatamatrix"

Features

  • Create structured tabular data with defined headers.
  • Add, update, delete, and search rows efficiently.
  • Export data to CSV, TSV, JSON, YAML, or custom formats.
  • Track header indices for optimized querying.
  • Support for case-insensitive searching.

Usage

1. Creating a Matrix

Create a new matrix with headers:

matrix, err := bdatamatrix.New("ID", "Name", "Age")
if err != nil {
    log.Fatal(err)
}

Create a matrix with predefined data:

rows := [][]string{
    {"1", "Alice", "30"},
    {"2", "Bob", "25"},
}
matrix, err := bdatamatrix.NewWithData(rows, "ID", "Name", "Age")
if err != nil {
    log.Fatal(err)
}
2. Adding and Querying Rows
_ = matrix.AddRow("3", "Charlie", "35")

query := bdatamatrix.FindRowsQuery{
    Column:          "Name",
    Operator:        bdatamatrix.OperatorEquals,
    CaseInsensitive: true,
    Values:          []string{"Alice"},
}

result, err := matrix.FindRows(query)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Matched rows:", result)
3. Exporting Data

Export as CSV:

csvOutput := matrix.ToCSV(true)
_ = csvOutput.Write("output.csv", 0644)

Export as JSON:

jsonOutput := matrix.ToJSON(true, false)
_ = jsonOutput.Write("output.json", 0644)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyHeader is returned when no header is provided.
	ErrEmptyHeader = errors.New("empty header")

	// ErrDuplicateHeader is returned when a duplicate header is encountered.
	ErrDuplicateHeader = errors.New("duplicate header")

	// ErrRowIndexOutOfRange is returned when the specified row index is invalid.
	ErrRowIndexOutOfRange = errors.New("row index out of range")

	// ErrColumnNotFound is returned when a specified column does not exist.
	ErrColumnNotFound = errors.New("column not found")

	// ErrNoRowsFound is returned when no rows match the query criteria.
	ErrNoRowsFound = errors.New("no rows found matching criteria")

	// ErrDeleteLastColumn is returned when try to delete the last column.
	ErrDeleteLastColumn = errors.New("unable to delete last column")
)

Functions

This section is empty.

Types

type BDataMatrix

type BDataMatrix interface {
	// AddRow appends a single row to the matrix.
	//
	// Parameters:
	//   - values: The values for the row to be added.
	//
	// Returns:
	//   - An error if writing fails.
	AddRow(values ...string) error

	// AddRows appends multiple rows to the matrix.
	//
	// Parameters:
	//   - values: The values for the multiple rows to be added.
	//
	// Returns:
	//   - An error if writing fails.
	AddRows(rows ...[]string) error

	// GetRow retrieves a row by index.
	//
	// Parameters:
	//   - index: The index of the row to retrieve.
	//
	// Returns:
	// 	 - The value of row at the specified index.
	//   - An error if query fails.
	GetRow(index int) ([]string, error)

	// GetRows retrieves multiple rows by indexes.
	//
	// Parameters:
	//   - indexes: More than one index of the rows to retrieve.
	//
	// Returns:
	// 	 - The value of rows at the specified indexes.
	//   - An error if query fails.
	GetRows(indexes ...int) (BDataMatrix, error)

	// GetColumn retrieves a column by name.
	//
	// Parameters:
	//   - key: The name of the column to retrieve.
	//
	// Returns:
	// 	 - The value of column at the specified key.
	//   - An error if query fails.
	GetColumn(key string) ([]string, error)

	// GetColumns retrieves multiple columns by names.
	//
	// Parameters:
	//   - key: The names of the columns to retrieve.
	//
	// Returns:
	// 	 - The value of columns at the specified keys.
	//   - An error if writing fails.
	GetColumns(keys ...string) (BDataMatrix, error)

	// UpdateRow updates an existing row at the specified index.
	//
	// Parameters:
	//   - index: The index of the row want to be updated.
	//   - values: The value that want to be updated.
	//
	// Returns:
	//   - An error if writing fails.
	UpdateRow(index int, values ...string) error

	// DeleteRow removes a row at the specified index.
	//
	// Parameters:
	//   - index: The index of the row want to be deleted.
	//
	// Returns:
	//   - An error if writing fails.
	DeleteRow(index int) error

	// FindRows searches for rows matching a given query.
	//
	// Parameters:
	//   - query: Have struct FindRowsQuery need to be filled.
	// Returns:
	//   - The value based on parameter query.
	//   - An error if query fails.
	FindRows(query FindRowsQuery) (BDataMatrix, error)

	// SortByDesc sorts rows by descending based on one or more column names.
	//
	// Parameters:
	//   - keys : The names of the columns to sorting.
	// Returns:
	//   - An error if query fails.
	SortByDesc(keys ...string) error

	// SortByAsc sorts rows by ascending based on one or more column names.
	//
	// Parameters:
	//   - keys : The names of the columns to sorting.
	// Returns:
	//   - An error if query fails.
	SortByAsc(keys ...string) error

	// Header returns the header row of the matrix.
	Header() []string

	// Rows returns all rows of the matrix.
	Rows() [][]string

	// Data returns the entire dataset with or without the header.
	//
	// Parameters:
	//   - withHeader: Want return with header or not.
	// Returns:
	//   - If param true, return data include header.
	Data(withHeader bool) [][]string

	// Clear removes all rows from the matrix.
	Clear()

	// ToCSV exports the matrix to CSV format.
	//
	// Parameters:
	//   - withHeader: Want return with header or not.
	// Returns:
	//   - If param true, return csv data include header.
	ToCSV(withHeader bool) Output

	// ToTSV exports the matrix to TSV format.
	//
	// Parameters:
	//   - withHeader: Want return with header or not.
	// Returns:
	//   - If param true, return TSV data include header.
	ToTSV(withHeader bool) Output

	// ToYAML exports the matrix to YAML format.
	ToYAML() Output

	// ToJSON exports the matrix to JSON format.
	//
	// Parameters:
	//   - compact: Want return json data with format minified (compact) or not.
	// Returns:
	//   - If param true, return json data with format minified (compact). If param false, return json data with format pretty-printed.
	ToJSON(compact bool) Output

	// ToCustom exports the matrix to a custom format using a specified separator.
	//
	// Parameters:
	//   - withHeader: Want return with header or not.
	//   - separator: Anything separator that want to use.
	// Returns:
	//   - Data with custom format using a specified separator.
	ToCustom(withHeader bool, separator string) Output

	// AddColumn adds a new column with an empty value for all rows.
	//
	// Parameters:
	//   - key: The naming of column want to be added.
	//   - data: The value of the column.
	//
	// Returns:
	//   - An error if writing fails.
	AddColumn(key string, data ...string) error

	// AddColumns adds multiple new columns with empty values for all rows.
	//
	// Parameters:
	//   - key: The naming of columns want to be added.
	//
	// Returns:
	//   - An error if writing fails.
	AddColumns(keys ...string) error

	// AddColumnWithDefaultValue adds a column with a default value for all rows.
	//
	// Parameters:
	//   - defaultValue: Default value that want to be added on the new column.
	//   - key: The naming of column want to be added.
	//
	// Returns:
	//   - An error if writing fails.
	AddColumnWithDefaultValue(defaultValue, key string) error

	// AddColumnsWithDefaultValue adds multiple columns with a default value for all rows.
	//
	// Parameters:
	//   - defaultValue: Default value that want to be added on the new column.
	//   - keys: The naming of columns want to be added.
	//
	// Returns:
	//   - An error if writing fails.
	AddColumnsWithDefaultValue(defaultValue string, keys ...string) error

	// GetRowData retrieves a specific cell value from a row and column.
	//
	// Parameters:
	//   - index: The index of the row.
	//   - key: The naming of columns.
	//
	// Returns:
	//   - The value of the specific index row and column.
	//   - An error if query fails.
	GetRowData(index int, key string) (string, error)

	// UpdateRowColumn updates a specific cell value in a row and column.
	//
	// Parameters:
	//   - index: The index of the row that want to be updated.
	//   - key: The naming of columns that want to be updated.
	//
	// Returns:
	//   - An error if writing fails.
	UpdateRowColumn(index int, key string, value string) error

	// DeleteColumn removes a column from the matrix.
	//
	// Parameters:
	//   - key: The naming of columns that want to be deleted.
	//
	// Returns:
	//   - An error if writing fails.
	DeleteColumn(key string) error

	// DeleteEmptyColumns removes all empty columns from the matrix.
	DeleteEmptyColumns() error

	// ContainsValue checks whether a specific value exists within a given column in the matrix.
	ContainsValue(key string, value string) (bool, error)

	// LenColumns returns the number of columns in the matrix.
	LenColumns() int

	// LenRows returns the number of rows in the matrix.
	LenRows() int

	// DataMap returns the matrix as a slice of maps where keys are column names.
	DataMap() []map[string]string

	// Copy creates a deep copy of the matrix.
	Copy() BDataMatrix

	// Peek prints a preview for the first 5 rows from the matrix.
	// Example output:
	//     +----+-------+-----+
	//     | ID | Name  | Age |
	//     +----+-------+-----+
	//     | 1  | Alice | 30  |
	//     | 2  | Bob   | 25  |
	//     | 3  | alice | 28  |
	//     +----+-------+-----+
	Peek()

	// PeekN prints a preview for the first N rows from the matrix.
	// Example output:
	//     +----+-------+-----+
	//     | ID | Name  | Age |
	//     +----+-------+-----+
	//     | 1  | Alice | 30  |
	//     | 2  | Bob   | 25  |
	//     | 3  | alice | 28  |
	//     +----+-------+-----+
	PeekN(n int)
}

BDataMatrix defines the behavior for a structured tabular data matrix.

func New

func New(keys ...string) (BDataMatrix, error)

New create a new BDataMatrix with the provided headers.

Example usage:

// Create a new matrix with headers "ID", "Name", "Age".
matrix, err := New("ID", "Name", "Age")
if err != nil {
    // handle error
}

// Add rows.
_ = matrix.AddRow("1", "Alice", "30")
_ = matrix.AddRow("2", "Bob", "25")

// Find rows where "Name" equals "Alice" (case-insensitive).
query := FindRowsQuery{
    Column:          "Name",
    Operator:        OperatorEquals,
    CaseInsensitive: true,
    Values:          []string{"Alice"},
}
result, err := matrix.FindRows(query)
if err != nil {
    // handle error
}

// Preview the matrix.
matrix.Peek()

// Export as CSV (with header) and write to file.
csvOut := matrix.ToCSV(true)
_ = csvOut.Write("output.csv", 0644)

func NewWithData

func NewWithData(rows [][]string, keys ...string) (BDataMatrix, error)

NewWithData creates a new BDataMatrix with the provided headers and initial data.

Example usage:

// Define initial data rows.
rows := [][]string{
    {"1", "Alice", "30"},
    {"2", "Bob", "25"},
}

// Create a new matrix with headers and data.
matrix, err := NewWithData(rows, "ID", "Name", "Age")
if err != nil {
    // handle error
}

// Preview the matrix.
matrix.Peek()

// Export as JSON (compact format).
jsonOut := matrix.ToJSON(true, true)
_ = jsonOut.Write("output.json", 0644)

type FindRowsQuery

type FindRowsQuery struct {
	// Column is the header name of the column to search.
	Column string
	// Operator is the comparison operator to apply.
	Operator Operator
	// CaseInsensitive indicates whether the comparison should ignore letter case.
	CaseInsensitive bool
	// Value is a value to compare against.
	Value string
	// Values is a slice of values to compare against.
	Values []string
}

FindRowsQuery specifies the criteria for searching rows.

If both FindRowsQuery.Value and FindRowsQuery.Values present, FindRowsQuery.Value will be added to be one of FindRowsQuery.Values entry.

type Input added in v1.0.0

type Input interface {
	FromCSV() (BDataMatrix, error)
	FromTSV() (BDataMatrix, error)
}

func NewFromFile added in v1.0.0

func NewFromFile(path string) Input

type Operator

type Operator int

Operator defines the type of comparison for queries.

const (
	OperatorEquals Operator = iota + 1
	OperatorNotEquals
	OperatorContains
	OperatorStartsWith
	OperatorEndsWith
)

func (Operator) String added in v0.0.2

func (o Operator) String() string

type Output

type Output interface {
	// Write writes the output data to a file with the given name and file mode.
	//
	// Parameters:
	//   - name: The filename to write to.
	//   - mode: The file mode (permissions) to use when writing.
	//
	// Returns:
	//   - An error if writing fails.
	Write(name string, mode os.FileMode) error

	// Bytes returns the output data as a byte slice.
	//
	// Returns:
	//   - A []byte containing the output data.
	Bytes() []byte

	// String returns the output data as a string.
	//
	// Returns:
	//   - A string representation of the output data.
	String() string
}

Output defines methods for exporting matrix data.

Example usage:

// Get CSV output and write to file.
csvOut := matrix.ToCSV(true)
err := csvOut.Write("output.csv", 0644)
if err != nil {
    // handle error
}

// Retrieve JSON output as a string.
jsonOut := matrix.ToJSON(true, false)
fmt.Println(jsonOut.String())

Jump to

Keyboard shortcuts

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