Querying and storing database objects
*************************************

Participants, trials, nodes, networks, assets, error logs and
asynchronous processes are **database-backed**: each object is a row
in PsyNet's PostgreSQL database, so its state is shared across server
processes and persists for the whole experiment. The mapping between
Python objects and database rows is implemented with SQLAlchemy.

As long as you use existing attributes and variable stores, such as
"participant.var.my_variable", changes are saved without extra work.
This page covers querying, custom columns, updating or creating
objects directly, and custom tables. It assumes familiarity with
Python classes, subclasses and "super()"; the Python tutorial on
classes covers them.


Tables and objects
==================

Each database-backed class has a table. Each row is an object, and
each column is an attribute with a name and a data type such as
integer, string or float. The "participant" table, for example, has
columns such as "id", "status", "worker_id", "base_pay" and "bonus".
SQLAlchemy exposes the columns as attributes:

   from psynet.participant import Participant

   participant = Participant.query.filter_by(id=1).one()

   participant.status  # read a column
   participant.status = "approved"  # write a column

The dashboard's database tab shows the tables and their contents. A
database viewer such as Postico shows the columns too:

   [image]

Subclassing a database-backed class, such as a trial class, defines a
new SQLAlchemy class. All class names within an experiment must be
unique, including classes imported from other packages.

PsyNet's participants, nodes and networks are built on the
corresponding classes of Dallinger, the platform PsyNet runs on.


Query objects
=============

A query loads objects from the database, like an SQL "SELECT"
statement. This returns all "CustomTrial" objects:

   trials = CustomTrial.query.all()

The result is a list. Filtering it in Python is fine for small numbers
of objects, but two costs grow quickly:

1. **Each query has a significant fixed overhead.** SQLAlchemy
   compiles an SQL command, sends it to the database, waits for the
   response, and parses the result. Loading 200 records in one query
   is much faster than loading them in 200 queries.

2. **Filtering in Python is slow.** The first access to an attribute
   of an SQLAlchemy object takes a few milliseconds, so filtering more
   than a few hundred objects in Python is prohibitively slow.

Filter in the query instead. "filter_by" finds all trials from
participant 5:

   CustomTrial.query.filter_by(participant_id=5).all()

".all()" always returns a list. ".one()" returns a single object, and
raises an error unless exactly one object matches. ".count()" returns
the number of matches:

   Participant.query.filter_by(status="approved").count()


Add a column to filter on
-------------------------

Queries can filter only on columns. Variables stored in "var" are
stored together as JSON, so queries can't filter on them. To filter on
a value, define it as a column:

   import random

   from sqlalchemy import Column, Integer

   class CustomTrial(GibbsTrial):
       random_integer = Column(Integer)

       def __init__(self, *args, **kwargs):
           super().__init__(*args, **kwargs)
           self.random_integer = random.randint(0, 10)

Queries can then filter on the column:

   CustomTrial.query.filter_by(random_integer=3).all()

Note:

  All trial classes share one "trial" table, and the same applies to
  other classes that share a table. Two classes that declare a column
  with the same name share that column, so the declarations must match
  exactly; PsyNet raises an error asking you to rename the column
  otherwise.

SQLAlchemy provides column types that map to PostgreSQL types, such as
"Integer", "DateTime", "Float", "Text", and "String"; see the
SQLAlchemy type documentation. "psynet.field" adds more, most
importantly "PythonObject", a general-purpose column that stores
arbitrary data, including database objects, serialized with
"jsonpickle".


Filter with comparisons and joins
---------------------------------

"filter" takes comparison expressions, so it is more flexible than
"filter_by":

   CustomTrial.query.filter(CustomTrial.random_integer >= 5).all()
   CustomTrial.query.filter(CustomTrial.random_integer != 5).all()

To filter on the columns of another class, join the two tables on a
related column. The trial table's "participant_id" column refers to
the participant table's "id" column, so this selects all trials from
approved participants:

   from dallinger import db
   from psynet.participant import Participant

   (
       db.session.query(CustomTrial)
       .join(Participant, CustomTrial.participant_id == Participant.id)
       .filter(Participant.status == "approved")
       .all()
   )


Update objects
==============

Change an object by assigning to its attributes. PsyNet saves the
change to the database when it commits the transaction (see Saving
changes):

   from psynet.participant import Participant

   participant = Participant.query.filter_by(id=1).one()
   participant.status = "approved"

SQLAlchemy does not track in-place changes to a "PythonObject"
column's value, such as updating a dictionary or appending to a list.
Mark the column as changed so the change is saved on commit:

   from sqlalchemy.orm.attributes import flag_modified

   trial.my_list.append(3)
   flag_modified(trial, "my_list")

"var" stores track assignments to top-level variables, but not in-
place changes to a stored dictionary or list. Assign a new value
instead:

   trial.var.my_dict = {**trial.var.my_dict, "value": 3}


Create objects
==============

Database objects are created like ordinary Python objects, then added
to the database session:

   from dallinger import db

   trial = CustomTrial(
       experiment=experiment,
       node=node,
       participant=participant,
       propagate_failure=False,
       is_repeat_trial=False,
   )
   db.session.add(trial)
   db.session.flush()

