csvstorage

package module
v0.0.0-...-48a0d3e Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2015 License: Unlicense Imports: 4 Imported by: 0

README

csvstorage

Хранение данных в csv-файлах с возможностью манипулировать ими с помощью некого подобия ActiveRecord

Примеры использования

Создание схемы данных для таблицы
id := csvstorage.CSVField{"id", csvstorage.CSVFieldTypeInt}
title := csvstorage.CSVField{"title", csvstorage.CSVFieldTypeText}
csvstorage.CreateCSVTableSchema("table", id, title)

В результате будут созданы два файла table.csv и table.schema для хранения данных и схемы данных соответственно

table.schema:

id,int
title,text
Вставка новых записей в таблицу

// CSVValueRecord == map[string]string
r1 := make(csvstorage.CSVValueRecord)
r1["id"] = "1"
r1["title"] = "one"

r2 := make(csvstorage.CSVValueRecord)
r2["id"] = "2"
r2["title"] = "two"
csvstorage.Insert("table").Values(r1, r2).Do()

table.csv:

1,one
2,two

Простая выборка
q := csvstorage.Select("id", "title").From("table")
fmt.Println(q.Do())

Результат

[map[id:1 title:one] map[id:2 title:two]]
Создание условий для фильтрации

Условия могут быть простыми и составными. Простые условия лишь проверяют данные на равенство. Составные содержат логический оператор (AND/OR) и два условия, которые погут быть как простыми, так и составными

Пример простого условия

simpleWhere := csvstorage.NewSimpleWhere("id", "=", "1")
q := csvstorage.Select("id", "title").From("table").Where(simpleWhere)
fmt.Println(q.Do()

Результат

[map[id:1 title:one]]

Пример составного условия, содержащего два простых условия

simpleWhere1 := csvstorage.NewSimpleWhere("id", "=", "1")
simpleWhere2 := csvstorage.NewSimpleWhere("title", "=", "two")
complexWhere := csvstorage.NewComplexWhereCondition("OR", simpleWhere1, simpleWhere2) // также можно использовать логический оператор "AND"

q := csvstorage.Select("id", "title").From("table").Where(complexWhere)
fmt.Println(q.Do())

Результат

[map[id:1 title:one] map[id:2 title:two]]

Кроме случая выборки, условия можно использовать при удалении и измении данных (см.ниже)

Изменение записей

! Если при выполнении изменения данных не указано условие, то изменения применятся ко всем записям в таблице !

simpleWhere := csvstorage.NewSimpleWhere("id", "=", "1")
r1 := make(csvstorage.CSVValueRecord)
r1["title"] = "~1~"
csvstorage.Update("table").Set(r1).Where(simpleWhere).Do()

table.csv до изменения

1,one
2,two

table.csv после изменения

1,~1~
2,two

Удаление записей

! Если при выполнении удаления данных не указано условие, то удалятся все записи в таблице !

simpleWhere := csvstorage.NewSimpleWhere("id", "=", "1")
csvstorage.Delete("table").Where(simpleWhere).Do()

table.csv до изменения

1,~1~
2,two

table.csv после изменения

2,two

Documentation

Overview

Пакет позволяет манипулировать записями в csv файлах с помощью sql-подобных запросов

Пример добавления новых записей в таблицу

r1 := make(csvstorage.CSVValueRecord)
r1["id"] = "6"
r1["title"] = "six"
csvstorage.Insert("index").Values(r1).Do()

Пример создания схемы с помощью функции CreateCSVTableSchema

id := CSVField{"id", CSVFieldTypeInt}
title := CSVField{"title", CSVFieldTypeText}
CreateCSVTableSchema("table", id, title)

будут созданы два файла table.csv и table.schema

table.schema будет содержать:

id,int
title,text

Пример использования составного where-условия:

simpleWhere1 := csvstorage.NewSimpleWhere("id", "<", "3")
simpleWhere2 := csvstorage.NewSimpleWhere("content", "=", "четыре")
complexWhere := csvstorage.NewComplexWhereCondition("OR", simpleWhere1, simpleWhere2)
q := csvstorage.Select("content", "id").From("index").Where(complexWhere)

Index

Constants

View Source
const (
	CSVFieldTypeInt  = "int"
	CSVFieldTypeText = "text"
)

Variables

This section is empty.

Functions

func CreateCSVTableSchema

func CreateCSVTableSchema(table string, fields ...CSVField) error

Types

type CSVField

type CSVField struct {
	FieldName, FieldType string
}

type CSVTableSchema

type CSVTableSchema map[string]CSVTableSchemaRecord

func ReadSchema

func ReadSchema(r io.Reader) CSVTableSchema

type CSVTableSchemaRecord

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

type CSVValueRecord

type CSVValueRecord map[string]string

type DeleteQuery

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

Пример удаления записи с использование where

simpleWhere := csvstorage.NewSimpleWhere("id", "<", "3")
csvstorage.Delete("index").Where(simpleWhere).Do()

func Delete

func Delete(table string) *DeleteQuery

func (*DeleteQuery) Do

func (this *DeleteQuery) Do()

func (*DeleteQuery) Where

func (this *DeleteQuery) Where(where WhereCondition) *DeleteQuery

type InsertQuery

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

func Insert

func Insert(table string) *InsertQuery

func (*InsertQuery) Do

func (this *InsertQuery) Do()

func (*InsertQuery) Values

func (this *InsertQuery) Values(values ...CSVValueRecord) *InsertQuery

type SelectQuery

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

func Select

func Select(fields ...string) *SelectQuery

инициализация запроса, в качестве аргументов указываются поля для выборки

func (*SelectQuery) Do

func (this *SelectQuery) Do() SelectQueryResult

выполнение запроса

func (*SelectQuery) From

func (this *SelectQuery) From(table string) *SelectQuery

указание таблицы, из которой будет производиться выборка

func (*SelectQuery) Limit

func (this *SelectQuery) Limit(limit int) *SelectQuery

максимальное количество записей в результате запроса

func (*SelectQuery) Where

func (this *SelectQuery) Where(cond WhereCondition) *SelectQuery

указание необходимых фильтров, с интерфейсом WhereCondition (см. csvwhere.go)

type SelectQueryResult

type SelectQueryResult []SelectQueryResultRecord

type SelectQueryResultRecord

type SelectQueryResultRecord map[string]string

type UpdateQuery

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

func Update

func Update(table string) *UpdateQuery

func (*UpdateQuery) Do

func (this *UpdateQuery) Do()

func (*UpdateQuery) Set

func (this *UpdateQuery) Set(value CSVValueRecord) *UpdateQuery

func (*UpdateQuery) Where

func (this *UpdateQuery) Where(where WhereCondition) *UpdateQuery

type WhereComplexCondition

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

сложное условие, может использовать логические операции AND, OR

func NewComplexWhereCondition

func NewComplexWhereCondition(logicCond string, cond1, cond2 WhereCondition) WhereComplexCondition

func (WhereComplexCondition) Compute

func (this WhereComplexCondition) Compute(record []string, schema CSVTableSchema) bool

type WhereCondition

type WhereCondition interface {
	Compute([]string, CSVTableSchema) bool
}

метод Compute должен выполнять фильтраци полей записи и указанных условий

type WhereSimpleCondition

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

простое условие, с равенством/неравенством

func NewSimpleWhere

func NewSimpleWhere(field, op, value string) WhereSimpleCondition

func (WhereSimpleCondition) Compute

func (this WhereSimpleCondition) Compute(record []string, schema CSVTableSchema) bool

Jump to

Keyboard shortcuts

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