Skip to main content
Version: 🚧 Alpha 🚧

Using Database Access

GAMA provides SQL actions through the gama.extension.database extension. A species can use the sql skill for actions that open a connection for each operation, or inherit from AgentDB to reuse an explicitly opened connection across operations. Use AgentDB when the model needs to manage a persistent connection; call connect before querying and close when finished.

Both approaches support SQL queries for reading and modifying relational databases. Query results can be used to create agents or to initialize model data, and simulation results can be written back to a database.

Description​

  • Extension: gama.extension.database
  • Author: TRUONG Minh Thai, Frederic AMBLARD, Benoit GAUDOU, Christophe SIBERTIN-BLANC

Supported DBMS​

The following DBMS are currently supported:

  • SQLite
  • MySQL
  • PostgreSQL, including PostGIS for spatial data.

SQLite uses a database file. MySQL and PostgreSQL connections use a database server.

The GAMA action interface is the same across these DBMS, but connection parameters and SQL syntax can differ. Spatial queries can also use database-specific functions.

The main SQL actions are:

  • select: executes a SELECT query and returns its result as a dataframe.
  • insert: inserts one or more rows and returns the number of inserted rows.
  • executeUpdate: executes a SQL statement that does not return a result set, such as CREATE, INSERT, UPDATE, DELETE or DROP.

The sql skill​

Define a species that uses the sql skill​

Example of declaration:

species toto skills: [sql] {
//insert your descriptions here
}

Agents with such a skill can use new actions defined in the skill. All these actions need information for the database connection.

Map of connection parameters for SQL​

The sql skill actions require a map containing the connection parameters. It uses the following keys:

  • dbtype (mandatory): database type. Supported values are mysql, postgres, postgis and sqlite; the connector converts this value to lowercase.
  • host (optional): Host name or IP address of data server. It is absent when we work with SQlite.
  • port (optional): Port of connection. It is not required when we work with SQLite.
  • database (required key): database name, or the SQLite database-file path. Use an empty value when connecting to a PostgreSQL or MySQL server without selecting a database.
  • user (optional): Username. It is not required when we work with SQLite.
  • passwd (optional): Password. It is not required when we work with SQLite.
  • crs or srid (optional): coordinate reference system used when writing spatial data. crs accepts a CRS code; srid accepts an EPSG code. crs takes precedence when both are present. If neither is present, GAMA uses the output CRS configured in Preferences under Data and Operators > GIS Coordinate Reference Systems.

Example: Definitions of connection parameters

// POSTGRES connection parameter
map <string, string> POSTGRES <- [
'host'::'localhost',
'dbtype'::'postgres',
'database'::'BPH',
'port'::'5432',
'user'::'postgres',
'passwd'::'abc'];

//SQLite
map <string, string> SQLITE <- [
'dbtype'::'sqlite',
'database'::'../includes/meteo.db'];

// MySQL connection parameter
map <string, string> MySQL <- [
'host'::'localhost',
'dbtype'::'MySQL',
'database'::'', // it may be empty to connect to a server without selecting a database
'port'::'3306',
'user'::'root',
'passwd'::'abc'];

The SQLite query examples below use the supplied meteo.db file. Its ../includes/meteo.db path matches the bundled example models; change it to the relative path from your own model to the database file. Examples that create or modify the registration table use a separate registration.db file; point this to a writable database file that you can discard after experimenting. Create the table with the CREATE TABLE example in the executeUpdate section before running the insert examples.

Action testConnection: test a connection to a database​

Syntax:

testConnection (params: map <string, string>) The action tests the connection to a given database.

  • Return: boolean. It is:
    • true: the agent can connect to the DBMS (to the given Database with the given name and password).
    • false: the agent cannot connect (either the server is not started, the database does not exist or the user/password are not correct).
  • Arguments:
    • params (type = map <string, string>): map of connection parameters
  • Exceptions: none are propagated by this action; a connection failure returns false.

Example: Check a connection to a MySQL database.

// Needs to be executed in the context of an agent with the sql skill.
// MySQL is the connection parameters map defined above.
if (testConnection(MySQL)){
write "Connection is OK" ;
}else{
write "Connection is false" ;
}

