xbase

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: MIT Imports: 20 Imported by: 0

README

xbase

Language codecov Go Report Card Build Status Release GoDoc

forked from svolodeev/xbase in the beginning,and both the project and author seems no action, so I forked it and refract.

Package xbase is DBF util written in GO,provides fast,idiomatic free mapping between DBF and GO values

A pure Go library for working with DBF files. The main purpose of the library is to organize export-import of data from files in DBF format.

The XBase type is used to work with DBF files. In addition to working with existing files, the XBase object allows you to create a new file of the given structure. Each XBase object can be linked with only one file.

Writing changes to a file

The XBase object contains data for one current record. Changing field values does not cause an immediate change to the file. Changes are saved when the Save() method is called.

Deleting records

Deleting a record does not physically destroy it on disk. The deletion mark is put in a special field of the record.

Error processing

If an error occurs when calling the method, use the Error() method to get its value. By default, methods don't panic. This behavior can be changed.

Serialization and Deserialization

easy to serialize and deserialize according to the code page of the dbf file.

Limitations

The following field types are supported: C, N, L, D. Memo fields are not supported. Index files are not supported.

Examples

File creation.

package main

import (
	"fmt"
	"github.com/tsingsun/xbase"
	"time"
)

func main() {
	// Create file
	db,err := xbase.New()
    if err != nil {
        fmt.Println(err)
        return
    }
	db.AddField("NAME", "C", 30)
	db.AddField("SALARY", "N", 9, 2)
	db.AddField("BDATE", "D")
	db.SetCodePage(1251)
	db.CreateFile("persons.dbf")
	if db.Error() != nil {
		fmt.Println(db.Error())
		return
	}
	defer db.Close()

	// Add record
	db.Add()
	db.SetFieldValue(1, "John Smith")
	db.SetFieldValue(2, 1234.56)
	db.SetFieldValue(3, time.Date(1998, 2, 20, 0, 0, 0, 0, time.UTC))
	db.Save()
	if db.Error() != nil {
		fmt.Println(db.Error())
		return
	}
}

Reading file.

package main

import (
	"fmt"
    "github.com/tsingsun/xbase"
)

func main() {
	// Open the DBF file
	db, err := xbase.Open("persons.dbf", true)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Close the file when done
	defer db.Close()

	// Read the records
	db.First()
	for !db.EOF() {
		name := db.FieldValueAsString(1)
		salary := db.FieldValueAsFloat(2)
		bDate := db.FieldValueAsDate(3)
		fmt.Println(name, salary, bDate)
		db.Next()
	}
}

File information.

package main

import (
	"fmt"
	"github.com/tsingsun/xbase"
)

func main() {
	db,err := xbase.Open("persons.dbf", true)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	fmt.Println("Record count:", db.RecCount())
	fmt.Println("Field count:", db.FieldCount())
	fmt.Println("Code page:", db.CodePage())

	// File structure
	for _, f := range db.DecodedFields() {
		fmt.Println(f.Name, f.Type, f.Len, f.Dec)
	}
}

Append Record

package main

import (
	"fmt"
	"github.com/tsingsun/xbase"
	"time"
)

func main() {
	db,err := xbase.Open("persons.dbf", false)
	if err != nil {
        fmt.Println(err)
        return
    }
	defer db.Close()

	db.Add()
	db.SetFieldValue(1, "John Smith")
	db.SetFieldValue(2, 1234.56)
	db.SetFieldValue(3, time.Date(1998, 2, 20, 0, 0, 0, 0, time.UTC))
	db.Save()
	if db.Error() != nil {
		fmt.Println("Code page:",db.Error())
	}
}

Serialization and Deserialization

package main

import (
	"fmt"
	"github.com/tsingsun/xbase"
	"time"
)

type Person struct {
	Name   string  `dbf:"name,len=30"`
	Salary float64 `dbf:"salary,len=9,dec=2"`
	BDate  time.Time `dbf:"bdate"`
}

