bdatamatrix

package module
v0.0.2-beta-7 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2025 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

View Source
const (
	FindRowsQueryStatus_Entries       = "entries"
	FindRowsQueryStatus_MeetCondition = "meet_condition"
)

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.
	AddRow(values ...string) error

	// AddRows appends multiple rows to the matrix.
	AddRows(rows ...[]string) error

	// GetRow retrieves a row by index.
	GetRow(index int) ([]string, error)

	// GetRows retrieves multiple rows by indexes.
	GetRows(indexes ...int) (BDataMatrix, error)

	// GetColumn retrieves a column by name.
	GetColumn(key string) ([]string, error)

	// GetColumns retrieves multiple columns by names.
	GetColumns(keys ...string) (BDataMatrix, error)

	// UpdateRow updates an existing row at the specified index.
	UpdateRow(index int, values ...string) error

	// DeleteRow removes a row at the specified index.
	DeleteRow(index int) error

	// FindRows searches for rows matching a given query.
	FindRows(query FindRowsQuery) (BDataMatrix, error)

	// FindRowsWithHistories searches for rows matching a given query with histories.
	FindRowsWithHistories(query FindRowsQuery) (BDataMatrix, BDataMatrix, error)

	// SortBy sorts rows based on one or more column names.
	SortBy(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.
	Data(withHeader bool) [][]string

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

	// Preview displays the first N rows of the matrix.
	Preview(n int)

	// ToCSV exports the matrix to CSV format.
	ToCSV(withHeader bool) Output

	// ToTSV exports the matrix to TSV format.
	ToTSV(withHeader bool) Output

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

	// ToJSON exports the matrix to JSON format.
	ToJSON(compact bool) Output

	// ToCustom exports the matrix to a custom format using a specified separator.
	ToCustom(withHeader bool, separator string) Output

	// AddColumn adds a new column with an empty value for all rows.
	AddColumn(key string) error

	// AddColumns adds multiple new columns with empty values for all rows.
	AddColumns(keys ...string) error

	// AddColumnWithDefaultValue adds a column with a default value for all rows.
	AddColumnWithDefaultValue(defaultValue, key string) error

	// AddColumnsWithDefaultValue adds multiple columns with a default value for all rows.
	AddColumnsWithDefaultValue(defaultValue string, keys ...string) error

	// GetRowData retrieves a specific cell value from a row and column.
	GetRowData(index int, key string) (string, error)

	// UpdateRowColumn updates a specific cell value in a row and column.
	UpdateRowColumn(index int, key string, value string) error

	// DeleteColumn removes a column from the matrix.
	DeleteColumn(key string) error

	// DeleteEmptyColumns removes all empty columns from the matrix.
	DeleteEmptyColumns() 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 of the matrix.
	Peek()
}

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.Preview()

// 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.Preview()

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

type Operator int

Operator defines the type of comparison for queries.

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

func (Operator) String

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