Action select: select data from a database​

Syntax:

select (params: map<string,string>, select: string, values: list (optional)) The action opens a database connection, executes the query and closes the connection. If the connection or query fails, it throws a GamaRuntimeException.

  • Return: a dataframe containing the query result.
  • Arguments:
    • params (type = map<string,string>): map containing the connection parameters
    • select (type = string): A SQL query returning values, i.e. a SELECT query. The selection query can be a parametric query (i.e. it can contain question marks).
    • values (type = list, optional): Values used to replace question marks in a parameterized query. Omit it, or pass nil or an empty list, when the query has no placeholders.
  • Exceptions: GamaRuntimeException

Example: select data from table points.

map <string, string> PARAMS <- ['dbtype'::'sqlite', 'database'::'../includes/meteo.db'];
dataframe t <- select(PARAMS, "SELECT * FROM points;");

Example: Select data from the points table with a parameterized query.

map <string, string> PARAMS <- ['dbtype'::'sqlite', 'database'::'../includes/meteo.db'];
dataframe t <- select(params: PARAMS,
select: "SELECT temp_min FROM points where (day>? and day<?);",
values: [10,20] );

Action insert: Insert data into a database​

Syntax:

insert (params: map<string,string>, into: string, data: any) The action creates a connection to a DBMS and executes the insert statement. If the connection or insertion fails then it throws a GamaRuntimeException.

  • Return: int

If the insertion succeeds, it returns the number of records inserted.

  • Arguments:
    • params (type = map<string,string>): map containing the connection parameters.
    • into (type = string): the table name.
    • data (any type): the data to insert. A dataframe inserts all its rows in a single batch (columns = dataframe column names). A map inserts a single row (keys = columns, values = values). A list inserts a single row, one value per column in the table's declaration order.
  • Exceptions: GamaRuntimeException

Example: Insert data into table registration.

map<string, string> PARAMS <- ['dbtype'::'sqlite', 'database'::'registration.db'];

// several rows at once, using a dataframe
do insert (params: PARAMS,
into: "registration",
data: dataframe_with(["id","first","last","age"], [[102,'Mahnaz','Fatma',25],[103,'Zaid','Kha',30]]));

// a single row, as a map of column:value pairs
do insert (params: PARAMS,
into: "registration",
data: ["id"::105, "first"::"Zara", "last"::"Ali"]);

// a single row, as a list of values in the table's column order
int n <- insert (params: PARAMS,
into: "registration",
data: [104, 'Bill', 'Clark', 40]);

Action executeUpdate: Execution update commands​

Syntax:

executeUpdate (params: map<string,string>, updateComm: string, values: list (optional)) With the sql skill, the action opens a connection, runs the update statement and closes the connection. It throws a GamaRuntimeException if the connection or statement fails.

  • Return: int. It returns the update count reported by the database driver; statements that do not change rows, such as table creation, may return zero.
  • Arguments:
    • params (type = map<string,string>): map containing the connection parameters,
    • updateComm (type = string): SQL statement that does not return a result set, such as create, insert, update, delete or drop. It may contain question-mark placeholders.
    • values (type=list, optional): Values used to replace question marks in a parameterized query. Omit it, or pass nil or an empty list, when the statement has no placeholders.
  • Exceptions: GamaRuntimeException

Examples: Using action executeUpdate to execute some SQL commands (create, insert, update, delete and drop).

map<string, string> PARAMS <- ['dbtype'::'sqlite', 'database'::'registration.db'];
// Create table
do executeUpdate (params: PARAMS,
updateComm: "CREATE TABLE registration"
+ "(id INTEGER PRIMARY KEY, "
+ " first TEXT NOT NULL, " + " last TEXT NOT NULL, "
+ " age INTEGER);");

// Insert into
do executeUpdate (params: PARAMS,
updateComm: "INSERT INTO registration " + "VALUES(100, 'Zara', 'Ali', 18);");
do insert (params: PARAMS, into: "registration",
data: ["id"::103, "first"::"Zaid tim", "last"::"Kha"]);