func main() {
	db, err := xbase.Open("persons.dbf", false)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	p := Person{
		Name:   "John Smith", 
		Salary: 1234.56,
		BDate:  time.Date(1998, 2, 20, 0, 0, 0, 0, time.UTC),
	}
	// append record by struct
	err = db.Append(p)
	if err != nil {
		fmt.Println(err)
	}

	// Deserialize to struct
	var p2 Person
	err = db.DecodeRecord(&p2)
	if err != nil {
		fmt.Println(err)
	}
}

Documentation

Index

Examples

Constants

View Source
const (
	FieldType_Character = 'C'
	FieldType_Numeric   = 'N'
	FieldType_Date      = 'D'
	FieldType_Float     = 'F'
	FieldType_Logical   = 'L'
	// not support
	FieldType_Binary        = 'B'
	FieldType_Memo          = 'M'
	FieldType_Timestamp     = '@'
	FieldType_Long          = 'I'
	FieldType_Double        = 'O'
	FieldType_OLE           = 'G'
	FieldType_Autoincrement = '+'
)

Variables

View Source
var BOF = errors.New("BOF")
View Source
var ErrFieldCount = errors.New("wrong number of fields in record")

ErrFieldCount is returned when header's length doesn't match the length of the read record.

Functions

func EncodingByPage added in v0.3.0

func EncodingByPage(page int) encoding.Encoding

Types

type Decoder

type Decoder struct {
	// Tag defines which key in the struct field's tag to scan for names and
	// options (Default: 'dbf').
	Tag string

	// If true, Decoder will return a MissingColumnsError if it discovers
	// that any of the columns are missing. This means that a DBF input
	// will be required to contain all columns that were defined in the
	// provided struct.
	DisallowMissingColumns bool

	// If not nil, Map is a function that is called for each field in the dbf
	// record before decoding the data. It allows mapping certain string values
	// for specific columns or types to a known format. Decoder calls Map with
	// the current column name (taken from header) and a zero non-pointer value
	// of a type to which it is going to decode data into. Implementations
	// should use type assertions to recognize the type.
	//
	// The good example of use case for Map is if NaN values are represented by
	// eg 'n/a' string, implementing a specific Map function for all floats
	// could map 'n/a' back into 'NaN' to allow successful decoding.
	//
	// Use Map with caution. If the requirements of column or type are not met
	// Map should return 'field', since it is the original value that was
	// read from the dbf input, this would indicate no change.
	//
	// If struct field is an interface v will be of type string, unless the
	// struct field contains a settable pointer value - then v will be a zero
	// value of that type.
	//
	// Map must be set before the first call to Decode and not changed after it.
	Map func(field, col string, v any) string
	// contains filtered or unexported fields
}

A Decoder reads and decodes string records into structs.

func NewDecoder

func NewDecoder(r Reader, fields ...string) (dec *Decoder, err error)

NewDecoder returns a new decoder that reads from r.

Decoder will match struct fields according to the given header.

If header is empty NewDecoder will read one line and treat it as a header.

Records coming from r must be of the same length as the header.

NewDecoder may return io.EOF if there is no data in r and no header was provided by the caller.

func (*Decoder) Decode

func (d *Decoder) Decode(v any) (err error)

Decode reads the next string record or records from its input and stores it in the value pointed to by v which must be a pointer to a struct, struct slice or struct array.

Decode matches all exported struct fields based on the header. Struct fields can be adjusted by using tags.

The "omitempty" option specifies that the field should be omitted from the decoding if record's field is an empty string.

Examples of struct field tags and their meanings:

// Decode matches this field with "myName" header column.
Field int `dbf:"myName"`

// Decode matches this field with "Field" header column.
Field int

// Decode matches this field with "myName" header column and decoding is not
// called if record's field is an empty string.
Field int `dbf:"myName,omitempty"`

