Skip to content

Model

:class:Model connects to a PostgreSQL database and acts as a factory for :class:~half_orm.relation.Relation subclasses. One Model instance per database is enough — it is shared across all relation classes.

from half_orm.model import Model

blog = Model('blog')
Author = blog.get_relation_class('blog.author')

See Learn halfORM in half an hour for a full walkthrough.


Connecting

Model

Connection to a PostgreSQL database.

Parameters:

Name Type Description Default
config_file str

name of the connection file searched in HALFORM_CONF_DIR (env var, defaults to /etc/half_orm). File format: [database] name = # mandatory user = password = host = port =

name is the only mandatory key when using peer authentication.

required
scope str | None

package name used to resolve registered subclasses.

None

Raises:

Type Description
MissingConfigFile

if the configuration file is not found.

MalformedConfigFile

if name is missing from the file.

OperationalError

if the database connection fails.

get_relation_class(relation_name, fields_aliases=None)

Generate a :class:~half_orm.relation.Relation subclass for a table or view.

Parameters:

Name Type Description Default
relation_name str

fully qualified name 'schema.relation'.

required
fields_aliases dict | None

optional mapping of field aliases.

None

Returns:

Name Type Description
type

a class inheriting :class:~half_orm.relation.Relation.

Raises:

Type Description
MissingSchemaInName

if the schema part is missing from relation_name.

UnknownRelation

if the relation does not exist in the database.

Example

Generate a Relation class:

Author = blog.get_relation_class('blog.author')

# Preferred: subclass and register
@register
class Author(blog.get_relation_class('blog.author')):
    Fkeys = {'post_rfk': '_reverse_fkey_blog_post_author_id'}

ping()

Check if the connection is alive, reconnecting if needed.

Returns:

Name Type Description
bool

True if the connection is established.

disconnect()

Closes the current thread's connection to the database.


Async connection

aconnect() async

Setup an async connection to the database.

Must be called explicitly before using any ho_a* method. The sync connection (used for metadata, ho_select, etc.) remains available.

New in version 0.18.0.

adisconnect() async

Closes the async connection to the database.

New in version 0.18.0.


Executing raw SQL

These methods execute SQL directly. Prefer the :class:~half_orm.relation.Relation methods for standard CRUD operations.

execute_query(query, values=None, mogrify=False)

Execute a raw SQL query. Executes SQL.

Parameters:

Name Type Description Default
query str

SQL query with %s placeholders.

required
values tuple | None

query parameters.

None
mogrify bool

if True, print the interpolated query before executing. Default: False.

False

Returns:

Name Type Description
cursor

psycopg cursor positioned on the result set.

Warning

Always use %s placeholders — never interpolate user input directly into the query string.

execute_function(fct_name, *args, **kwargs)

Call a PostgreSQL function and return its result set. Executes SQL.

Parameters:

Name Type Description Default
fct_name str

fully qualified function name ('schema.function').

required
*args

positional parameters.

()
**kwargs

named parameters (name => value syntax).

{}

Returns:

Type Description
List[tuple]

list[dict]: rows returned by the function.

Raises:

Type Description
RuntimeError

if both *args and **kwargs are provided.

call_procedure(proc_name, *args, **kwargs)

Call a PostgreSQL procedure. Executes SQL.

Parameters:

Name Type Description Default
proc_name str

fully qualified procedure name.

required
*args

positional parameters.

()
**kwargs

named parameters.

{}

Returns:

Type Description

list[dict] | None: rows if the procedure returns a result set,

otherwise None.

Raises:

Type Description
RuntimeError

if both *args and **kwargs are provided.


Inspection

has_relation(qtn)

Return True if the relation exists in the database.

Parameters:

Name Type Description Default
qtn str

qualified table name, e.g. 'public.person'.

required

Returns:

Type Description
bool

bool

sql_trace property writable

bool: if True, every SQL query is printed to stdout before execution.


Decorator

register_class(relation_class)

Register a :class:~half_orm.relation.Relation subclass with its Model.

After registration, FK navigation and factory calls return instances of the custom subclass instead of the generated base class, making Fkeys aliases and custom methods available throughout.

Parameters:

Name Type Description Default
relation_class

a class that subclasses the result of :meth:~half_orm.model.Model.get_relation_class.

required

Returns:

Type Description

relation_class — the decorated class, unchanged.

Raises:

Type Description
ValueError

if relation_class is not a valid relation subclass.

Example

Register a class:

from half_orm.model import Model, register

blog = Model('blog')

@register
class Author(blog.get_relation_class('blog.author')):
    Fkeys = {'post_rfk': '_reverse_fkey_blog_post_author_id'}