// executeUpdate with question marks
do executeUpdate (params: PARAMS,
updateComm: "INSERT INTO registration " + "VALUES(?, ?, ?, ?);",
values: [101, 'Mr', 'Mme', 45]);

//update
int n <- executeUpdate (params: PARAMS,
updateComm: "UPDATE registration SET age = 30 WHERE id IN (100, 101)" );

// delete
int n <- executeUpdate (params: PARAMS,
updateComm: "DELETE FROM registration where id=? ",
values: [101] );

// Drop table
do executeUpdate (params: PARAMS, updateComm: "DROP TABLE registration");

AgentDB​

AgentDB is an abstract species that provides database actions. Call connect explicitly to open a connection; later actions reuse it until close is called or connection parameters are changed. Calling connect while a connection is already open raises an error. The query and update actions also raise an error if called before a connection is established.

Define a species that is an inheritance of AgentDB​

Example of declaration:

species agtDB parent: AgentDB {
//insert your descriptions here
}

Action connect: Connect to a database​

Syntax:

connect (params: map<string,string>) This action opens a database connection. It throws a GamaRuntimeException if the connection cannot be established.

  • Return: null on success
  • Arguments:
    • params (type = map<string,string>): map containing the connection parameters
  • Exceptions: GamaRuntimeException

Example: Connect to PostgreSQL

// POSTGRES connection parameter
map <string, string> POSTGRES <- [
'host'::'localhost',
'dbtype'::'postgres',
'database'::'BPH',
'port'::'5433',
'user'::'postgres',
'passwd'::'abc'];
ask agtDB {
do connect (params: POSTGRES);
}

Action isConnected: Check whether an agent is connected to a database​

Syntax:

isConnected This action checks if an agent is connected to a database.

  • Return: Boolean. Returns true if the agent is connected, otherwise false.

Example: Check whether the agents in agtDB are connected.

ask agtDB {
if (self.isConnected()){
write "It already has a connection";
}else{
do connect (params: POSTGRES);
}
}

Action close: Close the current connection​

Syntax:

close This action closes the current database connection of the current agent. If no connection exists, it throws a GamaRuntimeException.

Example: close the connection of all the agtDB agents.

ask agtDB {
if (self.isConnected()){
do close();
}
}

Action getParameter: Get connection parameters​

Syntax:

getParameter This action returns the connection parameters of the current agent.

  • Return: map<string,string>

Example:

ask agtDB {
if (self.isConnected()){
write "the connection parameter: " +self.getParameter();
}
}

Set connection parameters​

Syntax:

setParameter (params: map<string,string>) This action sets new values for connection parameters and closes the current connection of the agent, if one is open. If it cannot close the current connection, it throws a GamaRuntimeException. Call connect to open a connection with the new values.

  • Return: null
  • Arguments:
    • params (type = map<string,string>): map containing the connection parameters
  • Exceptions: GamaRuntimeException

Example:

ask agtDB {
if (self.isConnected()){
do setParameter params: MySQL;
do connect params: self.getParameter();
}
}

Retrieve data from a database by using AgentDB​

Because AgentDB's connection to the database is kept alive, it can execute several SQL queries after one call to connect. It provides the select, insert and executeUpdate actions; these use the same arguments as their sql skill counterparts, except that the params argument is omitted because the connection is already open.

Examples:

map<string, string> PARAMS <- ['dbtype'::'sqlite', 'database'::'registration.db'];
ask agtDB {
do connect params: PARAMS;

// Create table
do executeUpdate updateComm: "CREATE TABLE registration"
+ "(id INTEGER PRIMARY KEY, "
+ " first TEXT NOT NULL, " + " last TEXT NOT NULL, "
+ " age INTEGER);";

// Insert into
do executeUpdate updateComm: "INSERT INTO registration "
+ "VALUES(100, 'Zara', 'Ali', 18);";
do insert into: "registration"
data: ["id":103, "first":"Zaid tim", "last":"Kha"];

// executeUpdate with question marks
do executeUpdate updateComm: "INSERT INTO registration VALUES(?, ?, ?, ?);"
values: [101, 'Mr', 'Mme', 45];

//select
dataframe t <- self.select("SELECT * FROM registration;");

//update
int n <- self.executeUpdate(updateComm: "UPDATE registration SET age = 30 WHERE id IN (100, 101)");

// delete
int n <- executeUpdate ( updateComm: "DELETE FROM registration where id=? ", values: [101] );

// Drop table
do executeUpdate updateComm: "DROP TABLE registration";
}