// Decode matches this field with "Field" header column and decoding is not
// called if record's field is an empty string.
Field int `dbf:",omitempty"`

// Decode ignores this field.
Field int `dbf:"-"`

// Decode treats this field exactly as if it was an embedded field and
// matches header columns that start with "my_prefix_" to all fields of this
// type.
Field Struct `dbf:"my_prefix_,inline"`

// Decode treats this field exactly as if it was an embedded field.
Field Struct `dbf:",inline"`

By default decode looks for "dbf" tag, but this can be changed by setting Decoder.Tag field.

To Decode into a custom type v must implement xbase.Unmarshaler or encoding.TextUnmarshaler.

Anonymous struct fields with tags are treated like normal fields and they must implement xbase.Unmarshaler or encoding.TextUnmarshaler unless inline tag is specified.

Anonymous struct fields without tags are populated just as if they were part of the main struct. However, fields in the main struct have bigger priority and they are populated first. If main struct and anonymous struct field have the same fields, the main struct's fields will be populated.

Fields of type []byte expect the data to be base64 encoded strings.

Float fields are decoded to NaN if a string value is 'NaN'. This check is case insensitive.

Interface fields are decoded to strings unless they contain settable pointer value.

Pointer fields are decoded to nil if a string value is empty.

If v is a slice, Decode resets it and reads the input until EOF, storing all decoded values in the given slice. Decode returns nil on EOF.

If v is an array, Decode reads the input until EOF or until it decodes all corresponding array elements. If the input contains less elements than the array, the additional Go array elements are set to zero values. Decode returns nil on EOF unless there were no records decoded.

Fields with inline tags that have a non-empty prefix must not be cyclic structures. Passing such values to Decode will result in an infinite loop.

func (*Decoder) Header

func (d *Decoder) Header() []string

Header returns the first line that came from the reader, or returns the defined header by the caller.

func (*Decoder) NormalizeHeader

func (d *Decoder) NormalizeHeader(f func(string) string) error

NormalizeHeader applies f to every column in the header. It returns error if calling f results in conflicting header columns.

NormalizeHeader must be called before Decode.

func (*Decoder) Record

func (d *Decoder) Record() []string

Record returns the most recently read record. The slice is valid until the next call to Decode.

func (*Decoder) Register

func (d *Decoder) Register(f any)

Register registers a custom decoding function for a concrete type or interface. The argument f must be of type:

func([]byte, T) error

T must be a concrete type such as *time.Time, or interface that has at least one method.

During decoding, fields are matched by the concrete type first. If match is not found then Decoder looks if field implements any of the registered interfaces in order they were registered.

Register panics if:

  • f does not match the right signature
  • f is an empty interface
  • f was already registered

Register is based on the encoding/json proposal: https://github.com/golang/go/issues/5901.

func (*Decoder) Unused

func (d *Decoder) Unused() []int

Unused returns a list of column indexes that were not used during decoding due to lack of matching struct field.

type Encoder

type Encoder struct {
	// Tag defines which key in the struct field's tag to scan for names and
	// options (Default: 'dbf').
	Tag string

	// If AutoHeader is true, a struct header is encoded during the first call
	// to Encode automatically (Default: true).
	AutoHeader bool
	// contains filtered or unexported fields
}

Encoder writes structs DBF representations to the output stream.

func NewEncoder

