Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Tuesday, September 10, 2013

4.3.3: Example - A Flat-File Database - part 3

We conclude this example by going over the Query package.

type (
    FieldQueryFunc func(string) bool
)

A FieldQueryFunc is similar to a i.FilterFunc with the exception that it is specialized to work on string values rather than i.Iterator values.

func (db *Ffdb) Query(f i.FilterFunc, d Direction) i.Forward {
    return i.Filter(f, RecordItr(db, d))
}

func (db *Ffdb) QueryField(fieldname string, f FieldQueryFunc, d Direction) i.Forward {
    fieldname = strings.ToUpper(fieldname)
    if _, ok := db.fieldnames[fieldname]; !ok {
        panic(fmt.Errorf("Unknown field: %q\n", fieldname))
    }

    return db.Query(func(itr i.Iterator) bool {
        r, _ := itr.Value().(*Record)
        return f(r.Value(fieldname))
    }, d)
}

The Query package contains two fundamental methods that serve as building blocks for all other queries. The first, Query(), is an iterator that uses the i.Filter iterator to construct a i.Forward iterator that will filter a Record stream in the direction of Direction with the filter f.
The QueryField() constructs a i.FilterFunc and binds it to a field name and a FieldQueryFunc. We can now iterate over the stream of Records and ask specific questions about individual field values. Two examples are provided in the Query package.

func (db *Ffdb) QueryFieldRx(fieldname, rxs string, d Direction) i.Forward {
    rx := regexp.MustCompile(rxs)
    return db.QueryField(fieldname, func(val string) bool {
        return rx.MatchString(val)
    }, d)
}

func (db *Ffdb) QueryGreater(fieldname string, check float64, d Direction) i.Forward {
    return db.QueryField(fieldname, func(fieldvalue string) bool {
        value, _ := strconv.ParseFloat(fieldvalue, 64)
        return value > check
    }, d)
}

QueryFieldRx is a query that checks field named fieldname against a regular expression rsx. QueryGreater is a query that returns records where the float64 value of field fieldname is greater than some value suppled to the query.

An entire pipeline of iterators, from query to text file using e.g. the QueryFieldRx, would look something like this:


The blue lines represent how data moves through the construction of the pipeline. FieldName, Rx and Direction are send to the QueryFieldRx which constructs a FieldQueryFunc and sends it along with the FieldName and Direction to the QueryField object. It constructs a i.FilterFunc and sends it with the Direction to the Query object. The Query constructs the Record iterator, which in turns constructs the Reader from the Direction.
Now that the pipeline is ready, we can read bytes from the file. The Reader turns those into a string for each line in the file and hands those over to the Record iterator. The Record iterator, being a i.Map iterator, maps the lines to a Record which the Query then filters and returns to the user.
Following is an example of how to use this package.

    db, _ := ffdb.NewFfdbHeader(os.Args[1], "[:]")
    defer db.Close()

    fmt.Println("From state: MA & NY")
    itrNY := db.QueryFieldRx("state", "NY", ffdb.Reverse)
    itrMA := db.QueryFieldRx("state", "MA", ffdb.Forward)
    for !itrNY.AtEnd() || !itrMA.AtEnd() {
        if !itrNY.AtEnd() {
            fmt.Println(itrNY.Value())
            itrNY.Next()
        }
        if !itrMA.AtEnd() {
            fmt.Println(itrMA.Value())
            itrMA.Next()
        }
    }
    fmt.Println("\nOwes more than 100")
    for itr := db.QueryGreater("owes", 100, ffdb.Forward); !itr.AtEnd(); itr.Next() {
        fmt.Println(itr.Value())
    }

We open the database, build some query iterators and run through them printing out the result.
The two source files discussed here are available at GitHub: Query and ffdb

Monday, September 9, 2013

4.3.3: Example - A Flat-File Database - part 2

The Record package iterates over a stream of lines, parsing them into a Record structure and passing them on. It utilizes a new function in the iterator library, Map. Lets start by running through it.

