Skip to content

Commit

Permalink
#6: documenting primary key setting and getting
Browse files Browse the repository at this point in the history
  • Loading branch information
Georges Labrèche committed Oct 10, 2017
1 parent 130a96a commit a81f083
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
38 changes: 35 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,40 @@ System.out.println(isValid);
// false
```

### Casting
## Row Casting
## Setting Primary Key
### Single Key
```java
Schema schema = new Schema();

Field idField = new Field("id", Field.FIELD_TYPE_INTEGER);
schema.addField(idField);

Field nameField = new Field("name", Field.FIELD_TYPE_STRING);
schema.addField(nameField);

schema.setPrimaryKey("id");
```

### Composite Key
```java
Schema schema = new Schema();

Field idField = new Field("id", Field.FIELD_TYPE_INTEGER);
schema.addField(idField);

Field nameField = new Field("name", Field.FIELD_TYPE_STRING);
schema.addField(nameField);

Field surnameField = new Field("surname", Field.FIELD_TYPE_STRING);
schema.addField(surnameField);

schema.setPrimaryKey(new String[]{"name", "surname"});
String[] compositeKey = schema.getPrimaryKey();
```


## Casting
### Row Casting
To check if a given set of values complies with the schema, you can use `castRow`:

```java
Expand All @@ -239,7 +271,7 @@ Object[] castRow = schema.castRow(row);

If a value in the given set of values cannot be cast to its expected type as defined by the schema, then an `InvalidCastException` is thrown.

## Field Casting
### Field Casting
Data values can be cast to native Java objects with a Field instance. This allows formats and constraints to be defined for the field in the [field descriptor](https://specs.frictionlessdata.io/table-schema/#field-descriptors):

```java
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/io/frictionlessdata/tableschema/Schema.java
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,11 @@ public boolean hasFields(){
return !this.getFields().isEmpty();
}

/**
* Set single primary key.
* @param key
* @throws InvalidPrimaryKeyException
*/
public void setPrimaryKey(String key) throws InvalidPrimaryKeyException{
if(this.hasField(key)){
this.key = key;
Expand All @@ -255,6 +260,11 @@ public void setPrimaryKey(String key) throws InvalidPrimaryKeyException{

}

/**
* Set composite primary key.
* @param compositeKey
* @throws InvalidPrimaryKeyException
*/
public void setPrimaryKey(String[] compositeKey) throws InvalidPrimaryKeyException{
for (String aKey : compositeKey) {
if (!this.hasField(aKey)) {
Expand Down

0 comments on commit a81f083

Please sign in to comment.