func NewEncoder(w Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode

func (e *Encoder) Encode(v any) error

Encode writes the DBF encoding of v to the output stream. The provided argument v must be a struct, struct slice or struct array.

Only the exported fields will be encoded.

First call to Encode will write a header unless EncodeHeader was called first or AutoHeader is false. Header names can be customized by using tags ('dbf' by default), otherwise original Field names are used.

If header was provided through SetHeader then it overrides the provided data type's default header. Fields are encoded in the order of the provided header. If a column specified in the header doesn't exist in the provided type, it will be encoded as an empty column. Fields that are not part of the provided header are ignored. Encoder can't guarantee the right order if the provided header contains duplicate column names.

Header and fields are written in the same order as struct fields are defined. Embedded struct's fields are treated as if they were part of the outer struct. Fields that are embedded types and that are tagged are treated like any other field, but they have to implement Marshaler or encoding.TextMarshaler interfaces.

Marshaler interface has the priority over encoding.TextMarshaler.

Tagged fields have the priority over non tagged fields with the same name.

Following the Go visibility rules if there are multiple fields with the same name (tagged or not tagged) on the same level and choice between them is ambiguous, then all these fields will be ignored.

Nil values will be encoded as empty strings. Same will happen if 'omitempty' tag is set, and the value is a default value like 0, false or nil interface.

Bool types are encoded as 'true' or 'false'.

Float types are encoded using strconv.FormatFloat with precision -1 and 'G' format. NaN values are encoded as 'NaN' string.

Fields of type []byte are being encoded as base64-encoded strings.

Fields can be excluded from encoding by using '-' tag option.

Examples of struct tags:

// Field appears as 'myName' header in DBF encoding.
Field int `dbf:"myName"`

// Field appears as 'Field' header in DBF encoding.
Field int

// Field appears as 'myName' header in DBF encoding and is an empty string
// if Field is 0.
Field int `dbf:"myName,omitempty"`

// Field appears as 'Field' header in DBF encoding and is an empty string
// if Field is 0.
Field int `dbf:",omitempty"`

// Encode ignores this field.
Field int `dbf:"-"`

// Encode treats this field exactly as if it was an embedded field and adds
// "my_prefix_" to each field's name.
Field Struct `dbf:"my_prefix_,inline"`

// Encode treats this field exactly as if it was an embedded field.
Field Struct `dbf:",inline"`

Fields with inline tags that have a non-empty prefix must not be cyclic structures. Passing such values to Encode will result in an infinite loop.

Encode doesn't flush data. The caller is responsible for calling Flush() if the used Writer supports it.

func (*Encoder) EncodeHeader

func (e *Encoder) EncodeHeader(v any) error

EncodeHeader writes the DBF header of the provided struct value to the output stream. The provided argument v must be a struct value.

The first Encode method call will not write header if EncodeHeader was called before it. This method can be called in cases when a data set could be empty, but header is desired.

EncodeHeader is like Header function, but it works with the Encoder and writes directly to the output stream. Look at Header documentation for the exact header encoding rules.

func (*Encoder) Register

func (e *Encoder) Register(f any)

Register registers a custom encoding function for a concrete type or interface. The argument f must be of type:

func(T) (any, error)

T must be a concrete type such as Foo or *Foo, or interface that has at least one method.

During encoding, fields are matched by the concrete type first. If match is not found then Encoder looks if field implements any of the registered interfaces in order they were registered.

Register panics if:

  • f does not match the right signature
  • f is an empty interface
  • f was already registered

Register is based on the encoding/json proposal: https://github.com/golang/go/issues/5901.

func (*Encoder) SetHeader

func (e *Encoder) SetHeader(header []*decodedField)

SetHeader overrides the provided data type's default header. Fields are encoded in the order of the provided header. If a column specified in the header doesn't exist in the provided type, it will be encoded as an empty column. Fields that are not part of the provided header are ignored. Encoder can't guarantee the right order if the provided header contains duplicate column names.

SetHeader must be called before EncodeHeader and/or Encode in order to take effect.

type InvalidDecodeError

type InvalidDecodeError struct {
	Type reflect.Type
}

An InvalidDecodeError describes an invalid argument passed to Decode. (The argument to Decode must be a non-nil struct pointer)

func (*InvalidDecodeError) Error

func (e *InvalidDecodeError) Error() string

type InvalidEncodeError

type InvalidEncodeError struct {
	Type reflect.Type
}

InvalidEncodeError is returned by Encode when the provided value was invalid.

func (*InvalidEncodeError) Error

func (e *InvalidEncodeError) Error() string

type InvalidMarshalError

type InvalidMarshalError struct {
	Type reflect.Type
}

InvalidMarshalError is returned by Marshal when the provided value was invalid.

func (*InvalidMarshalError) Error

func (e *InvalidMarshalError) Error() string

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	Type reflect.Type
}

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil slice of structs pointer)

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type Marshaler