"db.session.add" registers the object with the database, and
"db.session.flush" sends it to the database so that it gets an "id".
PsyNet saves it when it commits the transaction. Trial makers and
"cue()" normally create trials for you; creating trials directly is
mainly needed for custom network architectures.


Saving changes
==============

PsyNet runs experiment code inside a database transaction and commits
it once the step has finished. This includes code blocks, page makers,
page methods such as "format_answer", "validate", "on_complete" and
"pre_render", trial methods such as "show_trial" and
"finalize_definition", and trial maker hooks such as "grow_network",
"finalize_trial" and "select_node". While this code runs, the
transaction holds a lock on the participant's database row.

Do not call "db.session.commit()" or "db.session.rollback()" in this
code. Committing early releases the participant's lock, so a second
request from the same participant can interleave with this one, and it
saves half-finished changes if a later step fails. PsyNet raises a
"RuntimeError" that names the offending code if it commits or rolls
back.

Call "db.session.flush()" when you need a new object's "id" straight
away. Flushing sends pending changes to the database within the
current transaction, without committing them:

   def create_pet(participant):
       pet = Dog(participant)
       db.session.add(pet)
       db.session.flush()
       participant.var.current_pet = pet.id

The same applies to helper code called from these places, including
custom recruiter methods such as "release_participant". A helper
should leave committing to the code that started the transaction, and
flush if it needs database-generated values.

Recruiter calls that pay participants or end their panel session must
save a record alongside the call, so that a crash cannot repeat or
lose it. These are "experiment.pay_decided_bonus",
"recruiter.reward_bonus", "recruiter.report_submission_outcome", and
Lucid's "terminate_participant" and "complete_participant". They raise
in these places too, before contacting the platform, even when there
is nothing to pay or the session has already ended. Make them from an
"AsyncCodeBlock", which runs in a worker after the step has committed.
A custom recruiter that posts a payment should call
"experiment.commit_payment_state()" just before the post, so that a
crash cannot repeat the payment.

Code that does not run as part of a participant's progress through the
timeline manages its own transaction. For example, POST routes defined
with "@experiment_route" must call "db.session.commit()"; see
Exchanging data with the server.


Define a custom table
=====================

To store objects that don't fit PsyNet's classes, define a new table.
The class inherits from "SQLBase" and "SQLMixin", both imported from
"psynet.data", sets "__tablename__", and is decorated with
"register_table()", which adds the table to the dashboard's database
tab and to data exports. "SQLMixin" provides the standard columns,
such as "id", "creation_time" and "failed".

"demos/features/custom_table_simple" stores a coin each time the
participant chooses to collect one. The "relationship" with a
"backref" gives each participant an "all_coins" attribute:

   @register_table
   class Coin(SQLBase, SQLMixin):
       __tablename__ = "coin"

       participant = relationship(Participant, backref="all_coins")
       participant_id = Column(Integer, ForeignKey("participant.id"), index=True)

       def __init__(self, participant):
           self.participant = participant
           self.participant_id = participant.id


   def collect_coin():
       return CodeBlock(_collect_coin)


   def _collect_coin(participant):
       coin = Coin(participant)
       db.session.add(coin)


   def report_n_coins():
       return PageMaker(_report_n_coins, time_estimate=5)


   def _report_n_coins(participant):
       coins = participant.all_coins
       n_coins = len(coins)
       return InfoPage(f"You currently have {n_coins} coin(s).", time_estimate=5)



Subclasses of a custom table class share its table, and each subclass
can add its own columns. "demos/features/custom_table_complex" stores
dogs and cats in one "pet" table:

   @register_table
   class Pet(SQLBase, SQLMixin):
       __tablename__ = "pet"

       base_price = None

       participant = relationship(Participant, backref="all_pets")
       participant_id = Column(Integer, ForeignKey("participant.id"), index=True)

       price = Column(Float)
       name = Column(String)

       def __init__(self, participant):
           self.price = self.base_price
           self.participant = participant
           self.participant_id = participant.id

   class Dog(Pet):
       base_price = 500
       comes_with_kennel = Column(Boolean)

       @classmethod
       def get_purchase_details(cls):
           return super().get_purchase_details() + [cls.ask_comes_with_kennel()]

       @classmethod
       def ask_comes_with_kennel(cls):
           return ModularPage(
               "pet_kennel",
               "Do you want to purchase a kennel as well?",
               PushButtonControl(choices=["Yes", "No"]),
               time_estimate=2.5,
               save_answer="temp__comes_with_kennel",
           )

       def save_purchase_details(self, participant):
           super().save_purchase_details(participant)

           comes_with_kennel = participant.var.temp__comes_with_kennel
           assert comes_with_kennel in ["Yes", "No"]
           self.comes_with_kennel = comes_with_kennel == "Yes"

The demo's timeline creates a pet with "db.session.add" and
"db.session.flush", stores its "id" in a participant variable, and
queries it again with "Pet.query.filter_by(id=...)" on later pages.


Find slow queries
=================

"psynet test local --sql-profile" reports the SQL queries that the
experiment runs and how long they take; see SQLAlchemy profiling.
