Skip to content

Commit

Permalink
Constraints example.
Browse files Browse the repository at this point in the history
  • Loading branch information
danielfireman committed Sep 1, 2020
1 parent 279f32d commit 3cc64ed
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/constraints/capital.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
id,capital,url
1," 39,00",http://www.test.com
2,"23,00",http://www.test.de
3,"36,00",http://www.test.uk
4,"20,00",http://www.test.co.il
57 changes: 57 additions & 0 deletions examples/constraints/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package main

import (
"log"

"github.com/frictionlessdata/tableschema-go/csv"
"github.com/frictionlessdata/tableschema-go/schema"
)

// Example of how to read, validate and change a schema.
func main() {
// Reading schem.
capitalSchema, err := schema.LoadFromFile("schema.json")
if err != nil {
log.Fatal(err)
}
// Validate schema.
if err := capitalSchema.Validate(); err != nil {
log.Fatal(err)
}

// Printing schema fields names.
log.Println("Fields:")
for i, f := range capitalSchema.Fields {
log.Printf("%d - %s\n", i, f.Name)
}

// Working with schema fields.
if capitalSchema.HasField("Capital") {
log.Println("Field capital exists in schema")
} else {
log.Fatalf("Schema must have the field capital")
}
field, _ := capitalSchema.GetField("URL")
if field.TestString("http://new.url.com") {
value, err := field.Cast("http://new.url.com")
log.Printf("URL unmarshal to value: %v\n", value)
if err != nil {
log.Fatalf("Error casting value: %q", err)
}
} else {
log.Fatalf("Value http://new.url.com must fit in field capital.")
}

// Dealing with tabular data associated with the schema.
table, err := csv.NewTable(csv.FromFile("capital.csv"), csv.LoadHeaders())
var capitals = []struct {
ID int
Capital float64
URL string
}{}

if err := capitalSchema.CastTable(table, &capitals); err != nil {
log.Fatalf("Error casting table: %q", err)
}
log.Printf("Cast Table: %+v\n", capitals)
}
33 changes: 33 additions & 0 deletions examples/constraints/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"fields": [
{
"name": "ID",
"title": "",
"description": "",
"type": "integer",
"format": "default",
"constraints": {
"unique": true,
"required": true
}
},
{
"name": "Capital",
"title": "",
"description": "",
"bareNumber": false,
"decimalChar": ",",
"type": "number",
"constraints": {
"required" :true,
"minimum": "0"
}
},
{
"name": "URL",
"title": "",
"description": "",
"type": "string"
}
]
}

0 comments on commit 3cc64ed

Please sign in to comment.