Haxe Code Cookbook
Haxe programming cookbookAbstract typesArray access of a database manager

Array access of a database manager

Reading time: 2 minutes

When using SPOD database objects, or the record-macros library, instances of database models can be accessed using the manager's get function:

var user42 = User.manager.get(42);

By abstracting over the user's manager class, we can add array access functionality to easily grab a user by their primary key (id):

var user42 = userManager[42];

We can also use a shortcut for inserting a new user at a specific id if we so desire:

userManager[21] = new User("Douglas");

Or even abuse the array access by providing null to auto-assign a new id:

userManager[null] = new User("Zaphod");


import sys.db.Object;
import sys.db.Types;
import sys.db.Manager;

class User extends Object {
    public var id:SId;
    public var name:SString<255>;

    public function new(name:String) {
        this.name = name;

    override public function toString()
        return this.name + ' (${this.id})';

abstract UserManager(Manager<User>) from Manager<User> to Manager<User> {
    public function new()
        this = User.manager;

    inline function getUserById(id:Int)
        return this.get(id);

    inline function setUserById(id:Null<Int>, user:User):User {
        if(id != null) user.id = id;
        return user;


Description of how to use/test the code.

import sys.db.Sqlite;
import sys.db.TableCreate;
import sys.db.Manager;

class Main {
    static function main() {
        Manager.cnx = Sqlite.open('array-access.db');

        var users:UserManager = new UserManager();
        if(!TableCreate.exists(users)) {
            Sys.println('Creating user table...');

        var user:User = new User("Bob");
        Sys.println('Created new user: ${user}');

        var uid:Int = user.id;
        users[42] = new User("Douglas");
        Sys.println('Created another new user: ${users[42]}');

        var thirdUser = new User("Abed");
        users[null] = thirdUser;
        Sys.println('Created yet another new user: ${thirdUser}');



Creating user table...
Created new user: Bob (1)
Created another new user: Douglas (42)
Created yet another new user: Abed (43)

More on this topic:

Last modified:
Category:  Abstract types