Using database features to define the environment and create agents​

Database query results can initialize simulations: the select action returns a dataframe that can define the environment boundary or create agents, in the same way as data from a shape file. Simulation data, including geometries, can also be written to a database.

Spatial database operations support PostGIS and MySQL.

Define the boundary of the environment from the database​

  • Step 1: specify the SELECT query by declaring a map object with keys as below:

    • dbtype (mandatory): use postgis or mysql for spatial queries. The value is case-insensitive.
    • host (optional): Host name or IP address of data server.
    • port (optional): Port of connection.
    • database (mandatory): Name of database.
    • user (optional): Username.
    • passwd (optional): Password.
    • select (mandatory): selection query.

Example:

map<string,string> BOUNDS <- [
'host'::'localhost',
'dbtype'::'postgis',
'database'::'spatial_DB',
'port'::'5433',
'user'::'postgres',
'passwd'::'tmt',
'select'::'SELECT ST_AsEWKB(geom) as geom FROM bounds;' ];
  • Step 2: define the boundary of the environment by using the map object defined in the first step (in the global block of the model).
geometry shape <- envelope(BOUNDS);

For PostGIS, the packaged example selects geometry with ST_AsEWKB. The packaged MySQL example selects its geom column directly. The database extension converts geometry result columns to GAMA geometries, so whether a query needs a database-specific conversion depends on the database and column type.

Create agents from the result of a select action​

The query result is a dataframe. In the create ... from: statement, each row initializes one agent, and the values in the init facet identify result-column names. For example, the packaged PostGIS model maps the type column to nature and the geom column to shape:

  • Step 1: Define a species with the sql skill or inherit from AgentDB.
species DB_accessor skills: [sql] {
//insert your descriptions here
}
  • Step 2: Define a connection and selection parameters
global {
map<string,string> PARAMS <- [
'host'::'localhost',
'dbtype'::'postgis',
'database'::'spatial_db',
'port'::'5432',
'user'::'postgres',
'passwd'::''];
string QUERY <- "SELECT type, ST_AsEWKB(geom) as geom FROM buildings;";
}
  • Step 3: Create species by using selected results
init {
create DB_accessor {
create buildings(nature: "type", shape: "geom") from: select(PARAMS, QUERY);
}
}

Save Geometry data to database​

To create a PostGIS database and save agent geometries, first prepare an existing PostgreSQL database named template_postgis with the PostGIS extension installed. The target database must not already exist. Connect to the server with an empty database value, create the target database from the template, then update the connection map before creating its tables. This avoids trying to connect to the target before it exists.

  • Step 1: Define a species with the sql skill or inherit from AgentDB.
species DB_accessor skills: [sql] {
//insert your descriptions here
}
  • Step 2: Define a connection and create GIS database and tables
global {
map<string,string> PARAMS <- ['host'::'localhost', 'dbtype'::'postgres', 'database'::'',
'port'::'5434', 'user'::'postgres', 'passwd'::''];
string database_name <- "spatial_db";

init {
create DB_accessor;
ask DB_accessor {
if (testConnection(PARAMS)) {
do executeUpdate(params: PARAMS,
updateComm: "CREATE DATABASE " + database_name + " WITH TEMPLATE = template_postgis;");
put database_name key: "database" in: PARAMS;
do executeUpdate(params: PARAMS, updateComm:
"CREATE TABLE bounds (geom GEOMETRY)");
do executeUpdate(params: PARAMS, updateComm:
"CREATE TABLE buildings (name character varying(255), type character varying(255), geom GEOMETRY)");
} else {
write "Connection to PostgreSQL cannot be established.";
}
}
}
}
  • Step 3: Insert geometry data to the GIS database
ask building {
ask DB_accessor {
do insert(params: PARAMS,
into: "buildings",
data: ["name"::myself.name, "type"::myself.type, "geom"::myself.shape]);
}
}