hara.runtime
Runtime adapters for generated code.
hara.runtime executes generated code in local processes, browsers, databases, editors, OpenResty, Redis, Solidity, Python, and other runtime hosts.
1 Motivation
Emission alone is not enough for tests and systems work. Runtime adapters let hara.lang run target code, verify behavior, and connect generated functions to real services.
2 Internal usage
The CI workflow pulls runtime images for Hara tests and installs runtime dependencies for language-specific test groups. Walkthrough live examples use runtime contexts to execute emitted JS and Lua.
3 API
4 rt.postgres: A Comprehensive Overview of the PostgreSQL Transpilation and Interaction Layer
The rt.postgres module within the foundation-base ecosystem provides a robust and comprehensive layer for defining, transpiling, and interacting with PostgreSQL databases using Clojure. It extends the core std.lang framework to offer a domain-specific language (DSL) for PostgreSQL, enabling developers to define schema, write queries, and manage database operations directly from Clojure code, which is then transpiled to SQL.
4.1 Core Architecture and Components
rt.postgres is structured into several key namespaces, each handling a specific aspect of PostgreSQL integration:
rt.postgres.client: Manages the connection and lifecycle of PostgreSQL runtimes.nrt.postgres.client-impl: Implements the core interaction logic for executing raw SQL and invoking transpiled functions.nrt.postgres.grammar: Defines the custom grammar and syntax for transpiling Clojure forms into PostgreSQL SQL.nrt.postgres.grammar.*(common,meta,tf,form-*): These sub-namespaces provide foundational utilities for grammar definition, metadata extraction, type transformations, and custom form handling (e.g.,defn,deftype,defenum).nrt.postgres.script.*(addon,builtin,graph,impl,supabase): These namespaces expose high-level macros and functions (the DSL) for common database operations, graph-like queries, and integration with Supabase.nrt.postgres.system: Provides macros for interacting with PostgreSQL system functions.nrt.postgres.gen_bind: Facilitates the binding of Clojure-defined functions and database entities into a structured interface for external consumption (e.g., APIs).
4.2 Integration with hara.lang
rt.postgres extensively leverages the hara.lang framework's capabilities for code generation and runtime management.
std.lang.base.bookandstd.lang.base.library:rt.postgresdefines its own+book+(inrt.postgres.grammar.clj) which holds the PostgreSQL-specific grammar and metadata. This book is installed into the globalstd.langlibrary, making the PostgreSQL language available for transpilation.nhara.lang.base.emit: The emit pipeline uses thert.postgresgrammar (+grammar+) to translate Clojure forms into SQL strings.nhara.lang.base.grammar: The+grammar+inrt.postgres.grammar.cljis built uponhara.lang.base.grammar/build, incorporating various operators and customizing them for PostgreSQL's syntax and semantics.nhara.lang.base.runtime: Thert.postgres.client/RuntimePostgresimplements theIContextandIComponentprotocols, allowinghara.langto manage PostgreSQL connections and execute code within that context.nhara.lang.base.script: The high-levell/script :postgresmacro enables the seamless execution model, making PostgreSQL functions and macros available directly within Clojure namespaces.
4.3 Grammar and Schema Definition (rt.postgres.grammar.)
The heart of rt.postgres lies in its grammar definition, which dictates how Clojure code is transformed into PostgreSQL.
+features+(inrt.postgres.grammar.clj): This defines the operators and keywords available in the PostgreSQL DSL. It extends standardhara.langfeatures with PostgreSQL-specific constructs. Notable extensions include:n SQL Operators: Custom definitions for operators likeseteq(:=), andconcat(||).n JSONB Operators: Operators for JSONB manipulation likeidxe(#>>),idxt(->>),idxj(->).n Type Casting: Thecast(++) operator for explicit type casting.n Control Flow: Custom implementations fortry,if,let,loop,case,for,foreachadapted to PL/pgSQL.n Macro-based Top-Level Definitions:ndefenum.pg: Defines PostgreSQLENUMtypes.ndeftype.pg: Defines PostgreSQL tables, including columns, primary keys, foreign keys (:ref), unique constraints, and indexes. It also supports tracking for auditing purposes.ndefconst.pg: Defines constants, often used for configuration, that are persisted in a database table.ndefindex.pg: Creates database indexes.ndefpolicy.pg: Defines row-level security (RLS) policies.ndeftrigger.pg: Creates database triggers.n+template+(inrt.postgres.grammar.clj): Specifies the formatting and stylistic rules for the generated SQL, including comments, spacing, function invocation (reversed truefor PostgreSQL functions), and how data structures like maps, sets, and vectors are emitted (pg-map,pg-set,pg-vector).ntf.clj: Containspg-tf-js, a critical function for transforming Clojure maps, vectors, and sets into PostgreSQLjsonb_build_objectandjsonb_build_arraycalls, enabling dynamic JSON construction in SQL.nmeta.clj: Provides essential functions (has-function,has-table,create-schema,drop-extension, etc.) for managing PostgreSQL objects programmatically, forming the basis forsetup-moduleandteardown-modulelifecycle hooks.ncommon.clj: Serves as a central utility hub forrt.postgres.grammar, providing shared functions for type aliasing (+pg-type-alias+), symbol metadata handling (pg-sym-meta), and common SQL string/block constructions. It explicitly handles formatting for various forms includingdefenum,defindex,defpolicy,deftrigger, and genericdefblock.ncommon-application.clj: Defines theApplicationrecord and functions for managing application-specific schemas (app-create,app-rebuild), allowingrt.postgresto understand and track database schemas as Clojure data structures.n*common-tracker.clj: Implements a genericTrackermechanism for auditing and modifying data operations (e.g.,create,modify), often used indeftypedefinitions to automatically track changes.
4.4 Client and Runtime (rt.postgres.client, rt.postgres.client-impl)
The client components define how foundation-base connects to and interacts with a PostgreSQL database.
RuntimePostgres(inrt.postgres.client.clj): Thisdefimplrecord implementsstd.protocol.component/IComponent(for lifecycle management like starting/stopping the connection) andstd.protocol.context/IContext(for executing code).nrt-postgres:create,rt-postgres: Functions for creating and starting a PostgreSQL runtime instance, typically wrapping alib.postgresconnection.n Notification System: Supports adding and removing notification channels for real-time events.nraw-eval-pg(inrt.postgres.client-impl.clj): Executes raw SQL strings against the PostgreSQL connection. It includes logic for parsing JSON results from PostgreSQL functions.ninit-ptr-pg: Initializes pointers (database objects defined in Clojure) by executing their creation forms in the database.n*invoke-ptr-pg: The central function for invoking transpiled Clojure code (functions, blocks) in PostgreSQL. It handles single calls, and specifically transformsletandtryblocks into PL/pgSQLDOblocks for execution.
4.5 Scripting and Operations (rt.postgres.script.)
These namespaces provide the high-level DSL (macros with defmacro.pg) that simplifies common PostgreSQL operations.
addon.clj:n Utilities:id,name,full,coordfor working with entity identifiers and references.n Security:rand-hex,sha1for cryptographic utilities.n Time:time-ms,time-usfor timestamp generation.n Error Handling:throw,error,assertmacros for raising/handling exceptions directly within PL/pgSQL.n Flow Control: Customcasemacro.n Map/Reduce:map:rel,map:js-text,map:js-array,do:reducefor functional-style operations on relations and JSON arrays.n SQL Shorthands:b:select,b:update,b:insert,b:delete,performfor generating basic SQL DML statements.n Randomness:random-enum.nbuiltin.clj: Defines a vast array of PostgreSQL built-in functions (e.g., array functions, string functions, aggregate functions, math functions, JSONB functions, security functions) as Clojure macros (e.g.,l/script :postgres {:macro-only true}), allowing direct invocation within the PostgreSQL DSL.nimpl.clj: Provides "flat" macros (t:select,t:get,t:id,t:count,t:exists,t:delete,t:insert,t:upsert,t:update,t:modify,t:fields) for direct table interactions. These macros simplify common CRUD (Create, Read, Update, Delete) and query operations, abstracting away the underlying SQL generation.nimpl-base.clj: Contains helper functions forimpl, such asprep-entry,prep-table(for resolving schema metadata), input validation (t-input-check), and transforming Clojure values to SQL equivalents (t-val-fn). It also includes functions for constructingWHEREandRETURNINGclauses.nimpl-insert.clj: Implements the core logic fort:insertandt:upsert. It includesinsert-formfor constructing SQLINSERTstatements and integrates with thecommon-trackerfor auditing.nimpl-main.clj: Implements the core logic fort:select,t:id,t:count,t:exists, andt:delete. It details howWHERE,ORDER BY,LIMIT,OFFSET, andRETURNINGclauses are constructed.nimpl-update.clj: Implements the core logic fort:updateandt:modify, handling how Clojure maps and symbols are translated into SQLSETclauses.
4.6 Graph Operations (rt.postgres.script.graph.)
These namespaces provide specialized tools for working with data in a graph-like manner, particularly useful for managing interconnected entity relationships.
graph.clj: Offers high-level graph macros (g:where,g:id,g:count,g:exists,g:select,g:get,g:update,g:modify,g:insert,q,q:get,view). These macros build upon theimplfunctions to provide a more declarative way of performing operations, especially when dealing with nested or related data.ngraph-base.clj: Implements the coreWHEREclause construction logic for graph queries, specifically handling how:reftypes and nested conditions are translated into SQL.ngraph-insert.clj: Extendsimpl-insertto handle complex, nested data inserts by:ninsert-walk-ids: Assigning unique IDs to nodes in the input data.ninsert-generate-graph-tree: Building a dependency graph of nodes.ninsert-associate-graph-data: Associating graph metadata with data.ninsert-gen-sql: Generating a sequence of SQLINSERTstatements based on the graph's topological sort, ensuring dependencies are inserted first. This enables the insertion of deeply nested and interlinked data structures.ngraph-query.clj: Provides the foundation for complexSELECTqueries with nested data and linked entities. It defines how:returningclauses (e.g.,:*/default,:*/info,:*/linked) are expanded to retrieve associated data.ngraph-view.clj: Enables the creation of reusable "views" (defsel.pg,defret.pg) for common select and return patterns, abstracting complex queries into simple function calls.n*graph-walk.clj: Utilizesstd.lib.transformto traverse and manipulate complex data structures, primarily forlink-data(resolving references and seeding IDs) andflatten-data(converting a nested structure into flattened tables for insertion).
4.7 Supabase Integration (rt.postgres.supabase)
This module provides specialized macros and functions for interacting with Supabase features.
- Role Management:
create-role,alter-role-bypassrls,grant-public,revoke-execute-privileges-from-public,grant-usage,grant-tables,grant-privileges,grant-allfor fine-grained control over PostgreSQL roles and permissions, tailored for Supabase's authentication model.n Authentication Context:auth-uid,auth-email,auth-role,auth-jwtto access Supabase authentication context within PostgreSQL functions.is-supabasechecks for Supabase installation.n Error Handling:raisefor custom error messages with HTTP status and headers.n Context Switching:with-role,with-auth,with-supermacros simulate different user roles or authenticated states to test RLS and other security features.n API Calls: Functions likeapi-rpc,api-select-all,api-signup,api-signin,api-signup-create,api-signup-delete,api-impersonateprovide direct integration with the Supabase REST and Auth APIs from Clojure.n* Entry Transformations:transform-entry-defnandtransform-entry-deftypeautomatically add Supabase-specific grant statements and row-level security (RLS) configurations to transpiled functions and tables based on metadata (e.g.,:sb/grant,:sb/rls).
4.8 System Functions (rt.postgres.system)
This namespace (rt.postgres.system.clj) provides a collection of macros (pg-tmpl) for accessing and invoking a wide range of PostgreSQL system functions (e.g., advisory-lock, backend-pid, current-wal-lsn, timezone-names), allowing detailed database introspection and control.
4.9 Summary of Key Functions/Macros
- Schema Definition:
defenum.pg,deftype.pg,defconst.pg,defindex.pg,defpolicy.pg,deftrigger.pgn Grammar Transformation:pg-tf-js,pg-typecastn Client Operations:rt-postgres,raw-eval-pg,invoke-ptr-pgn Basic CRUD/Query:t:select,t:insert,t:upsert,t:update,t:delete,t:get,t:id,t:count,t:existsn Graph Operations:g:select,g:insert,g:update,g:get,q,view,link-data,flatten-datan Supabase Integration:with-role,with-auth,raise,api-rpc,transform-entryn PL/pgSQL Constructs:throw,error,assert,case,do:plpgsql,do:reducen* System Functions:advisory-lock,backend-pid, etc. (exposed viart.postgres.system)
rt.postgres provides a powerful and idiomatic way for Clojure developers to define and interact with PostgreSQL databases, integrating seamlessly with the foundation-base code generation and runtime management capabilities.