type Marshaler interface {
	MarshalDBF() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid string.

type MarshalerError

type MarshalerError struct {
	Type          reflect.Type
	MarshalerType string
	Err           error
}

MarshalerError is returned by Encoder when MarshalCSV or MarshalText returned an error.

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

func (*MarshalerError) Unwrap

func (e *MarshalerError) Unwrap() error

Unwrap implements Unwrap interface for errors package in Go1.13+.

type MissingColumnsError

type MissingColumnsError struct {
	Columns []string
}

MissingColumnsError is returned by Decoder only when DisallowMissingColumns option was set to true. It contains a list of all missing columns.

func (*MissingColumnsError) Error

func (e *MissingColumnsError) Error() string

type Option added in v0.3.0

type Option func(base *XBase)

func WithEncoding added in v0.3.0

func WithEncoding(cp encoding.Encoding) Option

WithEncoding set encoding for dbf file. this will work only the file code page code is not set, otherwise it will be set by the file code page.

func WithEncodingCode added in v0.3.0

func WithEncodingCode(codepage int) Option

WithEncodingCode set encoding for dbf file by code page.

func WithReadWriteSeeker added in v0.3.0

func WithReadWriteSeeker(rws io.ReadWriteSeeker) Option

type RWStep added in v0.3.0

type RWStep int

RWStep indicate the step of dbf read/write.

const (
	// RWStepNoop indicate may be just open the file.
	RWStepNoop RWStep = iota
	// RWStepHead indicate read/write header complete.
	RWStepHead
	// RWStepField indicate read/write is in data area.
	RWStepField
)

type Reader

type Reader interface {
	Read() ([]string, error)
}

Reader provides the interface for reading a single DBF record.

If there is no data left to be read, Read returns (nil, io.EOF).

It is implemented by dbf.Reader.

type UnmarshalTypeError

type UnmarshalTypeError struct {
	Value string       // string value
	Type  reflect.Type // type of Go value it could not be assigned to
}

An UnmarshalTypeError describes a string value that was not appropriate for a value of a specific Go type.

func (*UnmarshalTypeError) Error

func (e *UnmarshalTypeError) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalDBF([]byte) error
}

Unmarshaler is the interface implemented by types that can unmarshal a single record's field description of themselves.

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

An UnsupportedTypeError is returned when attempting to encode or decode a value of an unsupported type.

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

type Writer

type Writer interface {
	Write([]any) error
}

Writer provides the interface for writing a single DBF record.

It is implemented by dbf.Writer.

type XBase

type XBase struct {
	// contains filtered or unexported fields
}

XBase is a util for DBF file.

func New

func New(opts ...Option) (*XBase, error)

New creates a XBase object to work with a DBF file and an error if any.

func Open

func Open(name string, readOnly bool, opts ...Option) (db *XBase, err error)

Open opens an existing DBF file.

func (*XBase) Add

func (db *XBase) Add() error

Add adds a new empty record. To save the changes, you need to call the Save method.

func (*XBase) AddField

func (db *XBase) AddField(name string, typ string, opts ...int) error

AddField adds a field to the structure of the DBF file. This method can only be used before creating a new file.

The following field types are supported: "C", "N", "F", "L", "D".

The opts parameter contains optional parameters: field length and number of decimal places.

Examples:

db.AddField("NAME", "C", 24)
db.AddField("COUNT", "N", 8)
db.AddField("PRICE", "F", 12, 2)
db.AddField("FLAG", "L")
db.AddField("DATE", "D")

