Record types & fields
A record type is a blank form: the fields one kind of thing has, their types and the rules on each. The CLI and the API call it a schema. You design it once; every record of that type is one filled-in copy of the form, and lives in a collection. Types can go inside other types (a Site holds Visits, which hold Samples). New to these ideas? Start with Record types, collections and records.
A worked example
civex schema create site --label "Site"
civex schema add-field site name --type string --required
civex schema add-field site location --type geo
civex schema create visit --parent site --label "Visit"
civex schema add-field visit visited_on --type date --required --precision month
civex schema add-field visit team --type string
civex schema create sample --parent visit --label "Sample"
civex schema add-field sample number --type integer --min 1
civex schema add-field sample depth --type float --unit m --min 0
civex schema add-field sample taken_at --type datetime
civex schema add-field sample photo --type file --accept ".jpg,.png"
civex schema add-field sample reading --type file --accept ".csv"
civex schema update sample --display-template "Sample {number:02}"
civex schema show sample
Sample (sample)
Inherits: visit
Label Field Type Required Source
Number number integer sample
Depth depth float sample
Taken At taken_at datetime sample
Photo photo file sample
Reading reading file sample
Visited On visited_on date yes ↑ visit
Team team string ↑ visit
Name name string yes ↑ site
Location location geo ↑ site
Three record types, designed once. From here on the project only gets records: sites, visits and samples.
In the app: Record types → New record type, then Add field on its page. Type the label and the name fills itself in. The rules offered depend on the kind of field you pick.
Field types
| Type | In the app | Stores | Typed as |
|---|---|---|---|
string |
Text | One line of text | North Ridge |
longtext |
Text box | Several lines | (newlines kept) |
integer |
Whole number | 42 |
|
float |
Number | Optionally in a fixed unit | 3.14, 1024 ft |
boolean |
Yes/no | yes, true, 1 / no, false, 0 |
|
date |
Date | A day, or a month or year if allowed | 2024-03-15, 2024-03, 2024 |
datetime |
Date and time | A UTC instant, to the second | 2024-03-15T09:30:00 |
geo |
Location | A GeoJSON point, line or area | 56.12, -3.41 |
file / file_list |
File / Files | References to stored files | a path |
reference / reference_list |
Link(s) to records | Record ids | an id or unique prefix |
tags |
Tags | A list of short labels | seal, tagged |
url |
Web address | http(s):// text |
https://example.org |
enum |
Choice (legacy) | Use string with --choices instead |
|
formula |
Formula | Nothing: worked out from other fields when read | (can't be typed in) |
Rules on a field
Rules are checked whenever a record is saved: in the app, the CLI, the API, imports and workflows.
| Flag | Types | Example |
|---|---|---|
--required / --optional |
all | |
--min / --max |
integer, float |
--min 0 --max 100 |
--choices |
string |
--choices "pass,fail,inconclusive" (a dropdown in the app) |
--max-length |
string, longtext |
--max-length 500 |
--unit |
float |
--unit m, --unit degC |
--precision |
date |
--precision month (accepts 2024-03 and 2024-03-15) |
--geometry-types |
geo |
--geometry-types Point,Polygon |
--bbox |
geo |
--bbox "-12,48,4,62" (west,south,east,north) |
--accept |
file, file_list |
--accept ".jpg,.png" |
--max-size |
file, file_list |
--max-size 10485760 (bytes) |
--references |
reference, reference_list |
--references species |
--from-file + --filename-pattern |
string, integer, float, date, datetime |
--from-file reading --filename-pattern "YYYYMMDD[-_]HHmmSS" (read from the file's name when the file is attached or replaced; see Fill fields from file names) |
Changing a rule doesn't re-check the values already stored. Before you save,
the field editor says how many records hold a value the new rules refuse (or
leave a newly required field empty), names a few, and links to the
data check that lists them all;
civex schema update-field says the same and asks before going on
(POST /api/schemas/{schema}/fields/{field}/check with the rules you would
set). Those records keep their values and can still be edited: a save checks
only the values it changes, so a broken value is refused only when it is
changed to another one the rules refuse.
Some rules are set in the app (or over the API, as restrictions) only: a
date/datetime minimum and maximum, a datetime field's own timezone, and a
file's download-name template.
Units
A float with a unit stores every value in that unit. Conversion happens only
as data comes in: typing 1024 ft into a metres field stores 312.1152, and the
CSV import asks which unit each column is in. Changing a field's unit later
relabels it and converts nothing, so to switch units add a new field. Units
civex doesn't know (umol/kg) are plain labels.
Partial dates
--precision is the least precise value a date field accepts: year takes
2019, 2019-06 and 2019-06-14; month the last two; day (default) only
full dates. Values are stored as written, never padded. Minimums and maximums
compare whole periods, so 2020 fails a minimum of 2020-03.
Times and timezones
A datetime is stored as a UTC instant. A value with an offset
(2024-03-15T09:30:00-05:00) is exact. A value without one, from a CSV, an
instrument or a file name, is read as wall time in the field's timezone, else
the collection's, else UTC:
Times that don't exist or happen twice at a DST change are rejected rather than guessed: add an offset. Changing a timezone changes how values are shown and how new ones are read, never what is stored.
Locations
A geo field holds GeoJSON in WGS84 (longitude first). It reads the ways people
write coordinates:
Exports and CSVs write a point as lat, lon, and other shapes as GeoJSON. A point
may carry uncertainty_m and an elevation (negative for depth). A --bbox with
west greater than east crosses the 180th meridian.
On a record, Edit on map… places a point or draws a line or area, takes
coordinates in any format, imports GeoJSON, GPX, KML or WKT, and changes nothing
until Apply. The map works offline with built-in coastlines. For street
detail, set a tile server in Settings → Map ([map] tile_url and
attribution in config.toml), following that provider's terms.
Names and labels
name |
label |
|
|---|---|---|
| In the app | Key, folded under the name with a change link | Name |
| Is | the machine key | the display name |
| Looks like | visited_on (lowercase, digits, _) |
Visited On (anything) |
| Used by | workflow YAML, CSV headers, templates, API paths | the app, schema show, forms |
| Changing it | a real rename (see below) | always safe |
Without a label, one is derived from the name. Records store values by field id, so a rename never touches stored data, and templates are updated for you. Workflow YAML that names the old field must be updated by hand.
civex schema update-field sample number --label "Sample number" # safe
civex schema update-field sample number --rename sample_no # update workflows
civex schema lint # names that aren't valid slugs
Naming records and files
A record's name comes from its record type's template. It shows in lists, breadcrumbs, references and export folder names.
civex schema update sample --display-template "{species.common}-{taken_at:YYYY-MM}-{number:03}"
civex schema update sample --clear-display-template
| Write | Gives |
|---|---|
{team} |
the value |
{team:upper}, :lower, :title |
NORTH RIDGE, … |
{team:slug} |
north_ridge |
{team:trunc(3)} |
Nor |
{visited_on:YYYY-MM-DD} |
a date pattern (YYYY MM DD HH mm SS) |
{number:03}, {depth:.1f} |
007, 12.5 |
{species.common} |
a field of the record the reference species points at |
{schema}, {id} |
the record type's name, the record's short id |
{{, }} |
literal braces |
- A blank value is dropped with the separator beside it:
{team} - {number}with no team gives just7. - The first nameable field you add becomes the template, so new record types name records from the start.
{ref.field}reaches one level through a singlereferencefield that names its target schema. Editing the target renames at once.- Renaming or deleting a field updates every template that uses it.
A file field's download name (set on the field in the app) uses the same
builder. It names the stem, keeps the file's own extension, and may use fields of
records above and through any reference:
{species.common}_{name}_{number:02}.
Formulas
A formula field is worked out from the record's other fields each time the record is read: a duration, a ratio, a converted unit, a label made of two codes. Nothing is stored, so it never drifts from the values it reads and changing the formula changes every record at once, with no run to wait for.
civex schema add-field patient bmi --type formula --expression "mass / height ** 2" --decimals 1
civex schema add-field patient stay --type formula -e "days_between(admitted, discharged)" --result integer
civex schema add-field dive depth_m --type formula -e "depth_ft * 0.3048" --unit m
civex schema add-field sample code --type formula -e 'concat(site.code, "-", number)'
civex schema preview-formula patient "round(mass / height ** 2, 1)" --record 3f2a
| Write | Means |
|---|---|
mass, site.code |
a field of the record (or of a record above it), or a field of the record a link points at |
12, 0.3048, "text", True |
a number, text, yes/no |
+ - * / // % ** |
arithmetic (+ also joins two texts) |
== != < <= > >=, and or not |
comparisons and logic |
"deep" if depth > 200 else "shallow" |
a choice |
round(x, 2), abs, min, max, sqrt, log(x[, base]), exp, floor, ceil |
numbers |
concat(a, "-", b), str, upper, lower, len |
text (and len of tags) |
days_between(start, end), hours_between(start, end), year, month, day, date_add(date, days) |
dates and times |
coalesce(value, fallback) |
the first value that isn't blank |
- Blank in, blank out: a formula reading an empty field is empty, unless
coalescegives it something else. - What it gives (
--result:float,integer,string,boolean,date,datetime) is worked out from the formula when you leave it out. A decimal result can have--decimalsand a--unit, which tables and DataFrames carry. - A value that can't be worked out for one record (dividing by zero, a value of the wrong kind) is left blank there with the reason shown on the record; the rest of the list is unaffected.
- The formula is checked when you save it: the fields must exist and fit, and formulas can't read each other in a circle. One formula can read another, and a field of a record above, including its formula. A link reaches only stored values of the record it points at.
- Renaming a field rewrites the formulas that read it. A field a formula reads can't be deleted until the formula is changed or deleted.
- A formula can't be required, have a default, be part of a record's name or a unique key, or be set by an edit, an import or a workflow (a value sent for it is ignored).
- Lists can't be filtered, sorted or summarised by a formula: the database
holds no value for it. Formulas do show as columns in the explorer and in
exported tables, and in
ctx.frame()/ctx.rows(), typed by what they give. - Over the API a record's formulas are in
derived(never indata), withformula_errorssaying why one is blank. History, sync and bundles hold no formula values; a bundle carries the formula itself.
In the app, the field editor's Formula box puts field names and functions in at the cursor and shows what the formula gives for the latest record of that kind, or one you pick.
Types inside other types
In the app this is Goes inside when you create the type. A record of a child type sits inside a record of the parent type: every sample is filed under its visit, and every visit under its site. A child stores only its own fields, but filters, sorts, columns and templates can use its parents' fields, and parents can be filtered by their children ("sites that have a sample where…"). The parent can't be changed after creation.
This is still three record types and many records. Don't make a record type per site: Site is the type, and North Ridge and East Shore are two records of it.
Keeping records unique
civex schema add-unique sample number # no two samples in a visit share a number
civex schema unique sample
civex schema remove-unique sample number
In the app: the record type's Uniqueness tab.
- Checked among records of that type under the same parent (the samples of one visit), or for top-level records in the same collection.
- A record with a blank in any of the rule's fields isn't held to it.
- Only the type's own scalar fields (text, numbers, dates, yes/no, choices, links). Not files, locations, tags or lists.
- You can't add a rule while records already break it. The message names clashing records.
- A refused save names the record that already has the values. Workflow steps
skip such rows and list them in a
duplicatesoutput. - A deleted record frees its values. Restoring it is refused if another record took them.
Charts for a kind
A kind of record says which charts its lists open with, on its Charts tab: the same chart cards as beside any list of records (see Charts), drawn here over every record of the kind. Add, reorder or remove them, here or beside any list of the kind; each change is saved for everyone, is in the kind's history and syncs. A kind starts with no charts.
A chart follows a field that is renamed, and goes when a field it uses is deleted.
civex schema charts list sample
civex schema charts add sample --by site --measure mean:depth
civex schema charts add sample --by taken:month
civex schema charts add sample --map position --title "Where they are"
civex schema charts remove sample <id>
civex schema charts clear sample # no charts again
The API is PUT /api/schemas/{schema}/charts with the whole list.
Faster sorting and filtering: indexed fields
With hundreds of thousands of records of one type, sorting a list by a field, or counting the records a filter on it matches, can take seconds. An index on the field makes those fast (a sort's first page in a millisecond at a million records) and makes saving records of that type slightly slower.
civex schema index sample depth # index it
civex schema index sample depth --off # stop
civex db indexes # what is indexed, and built yet
civex db indexes --reconcile # build what is missing now, showing progress
In the app: the field's settings, Indexed.
- Fields in a uniqueness rule are always indexed (every save checks them).
- Only single values can be indexed (text, numbers, dates, yes/no, choices, links), like a uniqueness rule. An inherited field is indexed on the type that defines it.
- An index belongs to this computer's database: it is a setting in
config.toml([db] indexed_fields, by field id, so renaming a field keeps it), never synced or in the history. After moving the database (civex db move) the same indexes are built in the new one. - Indexes are always built and dropped in the background: by a running
civex serve(the status bar shows "Speeding up sorting on …"), or by a process the command that changed them starts, so the command returns at once. Lists work meanwhile, only slower.civex db indexes --reconciledoes it in front of you instead. - On a big table a build takes a while (a minute or two at a million records). On SQLite a build gives way whenever someone saves a record, and starts again once nobody has saved for a few seconds, so saving never waits for it; under constant saving an index waits for a pause.
- Indexes help sorting and filtering inside a collection. Counting every record of a type, and text search, still read every record.
Changing and deleting fields and types
civex schema update-field sample depth --min 0 --max 50 # merges with existing rules
civex schema update-field visit team --optional
civex schema update-field sample depth --clear-restrictions
civex schema remove-field sample depth
civex schema delete sample
A field's type can't change. Removing a field is reversible: records keep their values, shown under Deleted fields on the record, and restoring the field brings them back. Deleting a record type takes its records to Recently Deleted. See Deleting & restoring data.