ActiveRecord library
Part of Active Record
ActiveRecord is Flux's object-relational mapper. It ties classes to database tables: a
model is a class that extends ActiveRecord::Base, its table is named after the
lowercase plural of the class name, and every row of that table is loaded as an object
of the class and written back with ActiveRecord::Base#save.
The tables are described by migrations (ActiveRecord::Migration): files in the
schema's db/migrate/ folder that change the database through the schema statements
(create_table, add_column, add_index and so on). Pending migrations are run when
the server starts or through the flux db:* console commands (ActiveRecord.Tasks),
and the resulting schema is dumped into db/schema.lua. All SQL goes through a database
adapter (ActiveRecord::Adapters::Abstract) for SQLite, MySQL or PostgreSQL, picked by
the settings of the current environment in config/database.yml.
The functions on the ActiveRecord table itself connect to the database, bring the
library up and keep its bookkeeping: the columns of every table are mirrored in
ActiveRecord.schema and in the 'ar_schema' table, and the indexes, foreign keys and
primary keys in ActiveRecord.metadata and in the 'ar_metadata' key-value table.
ActiveRecord.ready is set once the stored schema has been read back, and the
ActiveRecordReady hook is run when startup is complete. The library only exists on
the server; the client gets a stub of ActiveRecord::Base.
Summary
Functions
Functions
ActiveRecord.add_to_schema(table_name, column_name, type, definition, options)
shared packages/active_record/lib/active_record.lua:76Registers a column in the in-memory schema, inserting a row into the 'ar_schema' table if the column is new. Throws an error if ActiveRecord is not ready yet.
Parameters
- table_name String database table the column belongs to
- column_name String
- type String abstract column type, e.g. 'string', 'integer' or 'datetime'
- definition String optional, defaults to
nilSQL definition of the column, including its NOT NULL and DEFAULT clauses; the adapter's definition of the type if not given - options Map optional, defaults to
nilcolumn options: null (Boolean) and default
Splits the arguments of a column type method into the column name and its options.
Parameters
- name String/Map column name, or a table holding the name at index 1 and the options as keys
- ... Vararg options table, when the name is given as a string
Returns
- String column name
- Map options
Runs a schema statement. Normally the statement is handed to the function of the same name in ActiveRecord.SchemaStatements, timed and printed if a migration is running. While a migration is being reverted through its #change, the statement is recorded instead, so that its inverse can be run later.
Parameters
- command String name of the statement, e.g. 'create_table'
- ... Vararg arguments of the statement
Returns
- Any whatever the statement returns
Defines the database table of a model. Meant to be used in migrations. The 'id' primary key and the 'created_at' / 'updated_at' columns are added automatically. The table is created right away, or queued until the schema is restored if ActiveRecord is not ready yet. Reverted with drop_table.
ActiveRecord.define_model('users', function(t)
t:string { 'steam_id', null = false }
t:string { 'name', null = false }
t:integer 'playtime'
end)
Parameters
- name String table name, the lowercase plural of the model's class name
- callback Function receives the table definition, which has a method for every column type: primary_key, string, text, integer, float, decimal, datetime, timestamp, time, date, binary, boolean and json, as well as timestamps and references
Clientside stand-in for model definition. Only declares a class that extends ActiveRecord::Base, no database table is involved.
Parameters
- name String class name of the model
Deletes a key from the 'ar_metadata' key-value table.
Parameters
- key String
Forgets a table of the in-memory schema and deletes its rows from 'ar_schema'.
Parameters
- table_name String
Drops the internal 'ar_schema', 'ar_metadata' and 'ar_schema_migrations' tables and, unless told otherwise, every table known to the schema. This destroys the stored data.
Parameters
- meta_only Boolean optional, defaults to
falseonly drop the internal tables
Generates the Lua source of the schema file ('db/schema.lua') from the schema and its metadata (indexes, foreign keys and primary keys), in the shape of the schema statements that create it. The internal 'ar_*' tables are left out.
Parameters
- version Number/String schema version to write into the file
Returns
- String Lua source code
Loads the database adapter named in the config and connects it to the database. Uses 'sqlite' if no adapter is named, and resolves the aliases 'postgresql', 'sqlite3' and 'mysql' (the config's adapter field is rewritten in that case). The resolved name is stored in ActiveRecord.adapter_name.
ActiveRecord.establish_connection {
adapter = 'mysqloo', host = '127.0.0.1', port = 3306,
user = 'username', password = 'password', database = 'flux_dev'
}
Parameters
- config Map database settings as found in config/database.yml: adapter, host, port, user, password, database, encoding, socket and flags
Removes an index, foreign key or primary key from the metadata.
Parameters
- kind String 'index', 'foreign_key' or 'primary_key'
- name String
Formats a schema statement and its arguments for the migration output, e.g. 'add_column("users", "role", "string")'.
Parameters
- command String
- ... Vararg arguments of the statement; functions are left out
Returns
- String
ActiveRecord.generate_create_func(obj, type, def)
shared packages/active_record/lib/generators/generator.lua:41Adds a column type method to a query, which lets columns be defined DSL-style. The generated method takes the column name followed by its options, or a single table holding both.
ActiveRecord.generate_create_func(query, 'string', 'varchar(255)')
query:string 'name'
query:string('steam_id', { null = false })
query:string { 'steam_id', null = false }
Parameters
- obj ActiveRecord::Query query to add the method to
- type String abstract column type, used as the name of the method
- def String adapter-specific SQL type definition
ActiveRecord.generate_create_funcs(obj)
shared packages/active_record/lib/generators/generator.lua:65Adds a column type method for every type supported by the current adapter.
Parameters
- obj ActiveRecord::Query query to add the methods to
See also
ActiveRecord.generate_table_name(class_name)
shared packages/active_record/lib/generators/generator.lua:178Returns the name of the database table for a model class name, which is its underscored plural ('TempPermission' becomes 'temp_permissions').
Parameters
- class_name String
Returns
- String
Creates the internal tables if they do not exist yet: 'ar_schema' (the columns of every table), 'ar_metadata' (key-value storage, which also holds the indexes and foreign keys) and 'ar_schema_migrations' (the migrations that have been run).
Reads a value from the 'ar_metadata' key-value table. Make sure to run this while the adapter is in "sync mode", since asynchronous queries return nothing.
Parameters
- key String
- default Any optional, defaults to
nilvalue to return if the key is not stored
Returns
- String/Any stored value, or default if the key is missing
Internal
This function is internal. It is not part of the public API and may change without notice.
Bootstraps ActiveRecord once the adapter is connected: creates the internal tables, restores the schema, brings the database up to date (see ActiveRecord.Tasks.prepare) and fires the 'ActiveRecordReady' hook.
Drops all tables, recreates the internal ones and then restarts the current map. This destroys all data stored in the database.
ActiveRecord.remove_from_schema(table_name, column_name)
shared packages/active_record/lib/active_record.lua:116Forgets a column of the in-memory schema and deletes its row from 'ar_schema'.
Parameters
- table_name String
- column_name String
ActiveRecord.rename_in_schema(table_name, column_name, new_name)
shared packages/active_record/lib/active_record.lua:135Renames a column in the in-memory schema and in 'ar_schema'.
Parameters
- table_name String
- column_name String
- new_name String
ActiveRecord.rename_table_in_schema(table_name, new_name)
shared packages/active_record/lib/active_record.lua:167Renames a table in the in-memory schema and in 'ar_schema'.
Parameters
- table_name String
- new_name String
Internal
This function is internal. It is not part of the public API and may change without notice.
Loads the metadata (indexes, foreign keys and primary keys) from the 'ar_metadata' table into ActiveRecord.metadata.
Internal
This function is internal. It is not part of the public API and may change without notice.
Loads the stored schema from the 'ar_schema' table. Once loaded, marks ActiveRecord as ready, populates the models and creates the tables queued by #define_model.
Writes a value to the 'ar_metadata' key-value table, updating the row if the key already exists.
Parameters
- key String
- value Any value to store, converted to a string
ActiveRecord.store_metadata(kind, name, entry)
shared packages/active_record/lib/active_record.lua:190Records an index, foreign key or primary key in the metadata, both in memory and in the 'ar_metadata' table (under the key '<kind>:<name>').
Parameters
- kind String 'index', 'foreign_key' or 'primary_key'
- name String name of the index or constraint
- entry Map its description, as written by the schema statements
Converts a raw database value to the Lua type matching an abstract column type.
Parameters
- str Any value as returned by the database, usually a string
- type String abstract column type
Returns
- Number/Boolean/Any number for 'integer', 'float', 'decimal' and 'primary_key' columns, boolean for 'boolean' columns, the unchanged value for anything else
Converts a Lua value to the form in which it is written to the database.
Parameters
- val Any
- type String abstract column type
Returns
- Number/String 0 or 1 for 'boolean' columns, otherwise the value converted to a string; nil if the value is nil