func (*XBase) Append

func (db *XBase) Append(input any) error

Append an input value,auto call save

Example

ExampleXBase_Append demonstrates how to append a record to a DBF file using the xbase package.

package main

import (
	"fmt"
	"github.com/tsingsun/xbase"
	"time"
)

func main() {
	// Open the DBF file
	db, err := xbase.Open("persons.dbf", false)
	if err != nil {
		fmt.Println(err)
		return
	}
	// Always check for errors
	if db.Error() != nil {
		fmt.Println(db.Error())
		return
	}

	// Close the file when done
	defer db.Close()

	// Append a record
	db.Add()
	db.SetFieldValue(1, "John Smith")
	db.SetFieldValue(2, 1234.56)
	db.SetFieldValue(3, time.Date(1998, 2, 20, 0, 0, 0, 0, time.UTC))
	db.Save()

	// Always check for errors
	if db.Error() != nil {
		fmt.Println(db.Error())
	}
}

func (*XBase) BOF

func (db *XBase) BOF() bool

BOF returns true if the beginning of the file is reached.

func (*XBase) Clear

func (db *XBase) Clear()

Clear zeroes the field values ​​of the current record and error.

func (*XBase) Close

func (db *XBase) Close() error

Close closes a previously opened or created DBF file.

func (*XBase) CodePage

func (db *XBase) CodePage() int

CodePage returns the code page of a DBF file. Returns 0 if no code page is specified.

func (*XBase) CreateFile

func (db *XBase) CreateFile(name string) (err error)

CreateFile creates a new file in DBF format. If a file with that name exists, it will be overwritten.

func (*XBase) DecodeRecord

func (db *XBase) DecodeRecord(dst any) (err error)

DecodeRecord decode current row to a struct

func (*XBase) DecodedFields added in v0.3.0

func (db *XBase) DecodedFields() []*decodedField

DecodedFields returns the decoded field list.

func (*XBase) Del

func (db *XBase) Del()

Del marks the current record as "deleted". The record is not physically deleted from the file and can be subsequently restored.

func (*XBase) EOF

func (db *XBase) EOF() bool

EOF returns true if end of file is reached.

func (*XBase) Error

func (db *XBase) Error() error

Error returns an error when working with a DBF file.

func (*XBase) FieldCount

func (db *XBase) FieldCount() int

FieldCount returns the number of fields in the DBF file.

func (*XBase) FieldNo

func (db *XBase) FieldNo(name string) int

FieldNo returns the number of the field by name. If name is not found returns 0. Fields are numbered starting from 1.

func (*XBase) FieldValueAsBool

func (db *XBase) FieldValueAsBool(fieldNo int) (val bool)

FieldValueAsBool returns the boolean value of the field of the current record. Field type must be logical ("L"). Fields are numbered starting from 1.

func (*XBase) FieldValueAsDate

func (db *XBase) FieldValueAsDate(fieldNo int) (d time.Time)

FieldValueAsDate returns the date value of the field of the current record. Field type must be date ("D"). Fields are numbered starting from 1.

func (*XBase) FieldValueAsFloat

func (db *XBase) FieldValueAsFloat(fieldNo int) (val float64)

FieldValueAsFloat returns the float value of the field of the current record. Field type must be numeric ("N"). Fields are numbered starting from 1.

func (*XBase) FieldValueAsInt

func (db *XBase) FieldValueAsInt(fieldNo int) (val int64)

FieldValueAsInt returns the integer value of the field of the current record. Field type must be numeric ("N"). Fields are numbered starting from 1.

func (*XBase) FieldValueAsString

func (db *XBase) FieldValueAsString(fieldNo int) (val string)

FieldValueAsString returns the string value of the field of the current record. Fields are numbered starting from 1.

func (*XBase) Fields

func (db *XBase) Fields() []string

Fields return the decoded field name list.

func (*XBase) First

func (db *XBase) First() error

