Data
****

exception psynet.data.DatabaseInUseError

   Bases: "RuntimeError"

   Raised when replacing the local database while another client is
   connected.

exception psynet.data.InvalidDefinitionError

   Bases: "ValueError"

   InvalidDefinitionError class

class psynet.data.SQLMixin(*args, **kwargs)

   Bases: "SQLMixinDallinger"

   We apply this mixin when creating our own SQL-backed classes from
   scratch. For example:

      from psynet.data import SQLBase, SQLMixin, register_table

      @register_table
      class Bird(SQLBase, SQLMixin):
          __tablename__ = "bird"

      class Sparrow(Bird):
          pass

class psynet.data.SQLMixinDallinger(*args, **kwargs)

   Bases: "SharedMixin"

   We apply this Mixin class when subclassing Dallinger classes, for
   example "Network" and "Info". It adds a few useful exporting
   features, but most importantly it adds automatic mapping logic, so
   that polymorphic identities are constructed automatically from
   class names instead of having to be specified manually. For
   example:

      from dallinger.models import Info

      class CustomInfo(Info)
          pass

   to_dict()

      Determines the information that is shown for this object in the
      dashboard.

psynet.data.assert_database_idle_for_replace(*, wait_sec=None)

   Refuse to drop tables while another same-role client is connected.

   Closes this process's ORM sessions and connection pool first so
   idle pooled connections here are not counted. When "wait_sec" is
   positive, leftover backends that disappear after a just-killed
   debug server are allowed to drain before refusing. The pool is
   released once; later polls only list other backends.

psynet.data.drop_all_db_tables(bind=db.engine, *, max_attempts=5, wait_sec=0.05)

   Drop every table, retrying leftover lock errors.

   SQLAlchemy's "drop_all" has no CASCADE option, which used to break
   Dallinger's "init_db" reset (https://github.com/pallets-eco/flask-
   sqlalchemy/issues/722). "DROP TABLE" needs "ACCESS EXCLUSIVE" and
   can still deadlock with a leftover backend after the experiment
   server should have stopped. Retry the whole drop; a partial drop
   rolls back with the aborted transaction. "psynet load" refuses that
   path while another client with this database role is still
   connected, including before each leftover-lock retry.

psynet.data.export_asset(asset_id, assets_root, server, local)

   Export one asset's bytes into the semantic export tree.

   For managed assets with a known SHA-256 digest the local cache at
   "~/psynet-data/cache/assets" is consulted first; only objects
   absent from the cache are fetched from storage. Cached objects are
   linked into the export directory at the asset's "export_path"
   (hardlink when possible, copy otherwise).

   Returns:
      "sha256_contents" / "export_path" / "object_path" for the
      manifest when bytes were exported. Does not mutate Asset
      database rows.

   Return type:
      dict or None

psynet.data.export_assets(path, server=None, local=False, manifest_only=False)

   Export collected assets into "path" using semantic "export_path"
   trees.

   Callers typically pass "<export_dir>/assets". Layout:

      <path>/
      ├── manifest.csv
      └── <module>/.../<semantic export_path>

   Bytes are still fetched via the content-addressed local cache; the
   export tree itself uses human-readable paths from
   "Asset.export_path". SSH command-line exports prefetch missing
   LocalStorage objects with one "rsync --files-from" into that cache.
   There is no per-asset SFTP fallback: if rsync cannot supply the
   bytes, the caller stops or switches to a complete server-built
   archive.

   "manifest_only" writes "manifest.csv" without copying any bytes.
   The incremental SSH transport uses this so the server can describe
   the asset selection cheaply while the client fetches the bytes over
   rsync.

psynet.data.get_db_tables()

   Lists the tables in the database.

   Returns:
      * *A dictionary where the keys identify the tables and the
        values are the table objects themselves.*

psynet.data.get_primary_key_values(instance)

   Return primary key values for an ORM instance.

psynet.data.get_sql_base_class(x)

   Return the SQLAlchemy base class of an object x, returning None if
   no such base class is found.

psynet.data.ingest_to_model(file, model, engine=None, clear_columns=None, replace_columns=None, drop_foreign_keys=True)

   Imports a CSV file to the database. The implementation is similar
   to "dallinger.data.ingest_to_model", but incorporates a few extra
   parameters ("clear_columns", "replace_columns") and does not fail
   for tables without an "id" column.

   Parameters:
      * **file** -- CSV file to import (specified as a file handler,
        created for example by open())

      * **model** -- SQLAlchemy class corresponding to the objects
        that should be created.

      * **clear_columns** ("Optional"["List"]) -- Optional list of
        columns to clear when importing the CSV file. This is useful
        in the case of foreign-key constraints (e.g. participant IDs).

      * **replace_columns** ("Optional"["dict"]) -- Optional
        dictionary of values to set for particular columns.

      * **drop_foreign_keys** ("bool") -- Whether to drop every
        foreign-key constraint before importing. Callers importing
        many tables should drop them once and pass "False", because
        finding the constraints reflects every table in the database.

psynet.data.ingest_zip(path, engine=None)

   Recreate the database from an export archive.

   "path" may be:

   * an "export.zip" (reads "database/<table>.csv" members; also
     accepts legacy "data/<table>.csv" members);

   * a "database/" directory of table CSVs;

   * an extracted export directory containing "database/".

   Nested lookalikes and mixed "database/" plus "data/" layouts are
   rejected. This patches Dallinger's "ingest_zip" with support for
   custom PsyNet tables and the flat "database/" export layout.

psynet.data.populate_db_from_zip_file(zip_path)

   Replace the contents of the local database with an exported
   archive.

   This drops every table first, so it must only be used where losing
   the current local database is the point ("psynet load"). Stop any
   local experiment server first; a connected "psynet debug" process
   is refused rather than dropped out from under, because "drop_all"
   deadlocks if the clock still holds locks.

psynet.data.register_table(cls)

   This decorator should be applied whenever defining a new SQLAlchemy
   table. For example:

      @register_table
      class Bird(SQLBase, SQLMixin):
          __tablename__ = "bird"

psynet.data.sql_base_classes()

   Lists the base classes underpinning the different SQL tables used
   by PsyNet, including both base classes defined in Dallinger (e.g.
   "Node", "Info") and additional classes defined in custom PsyNet
   tables.

   Returns:
      * A dictionary of base classes (e.g. "Node"), keyed by the
        corresponding

      * table names for those base classes (e.g. *node*).

psynet.data.update_dashboard_models()

   Determines the list of objects in the dashboard database browser.

class psynet.data.SQLBase

   SQLAlchemy declarative base for experiment tables, re-exported from
   "dallinger.db.Base". Combine it with "SQLMixin" and
   "register_table()" to define a custom table:

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

psynet.db.blocking_psycopg()

   Suspend the psycopg2 wait callback, e.g. around "copy_expert".

   Experiment code must wrap any PostgreSQL "COPY" in this context
   manager, because psycopg2 rejects "COPY" while the callback is
   installed. The callback is process-wide, so overlapping suspensions
   from different greenlets or threads are counted and the callback
   returns only when the last one exits. Keep the block short: while
   it is active, every query in the process, from any greenlet, blocks
   the whole process until it returns.
