How we run one formula language in JavaScript and in Postgres
How Emberblocks type-checks a formula once, evaluates it in JavaScript or compiles it to Postgres, and how a parity test keeps both engines in agreement.
Published 16 min read
On this page
- Why one formula has to run in two places
- The pipeline: parse, check once, then evaluate or lower
- Semantics come from SQL, not from JavaScript intuition
- Where the two engines differ, on purpose
- The parity sweep: the same rows through both engines
- Fail closed: what happens to a formula the checker rejects
- What we would tell someone building the same thing
Emberblocks has one formula language. A builder writes [Qty] * [Price] or IF([Qty] = 0, 0, [Price] / [Qty]) the way they would in a spreadsheet, and that text ends up in one of two engines. A JavaScript evaluator computes it against a single row, in the browser or on our server. A compiler lowers it to a Postgres expression that runs inside the query. Both have to give the same answer, including for blank cells, which is where formula engines most often disagree with themselves.
This post walks through how that works: why one language needs two engines, the pipeline that checks a formula once and hands the result to both, where the engines are allowed to differ, the test that runs the same rows through both and fails on any mismatch, and what happens to a formula the checker refuses.
Why one formula has to run in two places
Formulas show up all over an app. Some ask about one row the browser already has: should this button show on this record, is the number typed into this form field valid, what does a new record start with, what does this text block say. Sending each of those to the server would put a network round trip behind every keystroke and every row on screen, so they run in JavaScript, next to the data. Forms and actions lean on this the most.
Other questions only the database can answer. A role's row filter decides which rows leave the server at all. It cannot run in the browser, because the browser would first have to receive the rows it is not allowed to see. A Live formula field is a column with no storage: it is computed fresh on every read, it can be sorted on, and it can follow a reference to another table or count the child rows that point at this one. Doing that in JavaScript would mean shipping every related row to wherever the formula runs. So those compile to SQL and run inside the query.
| Where the formula is used | Engine | Why |
|---|---|---|
Visible if on actions, fields and blocks | JavaScript, in the browser; SQL when the rule reads other rows | One row, already loaded, no round trip |
Valid if and default values in forms | JavaScript, in the browser; Valid if again on the server when a form creates a row | Instant feedback first, enforcement on save |
| Stored computed fields | JavaScript, on the server, when the row is written | One engine for every write path |
| Row filters on blocks and roles, record filters | SQL | Decides which rows leave the database |
| Set-value actions | SQL, inside the update | The new value can read the row as it is stored |
| Live formula fields | SQL, on every read | Needs other rows: hops, counts, sums |
The stored computed field is the interesting row. Its value is written to a real column whenever the row changes, and it is evaluated by the same JavaScript engine the browser uses for defaults and validation, never by the SQL compiler. That way the value cannot depend on which write path produced it: a form save, a CSV import and a workflow step all compute it the same way. Even the builder uses both engines. The formula editor checks your formula in the browser as you type, while its preview runs the formula through the real SQL compiler against a few rows of your data, so the preview shows what a Live formula field will return.
The pipeline: parse, check once, then evaluate or lower
Every formula goes through the same three steps, and the first two are shared by both engines.
- Lex and parse. A small hand-written recursive-descent parser turns the text into a syntax tree. The grammar fits in a code comment: comparison is non-associative, so chaining two comparisons is an error rather than a surprise;
&joins text;[Status]names a column on the current row, and[Category].[Name]follows a reference to another table, up to two hops. Comments in//and/* */style are allowed, which matters once formulas get long. Length and node-count caps are enforced here. - Type-check. The checker resolves every
[Name]against an environment built from the app definition (tables, fields and their kinds), infers a type for every node, and records how each reference resolved: a column on this row, a chain of reference hops, a child table forCOUNT(), a table and column pair forLOOKUP(). Arity lives here and only here.AND()takes at least two conditions,IF()takes exactly three parts whose results share a type, and a text literal compared with a date must be written as YYYY-MM-DD. - Evaluate or lower. The JavaScript evaluator walks the tree against one row. The SQL lowering walks the same tree and emits a Postgres expression. Neither one resolves names or works out types again: both read the annotations the checker left on the tree.
[Qty] * [Price] * (1 - [Category].[Discount] / 100)
IF([Qty] = 0, 0, [Price] / [Qty])
COUNT([Notes], [Billable])The checker also takes a context, which is how one language can have functions that only make sense in some places. REFROWS(), which returns a list of related records, is legal only in a Live formula field's own formula. The travel-time functions, which call a paid routing service, are legal only in a stored computed field. RECORD[Name], which reads the record a record page is showing, is legal only where a record is in context, such as that page's filters. Used anywhere else, each fails the check with a message that says where it does work, instead of producing a value with no meaning.
Names resolve the way people expect: an exact match first, then a unique case-insensitive one, and an ambiguous name is an error that lists the candidates. Date literals are settled at check time too. In [Due] >= "2026-07-01" the checker sees a text literal next to a date column, validates its format and records a coercion, so the SQL side casts the bound value to a date and the JavaScript side parses it the same way.
What the SQL side emits
The lowering produces Kysely SQL fragments. Every identifier comes from the app definition and the introspected schema, never from the formula text: [Price] resolves to a field id, the field id maps to a column the introspection snapshot confirms exists, and that column is emitted as a quoted identifier. Every literal, and the signed-in user's email and role, is a bound parameter. There is no path from formula text to raw SQL.
A reference hop becomes a correlated scalar subquery on the target table's primary key, which composes safely under NOT and OR. A Live formula field that is a bare COUNT(), SUM() or REFROWS() takes a different route on a list read: unless the page is sorted by it, it runs as one grouped query over the page's parent ids after the page loads, instead of one subquery per row, and the values are merged into the rows. A formula field that names another formula field, like [Total] * 1.24, inlines that field's formula rather than reading a column, with a depth limit on the chain and loop detection at publish.
Semantics come from SQL, not from JavaScript intuition
The rule that makes parity possible is written at the top of the evaluator: its semantics are transcribed from the SQL lowering. Wherever JavaScript and Postgres would naturally disagree, the language picks one behavior, almost always the database's, and the evaluator implements it on purpose. Blank cells are where this matters most. In plain JavaScript null * 3 is 0, null > 10 is false, and joining "Drill x" with a null gives "Drill xnull". None of that is what a builder means.
| Formula | When the inputs are blank | Rule |
|---|---|---|
[Qty] * [Price] | Blank | Arithmetic with a blank operand is blank, as in SQL |
[Name] & " x" & [Qty] | "Drill x" | Joining text treats a blank as empty text and is never blank itself |
[Price] > 10 | Blank | A comparison with a blank is unknown, not false |
OR([Phone] = "x", [Active]) | With Phone blank: true if Active is true, otherwise blank | Three-valued logic: one true settles OR, one false settles AND |
IF([Active], [Price], 0) | 0 | An unknown condition takes the else branch, like CASE WHEN |
ISBLANK([Email]) | True, also for empty text | Never blank itself |
CONTAINS([Email], "acme") | False | A blank haystack reads as empty text; only a blank needle is unknown |
Division by zero is the one place Postgres raises an error instead of returning blank, so the evaluator refuses to produce a value there rather than invent Infinity. The safe pattern is the one in the lab: IF([Qty] = 0, 0, [Price] / [Qty]). Clocks follow the same discipline. The evaluator never reads a hidden clock: a formula that uses TODAY() or NOW() only evaluates if the caller passes the current time in, which keeps the module pure and its tests deterministic.
The one formula that means clear this field
The language has no NULL keyword. A set-value action or a workflow step that should empty a field uses a formula that is exactly an empty string, "". That shape, and only at the root, means write NULL, and it is accepted for any column type, so it can clear a number or a date as well as text. "" & [Name] is still ordinary text. One small function decides whether a formula is that sentinel, and the builder's warning badge, the publish validator and the SQL compiler all call it, so the three cannot disagree about what an empty formula means. Filters ignore the rule: a filter still needs a condition.
Where the two engines differ, on purpose
Parity does not mean the engines can do the same things. The browser has one row; the database has all of them. So the language has three groups of formula: ones both engines evaluate, ones only SQL can evaluate, and a few only JavaScript can.
Hops and aggregates exist only in SQL
A row loaded in the browser does not contain its category's discount or the hours logged against it. Formulas that need other rows are SQL-only:
[Category].[Name]
SUM([Notes], [Hours], [Billable])
LOOKUP([Category].[Code], [Categories].[Code], [Categories].[Discount])
SELECT(Notes[Hours], [Item] = THISROWID())If one of these reaches the JavaScript evaluator, it returns no value and says why: "This reference reads related rows and can't be evaluated here." It never guesses. Publish uses the same knowledge up front. A row-scope check walks the tree and flags every aggregate and every multi-step reference, and that is a hard error for places that can only ever evaluate in JavaScript, such as stored computed fields and workflow row triggers. For action visibility the runtime splits instead: rules the browser can evaluate run there, and the rest are computed in the same SQL query that loads the record and shipped as a true or false flag. That flag is computed with IS TRUE, so an unknown verdict hides the action, which is exactly what the browser does with an unknown result.
Text masks
TEXT([Due], "DD/MM/YYYY") gives the same string in both engines. The evaluator implements the numeric date tokens of Postgres's to_char (YYYY, YY, MM, DD, HH24, HH12, HH, MI and SS), passes separators through and copies quoted text as it is. Number masks such as TEXT([Price], "FM999990.00") are SQL-only, and the evaluator refuses them.
Here is a divergence we have documented rather than closed. The checker only validates a mask's alphabet (letters, digits and a few separators), so TEXT([Due], "Q") passes. Postgres reads Q as the quarter and returns 1 to 4. The evaluator does not implement Q, so it fails closed and returns nothing. In a Live formula field the formula works; in a rule the browser evaluates, it produces no value, which a Visible if treats as hidden. The Formula Lab marks that formula SQL-only and asserts that the JavaScript side refuses it, so the behavior cannot drift silently. Narrowing the checker to the tokens both engines share would close the gap, at the cost of rejecting masks that work in Live formula fields today.
The rest of the list
The other accepted divergences are written down in comments next to the code that causes them, so the list below is not reconstructed from memory:
- Dates and date-times are modeled in UTC, and match Postgres when the database session runs in UTC.
- Text ordering uses JavaScript's code-unit order. That matches Postgres under the C collation and for plain ASCII; a locale collation can sort accented names differently.
- Number to text uses JavaScript's own formatting, so a scaled
numericcolumn that keeps trailing zeros in Postgres (7.50) reads 7.5 in the browser. TODAY()andNOW()use the clock of whatever runs the JavaScript, usually the browser, and the database's clock in SQL.JSONGET()on a JSON object returns JSON text in both engines, but Postgres formats it differently fromJSON.stringify, so the parity test compares those cells as JSON.- A few text helpers exist only in JavaScript.
ENCODEURL(),TOJSON()andJSONESCAPE()shape text for workflow emails and API calls and have no SQL form, so publish refuses them in filters and set-value formulas.
These are acceptable because of where each engine's answer counts. What the browser decides is presentation: whether a button shows, what a field starts with. The server checks every action again when it runs, so a wrong guess in the browser is cosmetic, not a hole. What has to be right, such as which rows a role can read, is decided in SQL.
The parity sweep: the same rows through both engines
The expressions package has golden fixtures for the evaluator: small rows on a synthetic schema with hand-written expected values. They are deliberately narrow. The claim that matters, that both engines agree on real data of every field type, needs both engines on the same rows of a real app. That is the job of the Formula Lab, an API test suite that builds a real app in our test workspace and drives it through the same API the product uses.
- A table with every field type. Items has one column of each type, from text, number and date to reference, multi-reference, address and JSON, plus two stored computed columns. Categories is what Items references, and Notes is a child table that points at Items, for the counting family.
- A row that is blank everywhere. Five items are seeded on every run. One of them, Drill, is blank in every column except its name, so every formula meets blank inputs on every run.
- Postgres first, against values worked out by hand. Each formula under test becomes a Live formula field. The suite reads the rows back through the API, which means Postgres computed every value, and compares each cell with an expected value derived by hand from the seed data, never by running the engine.
- Then the same rows through JavaScript. The suite hands the same row payloads to the evaluator, in process. For every formula not marked SQL-only, the JavaScript value must equal the value Postgres returned: numbers within a small tolerance, text and booleans exactly. One mismatch fails the check and prints the formula, the row and both values.
- SQL-only formulas must be refused. Formulas marked SQL-only get the opposite assertion: the evaluator must return no value. A wrong value fails; only a refusal passes.
| Formula | Anvil | Bolt | Drill |
|---|---|---|---|
[Qty] * [Price] | 59.97 | 25 | Blank |
TEXT([Due], "DD/MM/YYYY") | 15/03/2026 | 01/01/2026 | Blank |
AND([Phone] = "x", [Active]) | False | False | Blank |
CONCATENATE([Status], "/", [Active], "/", [Due]) | Open/true/2026-03-15 | Done/false/2026-01-01 | // |
COUNT([Notes], [Billable]) (SQL only) | 2 | 1 | 2 |
In the run behind this post, Items carried 89 Live formula fields and Categories 4. All 445 Items cells (89 formulas on five rows) matched their hand-derived values. 71 of the 89 formulas are row-scoped and went through the parity sweep, and JavaScript and SQL agreed on all 355 of their cells. The other 18 are SQL-only: hops, aggregates, lookups, value lists, related-record lists, a number mask and the quarter mask. Every one of them that returns a single value was refused by the evaluator. The same run also sends 14 formulas the checker must reject, such as comparing a multi-select column with text or an IF() whose branches return a number and text, and confirms each comes back with a diagnostic.
The suite declares which code it covers: the expressions package, the SQL lowering, the Live formula field read path and the computed-field engine. Our test runner compares a branch with main and selects every suite whose declared paths match the changed files, so any change to either engine runs the sweep, and we run the full suite before every deploy. Adding a formula to the lab is one line: the source, a type, and the expected value for each of the five items.
Fail closed: what happens to a formula the checker rejects
A formula the checker refuses never runs, and it is refused in more than one place, because a formula that was fine yesterday can stop fitting the data today when someone renames a column or changes its type.
- While you type. The builder runs the same parser and checker in the browser on every edit and lists the problems with their position, in plain words. An
IF()that returns a number in one branch and text in the other gets: "Both IF() results must be the same type (got number and text)". Autocomplete reads the same environment, so the names it offers are the ones the checker resolves against. - At publish. Publishing checks every formula again in its own context and adds checks an editor cannot make on its own: a Live formula field's declared type must equal the type its formula returns, and formula fields that reference each other must not form a loop. Any failure blocks the publish.
- At read time. Every engine entry point parses and checks again before it runs anything, so drift between the published app and the data is caught where it happens.
| Surface | Result |
|---|---|
| Row filter or role filter | The read fails with an error. A filter never falls back to unfiltered rows. |
Visible if in the browser | Unknown, any other non-true result and any error all count as false, so the button or field stays hidden. |
| Live formula field | That one field is skipped: the row still loads and its cell is blank. |
| Stored computed field | The field keeps its current value instead of being overwritten with a guess. |
| Formula in a text block on a record page | The block shows an inline problem; the page keeps working. |
The posture is not the same everywhere, and that is deliberate. Where a wrong answer could expose data or offer an action it should not, the formula fails closed: no rows, no button. Where a wrong answer is only a missing value, it fails soft, so one broken column does not take a whole table down with it.
What we would tell someone building the same thing
- Pick one engine as the definition. Ours is SQL. The evaluator's header lists each core operator and function with its SQL behavior, and that list is the spec the JavaScript side is held to.
- Check once and share the result. If both back ends resolve names on their own, they will eventually resolve them differently.
- Let the weaker engine refuse. An evaluator that returns no value for what it cannot do is easy to test. One that approximates is not.
- Test with a blank row. Most disagreements live in null handling, and a row that is blank everywhere finds them on every formula at once.
- Derive expected values by hand. Comparing an engine with its own output proves nothing. Comparing two engines with each other and with a hand-derived value catches a bug in either.
- Write the divergences down. The ones you accept belong in a list next to the code and in a test that pins them, so nobody rediscovers them in production.
For anyone building on Emberblocks, the practical upshot is that a formula means the same thing wherever you put it, within the limits listed above, and the editor tells you when it does not fit. The expressions guide covers the language itself: references, operators, the core functions and where each kind of formula runs, and the formula function reference lists every function with an example. Coming from AppSheet, the AppSheet formulas translation table maps its functions to these. Row filters written as formulas are the subject of row-level and field-level permissions, and if you connect your own database, the Postgres front-end guide covers the database role an app should connect with.
Questions people ask
- Why not compile every formula to SQL?
- Some formulas answer questions about one row the browser already has, such as whether a button shows or whether a typed value is valid. Sending each of those to the database would put a network round trip behind every keystroke and every row on screen.
- Why not evaluate every formula in JavaScript?
- Filters decide which rows leave the database, so they have to run there. Counts, sums and reference hops need rows the browser does not have, and fetching all of them to compute one value would be slow and would send data to places it should not go.
- Can a formula inject SQL?
- No. Column and table names in a formula resolve to fields in the app definition and are emitted as quoted identifiers that the introspected schema confirms exist. Text, numbers and the signed-in user's details are bound parameters.
- Do the two engines ever disagree?
- In a short, documented list: time zones other than UTC, text ordering under locale collations, trailing zeros on scaled numbers, the client clock versus the database clock, JSON spacing, and date masks with letters the JavaScript evaluator does not implement, such as Q for quarter. Outside that list, the parity sweep runs both engines over the same rows whenever either one changes.
Sources
Written by Apostolos Papadopoulos
Apostolos builds Emberblocks, a visual app builder for internal tools on your own data, from Thessaloniki, Greece. Spotted something wrong or out of date? Write to hello@emberblocks.com.