First positions the object to the first record.

func (*XBase) Flush

func (db *XBase) Flush() (err error)

Flush commit changes to file

func (*XBase) GoTo

func (db *XBase) GoTo(recNo int64) (err error)

GoTo allows you to go to a record by its ordinal number. Numbering starts from 1, file can be appended by the other thread,so GOTO should try move to the record which is greater than the original rec count.

func (*XBase) Last

func (db *XBase) Last() error

Last positions the object to the last record.

func (*XBase) ModDate

func (db *XBase) ModDate() time.Time

ModDate returns the modification date of the DBF file.

func (*XBase) Next

func (db *XBase) Next() error

Next positions the object to the next record.

func (*XBase) Prev

func (db *XBase) Prev() error

Prev positions the object to the previous record.

func (*XBase) Read

func (db *XBase) Read() (val []string, err error)

Read() implement Reader interface, it returns the information like text scanner. The first call returns the field name list and the next call returns the record.

Example

ExampleXBase_Read demonstrates how to read a DBF file using the xbase package.

package main

import (
	"fmt"
	"github.com/tsingsun/xbase"
)

func main() {
	// Open the DBF file
	db, err := xbase.Open("persons.dbf", true)
	if err != nil {
		fmt.Println(err)
		return
	}
	// Always check for errors
	if db.Error() != nil {
		fmt.Println(db.Error())
		return
	}

	// Close the file when done
	defer db.Close()

	// Read the records
	db.First()
	for !db.EOF() {
		name := db.FieldValueAsString(1)
		salary := db.FieldValueAsFloat(2)
		bDate := db.FieldValueAsDate(3)
		fmt.Println(name, salary, bDate)
		db.Next()
	}
}

func (*XBase) RecCount

func (db *XBase) RecCount() int64

RecCount returns the number of records in the DBF file.

func (*XBase) RecDeleted

func (db *XBase) RecDeleted() bool

RecDeleted returns the value of the delete flag for the current record.

func (*XBase) RecNo

func (db *XBase) RecNo() int64

RecNo returns the sequence number of the current record. Numbering starts from 1.

func (*XBase) Recall

func (db *XBase) Recall()

Recall removes the deletion mark from the current record.

func (*XBase) Save

func (db *XBase) Save() error

Save writes changes to the file. Before calling it, all changes to the object were made only in memory and will be lost when you move to another record or close the file.

func (*XBase) SetCodePage

func (db *XBase) SetCodePage(cp int)

SetCodePage sets the encoding mode for reading and writing string field values. The default code page is 0.

Supported code pages:

	437   - US MS-DOS
	850   - International MS-DOS
	1252  - Windows ANSI
	10000 - Standard Macintosh
	852   - Easern European MS-DOS
	866   - Russian MS-DOS
	865   - Nordic MS-DOS
 936   - Chinese (PRC, Singapore) Windows
 950   - Chinese (Hong Kong SAR, Taiwan) Windows
	1255  - Hebrew Windows
	1256  - Arabic Windows
	10007 - Russian Macintosh
	1250  - Eastern European Windows
	1251  - Russian Windows
	1254  - Turkish Windows
	1253  - Greek Windows

func (*XBase) SetEncoding added in v0.3.0

func (db *XBase) SetEncoding(enc encoding.Encoding)

SetEncoding sets the encoding mode for reading and writing string field values only. it does not affect the encoding of the dbf file language ID field. if dbf file language ID field is 0,but the `C` field is encoded,then you should call this method. if you can change the dbf file language ID field,then you should call SetCodePage.

func (*XBase) SetFieldValue

func (db *XBase) SetFieldValue(fieldNo int, value any)

SetFieldValue sets the field value of the current record. The value must match the field type. To save the changes, you need to call the Save method.

func (*XBase) Write

func (db *XBase) Write(input []any) (err error)

Write implement Writer interface, it called by encoder.

Jump to

Keyboard shortcuts

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