type MapFunc func(Iterator) interface{}

type imap struct {
    fmap MapFunc
    val  interface{}
    itr  Forward
}

func Map(fmap MapFunc, itr Forward) Forward {
    return &imap{fmap: fmap, itr: itr, val: nil}
}

func (i *imap) AtEnd() bool {
    return i.itr.AtEnd()
}

func (i *imap) Next() error {
    i.val = nil
    return i.itr.Next()
}

func (i *imap) Value() interface{} {
    if i.val == nil {
        i.val = i.fmap(i.itr)
    }
    return i.val
}

func (i *imap) Error() error {
    return i.itr.Error()
}

The Map iterator accepts a MapFunc function and a Forward iterator. It then iterates over that iterator and uses the MapFunc to transform the value before returning it. You can see source at GitHub.

type (
    Record map[string]string
)

func RecordItr(db *Ffdb, d Direction) i.Forward {
    return i.Map(recordParser(db), d(db))
}

The Record type is simply a map of strings keyed to a string. And the constructor creates a map from a stream of lines to a stream of records as defined by recordParser. The Direction is a function pointer to either the Forward or the Reverse reader.

func recordParser(db *Ffdb) i.MapFunc {
    return func(itr i.Iterator) interface{} {
        line, _ := itr.Value().(string)
        fields := db.fieldsep.Split(line, -1)
        if len(fields) != len(db.fields) {
            panic(fmt.Errorf("Unexpected number of fields in record %q, expected %d, got %d\n", line, len(db.fields), len(fields)))
        }
        var record Record = make(map[string]string, len(fields))
        for i, v := range fields {
            record[db.fields[i]] = v
        }
        return &record
    }
}

The recordParser returns a function of type i.MapFunc. Its purpose is to accept a string, tokenize it with a field seperator defined in the Ffdb object, validate that the number of fields in the line matches with the number of fields in the Ffdb object, create a Record structure and fill it with the values from the line keyed to the fields defined in the Ffdb object.

func (r *Record) String() string {
    m := (map[string]string)(*r)
    return fmt.Sprint(m)
}

func (r *Record) Value(key string) string {
    return (*r)[key]
}

Finally we have some helper functions that allows to work with a Record structure. The Ffdb package defines the flat file database object.

type Bound struct {
    start, end int64
}

type Ffdb struct {
    file       *os.File
    fields     []string
    fieldnames map[string]int
    fieldsep   *regexp.Regexp
    bound      Bound
}

The Bound structure we've seen before, it defines the boundaries of the underlying text file for the readers. The Ffdb structure holds the neccessary state for the database: the name of the file, name of the fields, a mapping of field names to field numbers, the field seperator and the Bound structure.

func NewFfdb(name, fieldsep string, schema []string) (*Ffdb, error) {
    var db Ffdb
    var err error
    db.fieldsep = regexp.MustCompile(fieldsep)
    if db.file, err = os.Open(name); err != nil {
        return nil, err
    }
    db.fields = schema
    db.bound.end = -1
    return &db, nil
}

We have to constructors for the Ffdb object. The former assumes that there is no schema in the file and therefore expects the caller to supplie a slice of strings containing the names of the fields (and indirectly the number of fields). It defines the boundaries as the entire file.

func NewFfdbHeader(name, fieldsep string) (*Ffdb, error) {
    db, err := NewFfdb(name, fieldsep, nil)
    if err != nil {
        return nil, err
    }
    readbuf := make([]byte, 4096)
    var buf bytes.Buffer
    var pos int64
    found := false
    for !found {
        n, err := db.file.Read(readbuf)
        if err != nil && err != io.EOF {
            return nil, errors.New("Unable to read schema")
        }
        r := bytes.NewReader(readbuf)
        for r.Len() > 0 {
            ch, _, _ := r.ReadRune()
            if ch == '\n' {
                offset, err := r.Seek(0, os.SEEK_CUR)
                if err != nil {
                    return nil, err
                }
                pos += offset
                buf.Write(readbuf[0 : offset-1])
                found = true
                break
            }
        }
        if !found {
            buf.Write(readbuf)
            pos += int64(n)
        }
    }
    db.fields = db.fieldsep.Split(buf.String(), -1)
    db.fieldnames = make(map[string]int, len(db.fields))
    for i, v := range db.fields {
        db.fieldnames[v] = i
    }
    db.bound.start = pos
    return db, nil
}

