Skip to content

16 · Reflection & Metaprogramming

Derive: SQL Column List

A derive that uses closures and list.join to build a SQL column list from typeinfo fields.

On this page

This derive uses comptime closures (map) and list.join to map each field's name and nullability into a SQL column string, then concatenates them — a concise demonstration of how modern comptime features (closures, string interpolation, collection methods) combine inside a @derive_for function.

Use @derive_for(SqlSchema) with a closure-based map and join to generate a sql_columns() method that returns "id NOT NULL, owner NOT NULL, note NULL" for an Account struct.

13-derive-sql-schema.zolo
Playground
// SQL remains ordinary text; only the generated Zolo program is structured.

@derive_for(SqlSchema)
fn derive_sql_schema(info) -> Syntax<.Items> {
  let cols = info.fields.map(|f| {
    let nn = if f.type.is_optional { "NULL" } else { "NOT NULL" }
    "{f.name} {nn}"
  })
  let body = cols.join(", ")
  return quote items {
    impl ${info.ref} {
      fn sql_columns() -> str { return ${body} }
    }
  }
}

@derive(SqlSchema)
struct Account {
  id: int,
  owner: str,
  note: str?,
}

let a = Account.new(id: 1, owner: "x", note: nil)
print(a.sql_columns())
// expected: id NOT NULL, owner NOT NULL, note NULL

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

en