Skip to content

Derive: SQL Column List

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
// A derive that builds a SQL column list using the new comptime features:

// closures (map), list.join, struct field access, and string interpolation.

@derive_for(SqlSchema)
fn derive_sql_schema(info) -> str {
  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 "impl {info.name} \{ 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

enespt-br