The second constructor assumes that the first line in the text file contains the schema of the data base. It attempts to read this line and parse it to fill both the fields and the fieldnames members. It also saves the ending position of the first line and uses that to define the boundaries for the readers.

func (db *Ffdb) Close() {
    db.file.Close()
}

The Ffdb is at heart a file resource, and must therefore be closed to avoid resource leaks.

The two source files discussed here are available at GitHub: Record and Ffdb

Sunday, September 8, 2013

4.3.3: Example - A Flat-File Database - part 1

The flat file database is a text file in the form of e.g.:
LASTNAME:FIRSTNAME:CITY:STATE:COUNTRY:OWES
Adler:David:New York:NY:US:157.00
Asthon:Elaine:Boston:MA:US:0.00
Dominus:Mark:Philadelphia:PA:US:0.00
Orwant:Jon:Cambridge:MA:US:26.30
Schern:Michael:New York:NY:US:149658.23
Wall:Larry:Mountain View:CA:US:-372.14
Gylfason:Magnús:Reykjavík:NA:IS:20.00

The first line is an optional schema that names the individual columns, while ":" is the column separator. If no schema is in the file we have to supply a list of field names to the Ffdb constructor.

An overview over my implementation of this system is as such:


The Readers package provides iterators that allow us to iterate through text files line by line, the Record package provides an iterator that transforms a stream of lines into a stream of Record structures, the Ffdb provides the flat-file database object and lastly the Query package implements various examples of queries that are possible. This is a somewhat larger example than the previous ones, so we will go through this in more than one post. I think it is best to go through this bottom up, so lets start down by the metal. The Readers package provides two Forward iterators, Forward and Reverse, that iterate through text files line by line. A future solution would be to provide one BiDirectional iterator that could fulfill both roles, but this was simpler and will have to do for now.
type Direction func(*Ffdb) i.Forward

The Direction type is simply the type of the constructors of the readers, this allows us to specify when we create the query whether we want to search forwards or reversed simply by passing the name of the reader to the query.
type reader struct {
    file  *os.File
    pos   int64
    line  string
    err   error
    atEnd bool
    bound Bound
}

The reader structure is the state shared by both the Forward reader and the Reverse reader. It contains the file we are reading and our position in it, current line, last error, an atEnd indicator and the Bound structure which is used to bind the readers within a range of the file. This is so we can exclude the schema header if it is located within the file (usually the header). The readers are valid on the range bound.start <= pos <= bound.end.
func (r *reader) Error() error {
    if r.err == io.EOF {
        return nil
    }
    return r.err
}

func (r *reader) Value() interface{} {
    return r.line
}

func (r *reader) AtEnd() bool {
    return r.atEnd
}

These methods are shared between the readers and are therefore bound to the reader structure.
type forward struct {
    reader
    in *bufio.Reader
}

func Forward(db *Ffdb) i.Forward {
    var itr forward
    if itr.pos, itr.err = db.file.Seek(db.bound.start, os.SEEK_SET); itr.err == nil {
        itr.file = db.file
        itr.bound = db.bound
        itr.in = bufio.NewReader(db.file)
        itr.Next()
    }
    return &itr
}

The forward state is simply the reader state plus a bufio.Reader. This reader is very similar to the one we created in 4.3.3: Example - Filehandle Iterators with the exception of boundaries. The constructor seeks to the beginning position in the file as defined by bound.Start, creates the buffered reader from bufio and reads the first line.
func (f *forward) Next() error {
    if f.err == io.EOF || (f.bound.end > 0 && f.pos >= f.bound.end) {
        f.atEnd = true
        return nil
    }

    f.file.Seek(f.pos, os.SEEK_SET)
    if f.line, f.err = f.in.ReadString('\n'); f.err != nil && f.err != io.EOF {
        return f.err
    }

    f.pos, _ = f.file.Seek(0, os.SEEK_CUR)
    // chomp
    f.line = strings.TrimSuffix(f.line, "\n")
    return nil
}

The Next() method seeks to the last position in the file. This is so we can have many iterators on the same database file active at the same time, each maintaining its own position. It reads the line from the file, saves the new position in the file and chomps of the trailing NL character. A io.EOF or a position beyond the boundaries indicates that we've reached the end of the database for this iterator.
const readbufsize = 4096
type reverse struct {
    reader
    readbufpos, readbuflen int64
    readbuf                []byte
    buf                    bytes.Buffer
}

The Reverse reader is a bit more complicated. It inherits from the reader and adds various buffers and reading positions to it. The strategy here is to read the file backwards in readbufsize chunks, searching through the chunks for NL characters. We need to handle both that each chunk might contain many lines and that any line could span across many chunks.
func Reverse(db *Ffdb) i.Forward {
    whence := os.SEEK_SET
    pos := db.bound.end
    if pos == -1 {
        whence = os.SEEK_END
        pos = 0
    }

    var itr reverse
    if itr.pos, itr.err = db.file.Seek(pos, whence); itr.err == nil {
        itr.file = db.file
        itr.bound = db.bound
        itr.readbufpos = -1
        itr.readbuf = make([]byte, readbufsize)
        itr.Next()
    }
    return &itr
}

The constructor must start by positioning itself at the end of the area that the iterator is valid on, be that the end of the file or the position in bound.end. When then proceed to read the first chunk into our buffer.
func (r *reverse) writeBuffer() {
    var out bytes.Buffer
    out.Write(r.readbuf[r.readbufpos+1 : r.readbuflen])
    if r.buf.Len() > 0 {
        out.Write(r.buf.Bytes())
        r.buf.Reset()
    }

    r.readbuflen = r.readbufpos
    r.readbufpos--
    r.line = out.String()
}

The writeBuffer() writes the current line that is in the chunk to the variable returned by the Value() method. It then appends the leftover from the last iteration.
func (r *reverse) Next() error {
    for {
        if r.readbufpos < 0 {
            if r.pos == r.bound.start {
                r.atEnd = true
                return nil
            }
            r.readbuflen = readbufsize
            if r.pos < readbufsize {
                r.readbuflen = r.pos
            }
            r.pos -= r.readbuflen
            r.file.Seek(r.pos, os.SEEK_SET)
            if _, r.err = r.file.Read(r.readbuf); r.err != nil && r.err != io.EOF {
                return r.err
            }
            r.readbufpos = r.readbuflen - 1
        }

        if r.readbufpos < 0 {
            r.atEnd = true
            return nil
        }

        for ; r.readbufpos >= 0; r.readbufpos-- {
            if r.readbuf[r.readbufpos] == '\n' {
                r.writeBuffer()
                return nil
            }
        }

        if r.readbufpos < 0 && r.pos == r.bound.start {
            r.writeBuffer()
            return nil
        }

        var joinbuf bytes.Buffer
        joinbuf.Write(r.readbuf[0:r.readbuflen])
        if r.buf.Len() > 0 {
            joinbuf.Write(r.buf.Bytes())
        }
        r.buf = joinbuf
    }
    return nil
}

The Next() method starts by checking the readbufpos variable, if it is below zero we must read a new chunk from the file into our buffer. Normally we try to read readbufsize number of characters but if we are closer than that to the start of the file we simply read the rest of the file. If after reading readbufpos is still below zero we are finished. Otherwise we loop through the buffer searching for a NL character. If we find it we write out the buffer and return, otherwise we join the buffer with the previous buffer and iterate again. A special case is if we find no NL character but move beyond both the buffer and the reading boundary; then we've found the last (first) line in the file. Get the source at GitHub.