{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Databases, schemas and a chemical database\n",
    "\n",
    "The kinds of database and what each is for, how to plan tables for chemical data before storing anything, how to describe them, and a chemical database in PostgreSQL with the RDKit cartridge, searched by substructure and similarity.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/04-databases-and-schemas/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q rdkit pandas numpy duckdb psycopg[binary] python-dotenv\n",
    "\n",
    "# Cells that start with %%needs use a database. They run only where it is set up (see\n",
    "# the database guide); elsewhere, such as in Colab, they are skipped and the rest of the\n",
    "# lesson still runs. Their outputs are on the lesson's page.\n",
    "import os\n",
    "from IPython.core.magic import register_cell_magic\n",
    "\n",
    "\n",
    "@register_cell_magic\n",
    "def needs(service, cell):\n",
    "    \"\"\"Run this cell only if the database it needs is set up.\"\"\"\n",
    "    variable = {'postgres': 'DATABASE_URL'}[service.strip()]\n",
    "    if os.environ.get(variable):\n",
    "        get_ipython().run_cell(cell)\n",
    "    else:\n",
    "        print(f\"Skipped: this cell needs {service.strip()}, which is not set up here.\"\n",
    "              \" Its output is shown on the lesson's page.\")\n",
    "\n",
    "\n",
    "import pathlib\n",
    "import urllib.request\n",
    "if not pathlib.Path(\"chemlib.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/shared/chemlib.py\", \"chemlib.py\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far our molecules have lived in files: SMILES in CSV files, tables in Parquet files\n",
    "([Module 3](../03-files-and-identity/)). Files are fine for one person and one question. They stop\n",
    "being enough when several people add data at the same time, when the same compound arrives from\n",
    "three suppliers, when an assay result must always point to the batch it was measured on, or when a\n",
    "colleague asks \"which acids under 300 g/mol did we test against EGFR?\" and expects an answer in a\n",
    "second. That is the job of a **database**: a program that stores data in an organised way, checks\n",
    "it as it goes in, and answers questions about it.\n",
    "\n",
    "This module starts with the kinds of database and what each is good at. Then it does the step most\n",
    "people skip: planning the tables before storing anything (**data modelling**). We build the plan as\n",
    "real tables, with rules that stop bad data getting in, describe them so others can use them, and\n",
    "reshape them for analysis. Finally we put the molecules into PostgreSQL with its chemistry add-on,\n",
    "search them by substructure and similarity, and give a colleague safe, read-only access.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- name the main kinds of database (including the \"NoSQL\" kinds) and say which questions each\n",
    "  answers best;\n",
    "- plan the tables for chemical data: what things you store, how they are linked, and what rules\n",
    "  each value must follow, drawn as a diagram;\n",
    "- explain why each fact should be stored once, and show what goes wrong in a spreadsheet when it is\n",
    "  not;\n",
    "- create tables with keys and rules in SQL, and see the database refuse bad data;\n",
    "- ask questions in SQL: filter, sort, join tables and summarise;\n",
    "- describe a database so others can use it (a data dictionary), and record where each row came\n",
    "  from;\n",
    "- reshape tables for analysis (a star schema);\n",
    "- store molecules in PostgreSQL with the RDKit cartridge, search them by substructure and by\n",
    "  similarity, and see an index make a search faster;\n",
    "- give a colleague read-only access, and keep passwords out of your code;\n",
    "- see how SQL injection works, and stop it with parameters and lists of allowed names.\n",
    "\n",
    "From earlier modules we use SMILES, InChIKeys, SMARTS patterns and fingerprints\n",
    "([Module 2](../02-text-patterns-and-numbers/)), and the course's helper file `chemlib`, which makes\n",
    "a library of realistic molecules ([Module 3](../03-files-and-identity/)).\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **DuckDB**, a database that runs inside Python, with nothing to install or start: the whole\n",
    "  database is one file (or lives in memory). We use it for sections 3 to 6, so they run anywhere,\n",
    "  Colab included;\n",
    "- **psycopg**, which lets Python talk to a PostgreSQL database server (section 7 onwards);\n",
    "- **pandas** and **NumPy** for tables and numbers, and **RDKit** for the chemistry, as before.\n",
    "\n",
    "**What runs where.** Sections 1 to 6 run in Colab or on any computer. Sections 7 and 8 need\n",
    "**PostgreSQL**, a database server, running on your own computer in Docker; [the database\n",
    "guide](https://monstrous.com.ng/learn/databases/) shows how to install Docker and start it, step by\n",
    "step, in about twenty minutes. Their code starts with the line `# needs: postgres`; without the\n",
    "database those blocks do nothing, and you can still read them and their outputs here.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Every lesson starts with this block. It loads the packages and sets the lesson's settings, written\n",
    "in CAPITALS, so they can be changed in one place. Run it first. Two settings come from\n",
    "**environment variables** (named values your terminal passes to programs) rather than from the\n",
    "code: where the PostgreSQL database is, and the password we give a colleague in section 8. On your\n",
    "own computer they are kept in a file called `.env` at the repository's root, which you make once by\n",
    "copying `.env.example` and choosing your own passwords (the database guide shows how);\n",
    "`load_dotenv` reads it. Passwords never belong in code; section 8 explains why."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import psycopg\n",
    "from dotenv import find_dotenv, load_dotenv\n",
    "from psycopg import sql\n",
    "from psycopg.conninfo import make_conninfo\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Descriptors\n",
    "\n",
    "from chemlib import library\n",
    "\n",
    "# log lines: level and message only, so the lesson's outputs are the same on every run\n",
    "# (a real job would add \"%(asctime)s\" to the format)\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "\n",
    "# the lesson's data: a library from chemlib, offered by three suppliers and tested on two targets.\n",
    "# The compounds are realistic; the prices and assay results are made up for the lesson.\n",
    "N_COMPOUNDS = 1_500  # compounds drawn from chemlib\n",
    "LIBRARY_SEED = 4  # which compounds\n",
    "N_MEASUREMENTS = 4_000  # assay results\n",
    "DATA_SEED = 44  # seed for the made-up batches and results\n",
    "SUPPLIERS = [(\"Vendor A\", \"United Kingdom\"), (\"Vendor B\", \"Germany\"), (\"Vendor C\", \"India\")]\n",
    "TARGETS = [(\"CHEMBL203\", \"EGFR\", \"Homo sapiens\"), (\"CHEMBL205\", \"Carbonic anhydrase II\", \"Homo sapiens\")]  # fmt: skip\n",
    "LOADED_ON = \"2026-11-24\"  # the load date recorded with every row; fixed, so outputs never change\n",
    "SOURCE = \"chemlib library, seed 4\"  # where the rows came from, recorded with every row\n",
    "\n",
    "# where the lesson writes its files (git-ignored)\n",
    "WORK = Path(\"work\")\n",
    "DUCKDB_FILE = WORK / \"chem.duckdb\"\n",
    "\n",
    "# passwords and addresses: from the environment, or from the course's .env file (copied from\n",
    "# .env.example at the repository's root); find_dotenv looks for it in this folder and the ones\n",
    "# above, and settings already in the environment are kept\n",
    "load_dotenv(find_dotenv(usecwd=True))\n",
    "DATABASE_URL = os.environ.get(\"DATABASE_URL\", \"\")\n",
    "PG_SCHEMA = \"module4\"  # the lesson's own area inside the database, emptied at the start of section 7\n",
    "ANALYST = \"analyst\"  # the read-only colleague of section 8\n",
    "ANALYST_PASSWORD = os.environ.get(\"ANALYST_PASSWORD\", \"\")\n",
    "ACID_SMARTS = \"[CX3](=O)[OX2H1]\"  # a carboxylic acid: C=O and an O carrying one H (Module 2)\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")  # chemlib's molecules all parse; RDKit has nothing to tell us\n",
    "WORK.mkdir(exist_ok=True)\n",
    "DUCKDB_FILE.unlink(missing_ok=True)  # start the lesson with an empty database file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Kinds of database\n",
    "\n",
    "A database is more than a file: it is a program that holds the data, and every change and question\n",
    "goes through it. That lets it do things a file cannot: refuse a value that breaks a rule, let many\n",
    "people read and write at the same time without trampling on each other, and answer questions\n",
    "quickly by keeping **indexes** (lookup tables, like the index at the back of a book).\n",
    "\n",
    "There is no single best database. Each kind stores data in a different shape and is fast at\n",
    "different questions:\n",
    "\n",
    "| Kind | The data looks like | Good at | Examples | In chemistry |\n",
    "|---|---|---|---|---|\n",
    "| Relational (SQL) | tables of rows and columns, linked by keys | keeping data correct while many people change it | PostgreSQL, SQLite, MySQL | compound registration, assay results |\n",
    "| Analytical (columnar) | tables, stored column by column | adding up millions of rows quickly | DuckDB, BigQuery, Snowflake | analysing screening campaigns |\n",
    "| Document | records like JSON, each with its own fields | records whose fields vary | MongoDB, CouchDB | instrument metadata, lab notebook entries |\n",
    "| Key-value | a value stored under a key | the fastest possible lookup by one key | Redis | a cache of computed descriptors, by InChIKey |\n",
    "| Wide-column | huge tables spread over many machines | very large write volumes, across a cluster | Cassandra, HBase | readings from thousands of instruments |\n",
    "| Graph | nodes joined by relationships | following links many steps deep | Neo4j | reaction networks, compound-target-pathway links ([Module 5](../05-graphs-and-graph-databases/)) |\n",
    "| Vector | lists of numbers (embeddings) | \"find the most similar\" | pgvector, Milvus, Qdrant | similarity search on learned molecular embeddings |\n",
    "\n",
    "The first row is the classic **relational database**, questioned in **SQL** (Structured Query\n",
    "Language). The second stores the same kind of tables differently, for analysis; it is also\n",
    "questioned in SQL. The others are together called **NoSQL** (\"not only SQL\"). Each gives up\n",
    "something a relational database guarantees, such as joins between tables, changes to several\n",
    "records that succeed or fail together, or a fixed set of columns, in exchange for scale or\n",
    "flexibility. That trade is worth making for some jobs, and not for most chemical records, where a\n",
    "measurement that points to a batch that does not exist is simply wrong.\n",
    "\n",
    "The lines between kinds have blurred: PostgreSQL stores JSON documents, vectors (with the pgvector\n",
    "add-on) and, with the RDKit add-on, molecules. A sound default for chemical data is a relational\n",
    "database for the records and an analytical one for the questions, which is what this module\n",
    "builds. Module 5 adds a graph database for questions about links.\n",
    "\n",
    "## 2. Plan the tables before storing anything\n",
    "\n",
    "The commonest way chemical data is stored is one big spreadsheet: a row per measurement, with the\n",
    "compound's structure, the supplier's name and the target's name typed into every row. Let us build\n",
    "that spreadsheet from our data and see what goes wrong. First the data itself: compounds from\n",
    "`chemlib`, each offered by one to three suppliers as a **batch** (one supplier's lot of a compound,\n",
    "with its own price), and assay results on two targets, each measured on a batch:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1,500 compounds, 2,998 batches, 4,000 measurements\n"
     ]
    }
   ],
   "source": [
    "compounds = library(N_COMPOUNDS, seed=LIBRARY_SEED)[[\"smiles\"]].reset_index(drop=True)\n",
    "mols = [Chem.MolFromSmiles(s) for s in compounds[\"smiles\"]]\n",
    "compounds[\"smiles\"] = [Chem.MolToSmiles(m) for m in mols]  # canonical SMILES (Module 2)\n",
    "compounds[\"inchikey\"] = [Chem.MolToInchiKey(m) for m in mols]  # the compound's identity\n",
    "compounds[\"mw\"] = [round(Descriptors.MolWt(m), 2) for m in mols]\n",
    "compounds.insert(0, \"compound_id\", range(1, len(compounds) + 1))\n",
    "\n",
    "rng = np.random.default_rng(DATA_SEED)\n",
    "batch_rows = []\n",
    "for cid in compounds[\"compound_id\"]:\n",
    "    # each compound is sold by one, two or three of the suppliers, each at its own price\n",
    "    for supplier_id in sorted(rng.choice([1, 2, 3], size=rng.integers(1, 4), replace=False)):\n",
    "        batch_rows.append((cid, int(supplier_id), round(float(rng.uniform(15, 400)), 2),\n",
    "                           int(rng.choice([5, 10, 25, 50, 100]))))  # fmt: skip\n",
    "batches = pd.DataFrame(batch_rows, columns=[\"compound_id\", \"supplier_id\", \"price_usd\", \"amount_mg\"])\n",
    "batches.insert(0, \"batch_id\", range(1, len(batches) + 1))\n",
    "\n",
    "# made-up assay results: pIC50 values, a little lower on Vendor C's batches (a purity problem)\n",
    "pick = rng.integers(0, len(batches), size=N_MEASUREMENTS)\n",
    "target = rng.integers(0, len(TARGETS), size=N_MEASUREMENTS)\n",
    "pic50 = rng.normal(np.where(target == 0, 6.3, 5.5), 0.7) - 0.4 * (batches[\"supplier_id\"].to_numpy()[pick] == 3)  # fmt: skip\n",
    "measurements = pd.DataFrame({\n",
    "    \"measurement_id\": range(1, N_MEASUREMENTS + 1),\n",
    "    \"batch_id\": batches[\"batch_id\"].to_numpy()[pick],\n",
    "    \"target_id\": [TARGETS[t][0] for t in target],\n",
    "    \"ic50_nm\": np.round(10 ** (9 - pic50), 1),\n",
    "    \"measured_on\": pd.Timestamp(\"2026-01-05\") + pd.to_timedelta(rng.integers(0, 300, N_MEASUREMENTS), unit=\"D\"),\n",
    "})  # fmt: skip\n",
    "print(f\"{len(compounds):,} compounds, {len(batches):,} batches, {len(measurements):,} measurements\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**IC50** is the concentration of a compound that halves the target's activity, here in nanomolar\n",
    "(nM); **pIC50** is the same on a log scale, 9 minus the log10 of the IC50 in nM, so higher means\n",
    "more potent. Now the spreadsheet: every measurement with everything about it copied into its row.\n",
    "`merge` joins two tables on a shared column, as in Module 3:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "4000 rows, 11 columns\n",
      "supplier\n",
      "Vendor A    1370\n",
      "Vendor B    1331\n",
      "Vendor C    1299\n"
     ]
    }
   ],
   "source": [
    "suppliers = pd.DataFrame([(i + 1, n, c) for i, (n, c) in enumerate(SUPPLIERS)],\n",
    "                         columns=[\"supplier_id\", \"name\", \"country\"])  # fmt: skip\n",
    "targets = pd.DataFrame(TARGETS, columns=[\"target_id\", \"name\", \"organism\"])\n",
    "sheet = (\n",
    "    measurements.merge(batches, on=\"batch_id\")\n",
    "    .merge(compounds, on=\"compound_id\")\n",
    "    .merge(suppliers.rename(columns={\"name\": \"supplier\"}), on=\"supplier_id\")\n",
    "    .merge(targets.rename(columns={\"name\": \"target\"}), on=\"target_id\")\n",
    "    [[\"measurement_id\", \"smiles\", \"inchikey\", \"mw\", \"supplier\", \"country\", \"price_usd\",\n",
    "      \"target\", \"organism\", \"ic50_nm\", \"measured_on\"]]\n",
    ")  # fmt: skip\n",
    "print(sheet.shape[0], \"rows,\", sheet.shape[1], \"columns\")\n",
    "print(sheet[\"supplier\"].value_counts().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each supplier's name and country are typed out about 1,300 times, and each compound's SMILES,\n",
    "InChIKey and weight once for every measurement on it. Repetition is more than wasted space. Suppose\n",
    "a colleague corrects some rows by hand and types Vendor B with a trailing space, and Vendor A moves\n",
    "its address to Ireland but only some rows are updated:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "suppliers: 4\n",
      "country\n",
      "United Kingdom    685\n",
      "Ireland           663\n"
     ]
    }
   ],
   "source": [
    "messy = sheet.copy()\n",
    "messy.loc[messy.index[::50], \"supplier\"] = \"Vendor B \"  # a stray space, typed by hand\n",
    "moved = messy[\"supplier\"].eq(\"Vendor A\")\n",
    "messy.loc[moved & (messy.index < 2000), \"country\"] = \"Ireland\"  # only half the rows updated\n",
    "print(\"suppliers:\", messy[\"supplier\"].nunique())\n",
    "print(messy[messy[\"supplier\"] == \"Vendor A\"][\"country\"].value_counts().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the spreadsheet says there are four suppliers, and Vendor A is in two countries at once. These\n",
    "are called **update anomalies**: a fact stored in many places goes out of step with itself. The fix\n",
    "is to store each fact **once**, in its own table, and point to it. That is the idea behind\n",
    "**normalisation**, and planning those tables is **data modelling**. It goes in three steps:\n",
    "\n",
    "1. **Conceptual model: what things do we store, and how are they related?** In plain words: a\n",
    "   *compound* is a structure, identified by its InChIKey. A *supplier* sells compounds. A *batch* is\n",
    "   one supplier's lot of one compound, with a price. A *target* is a protein we test against. A\n",
    "   *measurement* is one result, of one batch, on one target. Each of these things is an **entity**.\n",
    "   The links are **one-to-many**: one compound has many batches, one batch many measurements.\n",
    "2. **Logical model: which tables and columns?** One table per entity, each row with an\n",
    "   **identifier**, and links written as columns that hold another table's identifier: a batch row\n",
    "   holds a `compound_id` and a `supplier_id`. This is usually drawn as an\n",
    "   **entity-relationship (ER) diagram**, like the one below.\n",
    "3. **Physical model: the exact database.** Column types (whole number, decimal, text, date), the\n",
    "   rules each value must follow, units, and indexes, written in SQL for the database we use.\n",
    "\n",
    "![The lesson's data model as an entity-relationship diagram: five tables, supplier, compound, batch, target and measurement, each listing its columns with the key marked; lines run from batch to compound and to supplier, and from measurement to batch and to target, each line marked one at one end and many at the other](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/04-databases-and-schemas/figures/er-diagram.svg)\n",
    "\n",
    "Two kinds of **key** hold the model together. A **primary key** is the column that identifies a\n",
    "row, unique and never empty: `compound_id`. A **foreign key** is a column that holds another\n",
    "table's primary key, and the database checks that the row it points to exists: `batch.compound_id`\n",
    "must be a real compound. Where a value has a unit, the unit goes in the column's name\n",
    "(`ic50_nm`, `price_usd`, `amount_mg`), so nobody has to guess it.\n",
    "\n",
    "## 3. Build the tables, with rules\n",
    "\n",
    "We build the model in **DuckDB**, which needs no server: `duckdb.connect` opens (or creates) a\n",
    "database file. **SQL** describes tables with `CREATE TABLE`: each column has a name, a type, and\n",
    "optional rules (**constraints**):\n",
    "\n",
    "- `PRIMARY KEY` and `REFERENCES other_table` for the two kinds of key;\n",
    "- `NOT NULL`: the value must be given (a missing value is `NULL` in SQL);\n",
    "- `UNIQUE`: no two rows may have the same value;\n",
    "- `CHECK (...)`: any condition the value must meet, such as a price of at least zero."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['batch', 'compound', 'measurement', 'supplier', 'target']\n"
     ]
    }
   ],
   "source": [
    "db = duckdb.connect(DUCKDB_FILE)\n",
    "db.execute(\"\"\"\n",
    "CREATE TABLE supplier (\n",
    "    supplier_id INTEGER PRIMARY KEY,\n",
    "    name        VARCHAR NOT NULL UNIQUE,\n",
    "    country     VARCHAR NOT NULL\n",
    ");\n",
    "CREATE TABLE compound (\n",
    "    compound_id INTEGER PRIMARY KEY,\n",
    "    inchikey    VARCHAR NOT NULL UNIQUE CHECK (length(inchikey) = 27),\n",
    "    smiles      VARCHAR NOT NULL,\n",
    "    mw          DECIMAL(7, 2) NOT NULL CHECK (mw > 0),\n",
    "    source      VARCHAR NOT NULL,\n",
    "    loaded_on   DATE NOT NULL\n",
    ");\n",
    "CREATE TABLE batch (\n",
    "    batch_id    INTEGER PRIMARY KEY,\n",
    "    compound_id INTEGER NOT NULL REFERENCES compound (compound_id),\n",
    "    supplier_id INTEGER NOT NULL REFERENCES supplier (supplier_id),\n",
    "    price_usd   DECIMAL(8, 2) NOT NULL CHECK (price_usd >= 0),\n",
    "    amount_mg   INTEGER NOT NULL CHECK (amount_mg > 0)\n",
    ");\n",
    "CREATE TABLE target (\n",
    "    target_id   VARCHAR PRIMARY KEY,\n",
    "    name        VARCHAR NOT NULL,\n",
    "    organism    VARCHAR NOT NULL\n",
    ");\n",
    "CREATE TABLE measurement (\n",
    "    measurement_id INTEGER PRIMARY KEY,\n",
    "    batch_id    INTEGER NOT NULL REFERENCES batch (batch_id),\n",
    "    target_id   VARCHAR NOT NULL REFERENCES target (target_id),\n",
    "    ic50_nm     DOUBLE NOT NULL CHECK (ic50_nm > 0),\n",
    "    measured_on DATE NOT NULL\n",
    ");\n",
    "\"\"\")\n",
    "print([row[0] for row in db.sql(\"SHOW TABLES\").fetchall()])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`DECIMAL(7, 2)` is a number with up to 7 digits, 2 after the point, stored exactly (unlike a\n",
    "floating-point `DOUBLE`, which is right for measurements but not for money). The `compound` table\n",
    "has two extra columns, `source` and `loaded_on`, which record where each row came from and when it\n",
    "was loaded: **provenance**, which section 5 comes back to.\n",
    "\n",
    "To load the pandas tables, `db.register` lets SQL see a DataFrame under a name, and\n",
    "`INSERT INTO ... SELECT ...` copies its rows in. Tables are filled in order, so that every row a\n",
    "foreign key points to already exists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO loaded 3 rows into supplier\n",
      "INFO loaded 1,500 rows into compound\n",
      "INFO loaded 2,998 rows into batch\n",
      "INFO loaded 2 rows into target\n",
      "INFO loaded 4,000 rows into measurement\n"
     ]
    }
   ],
   "source": [
    "compounds[\"source\"] = SOURCE\n",
    "compounds[\"loaded_on\"] = pd.Timestamp(LOADED_ON)\n",
    "for name, frame in [(\"supplier\", suppliers), (\"compound\", compounds), (\"batch\", batches),\n",
    "                    (\"target\", targets), (\"measurement\", measurements)]:  # fmt: skip\n",
    "    db.register(\"incoming\", frame)\n",
    "    columns = \", \".join(c[0] for c in db.sql(f\"DESCRIBE {name}\").fetchall())\n",
    "    db.execute(f\"INSERT INTO {name} SELECT {columns} FROM incoming\")\n",
    "    db.unregister(\"incoming\")\n",
    "    count = db.execute(f\"SELECT count(*) FROM {name}\").fetchall()[0][0]\n",
    "    log.info(\"loaded %s rows into %s\", f\"{count:,}\", name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the rules at work. Each of these inserts breaks one, and the database refuses it with an error\n",
    "that names the rule, instead of quietly storing a wrong value. `try` runs the code and `except`\n",
    "catches the error so we can print it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "a negative price: refused, ConstraintException\n",
      "a batch of a compound that does not exist: refused, ConstraintException\n",
      "the same compound registered twice: refused, ConstraintException\n",
      "a measurement with no IC50: refused, ConstraintException\n",
      "a fourth supplier called Vendor B: refused, ConstraintException\n"
     ]
    }
   ],
   "source": [
    "bad_rows = {\n",
    "    \"a negative price\": \"INSERT INTO batch VALUES (99001, 1, 1, -5.00, 10)\",\n",
    "    \"a batch of a compound that does not exist\": \"INSERT INTO batch VALUES (99002, 99999, 1, 20.00, 10)\",\n",
    "    \"the same compound registered twice\": f\"INSERT INTO compound VALUES (99003, '{compounds.inchikey[0]}', 'C', 16.04, 'typed by hand', DATE '2026-11-24')\",\n",
    "    \"a measurement with no IC50\": \"INSERT INTO measurement VALUES (99004, 1, 'CHEMBL203', NULL, DATE '2026-11-24')\",\n",
    "    \"a fourth supplier called Vendor B\": \"INSERT INTO supplier VALUES (4, 'Vendor B', 'Germany')\",\n",
    "}  # fmt: skip\n",
    "for problem, statement in bad_rows.items():\n",
    "    try:\n",
    "        db.execute(statement)\n",
    "        print(f\"{problem}: stored (no rule stopped it)\")\n",
    "    except duckdb.Error as error:\n",
    "        print(f\"{problem}: refused, {type(error).__name__}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every one of these mistakes would have gone into the spreadsheet without a word. The rules are part\n",
    "of the database, so they hold for every program and every person that writes to it, not only for\n",
    "code that remembers to check.\n",
    "\n",
    "## 4. Asking questions in SQL\n",
    "\n",
    "A question in SQL is a `SELECT` statement. It reads almost like English:\n",
    "\n",
    "- `SELECT` the columns you want (or calculations on them);\n",
    "- `FROM` a table;\n",
    "- `WHERE` a condition, to keep only some rows;\n",
    "- `ORDER BY` a column, to sort (`DESC` for largest first), and `LIMIT` to keep the first few.\n",
    "\n",
    "`db.sql(...)` runs the question and `.df()` returns the answer as a pandas table. The five cheapest\n",
    "batches:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " batch_id  compound_id  supplier_id  price_usd\n",
      "      484          253            2      15.17\n",
      "     2130         1070            3      15.48\n",
      "      567          293            2      15.49\n",
      "     2034         1023            1      15.50\n",
      "     1668          848            1      15.85\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT batch_id, compound_id, supplier_id, price_usd\n",
    "    FROM batch\n",
    "    WHERE amount_mg >= 25\n",
    "    ORDER BY price_usd\n",
    "    LIMIT 5\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Numbers alone are not much use: we want the supplier's name and the compound's structure. A\n",
    "**join** puts tables back together through their keys, the reverse of what normalisation did.\n",
    "`JOIN supplier USING (supplier_id)` matches each batch with the supplier row that has the same\n",
    "`supplier_id`. A **GROUP BY** then summarises: one row per group, with `count(*)` (how many rows),\n",
    "`avg(...)` and `min(...)`. Here, for each supplier, how many batches it sells and their average\n",
    "price:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "supplier  batches  mean_price_usd\n",
      "Vendor A     1009          213.38\n",
      "Vendor B     1015          208.53\n",
      "Vendor C      974          207.34\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT supplier.name AS supplier, count(*) AS batches, round(avg(price_usd), 2) AS mean_price_usd\n",
    "    FROM batch\n",
    "    JOIN supplier USING (supplier_id)\n",
    "    GROUP BY supplier.name\n",
    "    ORDER BY supplier.name\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Questions can join several tables at once. Which compounds under 300 g/mol reached a pIC50 of 7 or\n",
    "more on EGFR, and from which supplier? The pIC50 is calculated from the stored IC50 in the query\n",
    "(`log10` is the logarithm to base 10), so it can never disagree with it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "                   inchikey     mw supplier  pic50\n",
      "AZDAVSMQFFWVNS-UHFFFAOYSA-N 297.27 Vendor A   8.62\n",
      "BSSOCPROESAAQU-UHFFFAOYSA-N 266.70 Vendor A   8.37\n",
      "WAFIQPKIAIXJQX-UHFFFAOYSA-N 207.20 Vendor C   7.87\n",
      "NZTLMGBTCUSIAC-UHFFFAOYSA-N 298.35 Vendor A   7.69\n",
      "WKKLMVGLONEUTL-UHFFFAOYSA-N 290.28 Vendor B   7.63\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT compound.inchikey, compound.mw, supplier.name AS supplier,\n",
    "           round(9 - log10(measurement.ic50_nm), 2) AS pic50\n",
    "    FROM measurement\n",
    "    JOIN batch    USING (batch_id)\n",
    "    JOIN compound USING (compound_id)\n",
    "    JOIN supplier USING (supplier_id)\n",
    "    JOIN target   USING (target_id)\n",
    "    WHERE target.name = 'EGFR' AND compound.mw < 300 AND 9 - log10(measurement.ic50_nm) >= 7\n",
    "    ORDER BY pic50 DESC\n",
    "    LIMIT 5\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Correcting a supplier is now one change in one row, and every question sees it at once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[('Vendor A', 'Ireland'), ('Vendor B', 'Germany'), ('Vendor C', 'India')]\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"UPDATE supplier SET country = 'Ireland' WHERE name = 'Vendor A'\")\n",
    "print(db.sql(\"SELECT name, country FROM supplier ORDER BY supplier_id\").fetchall())\n",
    "db.execute(\"UPDATE supplier SET country = 'United Kingdom' WHERE name = 'Vendor A'\")  # put it back"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Describing the database: metadata\n",
    "\n",
    "A table called `measurement` with a column `ic50_nm` is clear to us today. It will not be clear to\n",
    "a colleague in a year, or to a program that reads the database. Data that describes data is called\n",
    "**metadata**, and three kinds are worth keeping in the database itself.\n",
    "\n",
    "**Comments on tables and columns.** `COMMENT ON` attaches a description that stays with the table:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "db.execute(\"\"\"\n",
    "COMMENT ON TABLE measurement IS 'One assay result: one batch tested on one target.';\n",
    "COMMENT ON COLUMN measurement.ic50_nm IS 'Half-maximal inhibitory concentration, nanomolar.';\n",
    "COMMENT ON COLUMN measurement.measured_on IS 'Date the assay was run (not the date it was loaded).';\n",
    "COMMENT ON TABLE compound IS 'One row per distinct structure, identified by its standard InChIKey.';\n",
    "COMMENT ON COLUMN compound.smiles IS 'Canonical SMILES from RDKit.';\n",
    "COMMENT ON COLUMN compound.mw IS 'Average molecular weight, g/mol, from RDKit.';\n",
    "COMMENT ON COLUMN compound.source IS 'Where the row came from.';\n",
    "COMMENT ON COLUMN compound.loaded_on IS 'Date the row was loaded.';\n",
    "COMMENT ON COLUMN batch.price_usd IS 'Catalogue price of the batch, US dollars.';\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**A data dictionary**: a table that lists every column with its type, its rules and its meaning.\n",
    "The database already knows all of it, so it can be produced by a query rather than written by hand\n",
    "and left to go stale. DuckDB keeps it in `duckdb_columns()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "      table         column         type     rule                                              comment\n",
      "   compound    compound_id      INTEGER required                                  (not described yet)\n",
      "   compound       inchikey      VARCHAR required                                  (not described yet)\n",
      "   compound         smiles      VARCHAR required                         Canonical SMILES from RDKit.\n",
      "   compound             mw DECIMAL(7,2) required         Average molecular weight, g/mol, from RDKit.\n",
      "   compound         source      VARCHAR required                             Where the row came from.\n",
      "   compound      loaded_on         DATE required                             Date the row was loaded.\n",
      "measurement measurement_id      INTEGER required                                  (not described yet)\n",
      "measurement       batch_id      INTEGER required                                  (not described yet)\n",
      "measurement      target_id      VARCHAR required                                  (not described yet)\n",
      "measurement        ic50_nm       DOUBLE required    Half-maximal inhibitory concentration, nanomolar.\n",
      "measurement    measured_on         DATE required Date the assay was run (not the date it was loaded).\n"
     ]
    }
   ],
   "source": [
    "dictionary = db.sql(\"\"\"\n",
    "    SELECT table_name AS \"table\", column_name AS \"column\", data_type AS type,\n",
    "           CASE WHEN is_nullable THEN '' ELSE 'required' END AS rule,\n",
    "           coalesce(comment, '(not described yet)') AS comment\n",
    "    FROM duckdb_columns()\n",
    "    WHERE table_name IN ('compound', 'measurement')\n",
    "    ORDER BY table_name, column_index\n",
    "\"\"\").df()\n",
    "print(dictionary.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`coalesce(a, b)` gives `a`, or `b` when `a` is missing, so the columns nobody has described yet\n",
    "say so: the dictionary shows the gaps too. Written\n",
    "out as a file or a web page, it is what a new colleague reads first.\n",
    "\n",
    "**Provenance columns**: `source` and `loaded_on` on every compound record where it came from and\n",
    "when. When a supplier's file later turns out to be wrong, a query finds every row it brought in.\n",
    "Module 13 takes this further, recording the exact versions of code, rules and data behind every\n",
    "result.\n",
    "\n",
    "**Where a data contract fits.** The schema says what the *database* will accept. A **data\n",
    "contract** is an agreement with the people who *send* the data: which columns a supplier's file\n",
    "has, in which units, how often it arrives, and what happens when it breaks the agreement. The\n",
    "contract is checked on the incoming file, before loading; the schema is the last line of defence\n",
    "inside the database. [Module 12](../12-validating-data/) writes and checks one.\n",
    "\n",
    "## 6. Recording versus analysing: a star schema\n",
    "\n",
    "The normalised model is right for **recording** data: each fact once, every change in one place.\n",
    "For **analysing** it, five joins in every question is a lot to ask of a colleague with a\n",
    "spreadsheet habit. Data warehouses therefore reshape the same data into a **star schema**:\n",
    "\n",
    "- one **fact table** in the middle, one row per event we count or measure (a measurement), holding\n",
    "  the numbers (pIC50, price) and keys;\n",
    "- **dimension tables** around it, describing the who, what and when (compound, supplier, target,\n",
    "  date), with everything about each one in a single table.\n",
    "\n",
    "![A star schema: the fact table fact_measurement in the middle, with pic50 and price_usd and four keys, joined to four dimension tables around it: dim_compound, dim_supplier, dim_target and dim_date](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/04-databases-and-schemas/figures/star-schema.svg)\n",
    "\n",
    "We build it as **views**: saved questions that look like tables but are calculated from the\n",
    "normalised tables each time they are read, so the two can never disagree. `CREATE VIEW name AS\n",
    "SELECT ...` saves one:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "               target supplier  results  mean_pic50\n",
      "Carbonic anhydrase II Vendor A      704        5.48\n",
      "Carbonic anhydrase II Vendor B      667        5.49\n",
      "Carbonic anhydrase II Vendor C      614        5.10\n",
      "                 EGFR Vendor A      666        6.32\n",
      "                 EGFR Vendor B      664        6.33\n",
      "                 EGFR Vendor C      685        5.93\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "CREATE VIEW fact_measurement AS\n",
    "    SELECT m.measurement_id, b.compound_id, b.supplier_id, m.target_id, m.measured_on AS date_key,\n",
    "           round(9 - log10(m.ic50_nm), 2) AS pic50, b.price_usd\n",
    "    FROM measurement m JOIN batch b USING (batch_id);\n",
    "CREATE VIEW dim_compound AS\n",
    "    SELECT compound_id, inchikey, smiles, mw,\n",
    "           CASE WHEN mw < 300 THEN 'under 300' WHEN mw < 400 THEN '300-400' ELSE '400 and over' END AS mw_band\n",
    "    FROM compound;\n",
    "CREATE VIEW dim_supplier AS SELECT supplier_id, name AS supplier, country FROM supplier;\n",
    "CREATE VIEW dim_target AS SELECT target_id, name AS target, organism FROM target;\n",
    "CREATE VIEW dim_date AS\n",
    "    SELECT DISTINCT measured_on AS date_key, year(measured_on) AS year, quarter(measured_on) AS quarter\n",
    "    FROM measurement;\n",
    "\"\"\")\n",
    "print(db.sql(\"\"\"\n",
    "    SELECT t.target, s.supplier, count(*) AS results, round(avg(f.pic50), 2) AS mean_pic50\n",
    "    FROM fact_measurement f\n",
    "    JOIN dim_target t USING (target_id)\n",
    "    JOIN dim_supplier s USING (supplier_id)\n",
    "    GROUP BY t.target, s.supplier\n",
    "    ORDER BY t.target, s.supplier\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every question now has the same shape, the fact table joined to the dimensions it needs, and this\n",
    "one finds something: Vendor C's batches read about 0.4 log units lower on both targets. In real\n",
    "data that is the cue to check the purity of that supplier's batches before trusting any of their\n",
    "results. (We made the data that way, to show what such a pattern looks like.)\n",
    "\n",
    "DuckDB is an **analytical** database: it stores each column separately and works on whole columns\n",
    "at a time, so summaries over millions of rows take a fraction of a second. Module 8 uses it to query\n",
    "a library of millions of molecules spread over Parquet files. We close this database here: the file\n",
    "`work/chem.duckdb` keeps everything, and `duckdb.connect` would open it again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "db.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. A chemical database: PostgreSQL with the RDKit cartridge\n",
    "\n",
    "DuckDB is one file used by one program at a time. A group's compound database has different needs:\n",
    "many people and programs reading and writing at once, accounts with different permissions, and\n",
    "chemistry inside the database. That is the job of a **database server**: a program that runs all\n",
    "the time (here in Docker, on your own computer), which programs connect to over the network.\n",
    "**PostgreSQL** is the most widely used open-source one, and the **RDKit cartridge** is an add-on\n",
    "that gives it a `mol` column type for molecules, chemical searches in SQL, and indexes that make\n",
    "them fast.\n",
    "\n",
    "*This section and the next need PostgreSQL running (see [the database\n",
    "guide](https://monstrous.com.ng/learn/databases/)) and `DATABASE_URL` set in the terminal you\n",
    "started Python or Jupyter from. In Colab their blocks do nothing; read them and their outputs here.*\n",
    "\n",
    "`psycopg.connect(DATABASE_URL)` opens a connection; the address comes from the environment, so it\n",
    "is not written in the code (section 8 explains why). `autocommit=True` makes each statement take\n",
    "effect at once. We work inside our own **schema**, `module4`: in PostgreSQL a schema is also a named\n",
    "area of the database, like a folder for tables, which lets the lesson empty its own area at the\n",
    "start without touching anything else. `SET search_path` makes it the place our table names refer\n",
    "to. Names of schemas, tables and accounts cannot be passed to SQL as ordinary values, so psycopg's\n",
    "`sql.SQL(...).format(sql.Identifier(...))` puts them into the statement safely, quoted.\n",
    "\n",
    "The compound table is the same as in DuckDB with one addition: a column of type `mol`, holding the\n",
    "molecule itself. **COPY** is PostgreSQL's fast way to load many rows: psycopg's `cur.copy` streams\n",
    "them in. We load the SMILES first, then let the cartridge build every molecule from its SMILES with\n",
    "`mol_from_smiles`, and only then make the column required:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO loaded 1,500 compounds into PostgreSQL, 1,500 with a molecule\n"
     ]
    }
   ],
   "source": [
    "%%needs postgres\n",
    "# needs: postgres\n",
    "pg = psycopg.connect(DATABASE_URL, autocommit=True)\n",
    "schema, analyst = sql.Identifier(PG_SCHEMA), sql.Identifier(ANALYST)\n",
    "pg.execute(sql.SQL(\"DROP SCHEMA IF EXISTS {} CASCADE\").format(schema))  # empty the lesson's area\n",
    "pg.execute(sql.SQL(\"DROP ROLE IF EXISTS {}\").format(analyst))  # and remove section 8's account\n",
    "pg.execute(sql.SQL(\"CREATE SCHEMA {}\").format(schema))\n",
    "pg.execute(sql.SQL(\"SET search_path TO {}, public\").format(schema))\n",
    "pg.execute(\"\"\"\n",
    "CREATE TABLE compound (\n",
    "    compound_id integer PRIMARY KEY,\n",
    "    inchikey    text NOT NULL UNIQUE CHECK (length(inchikey) = 27),\n",
    "    smiles      text NOT NULL,\n",
    "    mw          numeric(7, 2) NOT NULL CHECK (mw > 0),\n",
    "    mol         mol\n",
    ")\"\"\")\n",
    "with pg.cursor() as cur, cur.copy(\"COPY compound (compound_id, inchikey, smiles, mw) FROM STDIN\") as copy:\n",
    "    for row in compounds.itertuples(index=False):\n",
    "        copy.write_row((int(row.compound_id), row.inchikey, row.smiles, float(row.mw)))\n",
    "pg.execute(\"UPDATE compound SET mol = mol_from_smiles(smiles::cstring)\")\n",
    "pg.execute(\"ALTER TABLE compound ALTER COLUMN mol SET NOT NULL\")\n",
    "pg.execute(\"ANALYZE compound\")  # let PostgreSQL count what is in the table, for planning (below)\n",
    "total, with_mol = pg.execute(\"SELECT count(*), count(mol) FROM compound\").fetchone()\n",
    "log.info(\"loaded %s compounds into PostgreSQL, %s with a molecule\", f\"{total:,}\", f\"{with_mol:,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`smiles::cstring` converts the text to the kind of string the cartridge's function expects; `::`\n",
    "is SQL's way of converting a value to another type.)\n",
    "\n",
    "### Substructure search, and the ester trap\n",
    "\n",
    "The cartridge's `@>` means \"contains\": `mol @> pattern` is true when the molecule contains the\n",
    "pattern. The pattern can be written as a molecule (`'C(=O)O'::mol`) or as SMARTS\n",
    "(`'...'::qmol`, a query molecule). [Module 2](../02-text-patterns-and-numbers/) showed why the\n",
    "difference matters: as a molecule, `C(=O)O` says nothing about what is attached to the last oxygen,\n",
    "so it matches esters as well as acids. The SMARTS `[CX3](=O)[OX2H1]` asks for an oxygen with\n",
    "exactly one hydrogen. The same three molecules as in Module 2, now searched inside the database\n",
    "(`%s` marks a value psycopg sends separately from the SQL, the safe way to pass values in):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "acetic acid        C(=O)O as a molecule: True   acid SMARTS: True\n",
      "methyl salicylate  C(=O)O as a molecule: True   acid SMARTS: False\n",
      "ibuprofen          C(=O)O as a molecule: True   acid SMARTS: True\n",
      "in the library: 185 compounds contain C(=O)O as a molecule; 0 are acids\n"
     ]
    }
   ],
   "source": [
    "%%needs postgres\n",
    "# needs: postgres\n",
    "examples = {\n",
    "    \"acetic acid\": \"CC(=O)O\",\n",
    "    \"methyl salicylate\": \"COC(=O)c1ccccc1O\",\n",
    "    \"ibuprofen\": \"CC(C)Cc1ccc(cc1)C(C)C(=O)O\",\n",
    "}\n",
    "for name, smiles in examples.items():\n",
    "    as_molecule, as_smarts = pg.execute(\n",
    "        \"SELECT %s::mol @> 'C(=O)O'::mol, %s::mol @> %s::qmol\", (smiles, smiles, ACID_SMARTS)\n",
    "    ).fetchone()\n",
    "    print(f\"{name:18} C(=O)O as a molecule: {as_molecule}   acid SMARTS: {as_smarts}\")\n",
    "plain, acids = pg.execute(\n",
    "    \"SELECT count(*) FILTER (WHERE mol @> 'C(=O)O'::mol), count(*) FILTER (WHERE mol @> %s::qmol)\"\n",
    "    \" FROM compound\", (ACID_SMARTS,)\n",
    ").fetchone()  # fmt: skip\n",
    "print(f\"in the library: {plain} compounds contain C(=O)O as a molecule; {acids} are acids\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In our library the difference is total: 185 compounds match the loose pattern and not one of them\n",
    "is an acid. A colleague who asked for \"the acids\" and was sent the loose search would get 185 wrong\n",
    "answers. Write substructure queries as SMARTS, and test them on molecules you know.\n",
    "\n",
    "### Similarity search\n",
    "\n",
    "`morganbv_fp(mol)` makes a Morgan fingerprint (the bits of Module 2) inside the database, and\n",
    "`tanimoto_sml(a, b)` compares two fingerprints: 1 means identical bits, 0 nothing in common. The\n",
    "five compounds most similar to compound 1 (`round(..., 3)` keeps three decimals; `::numeric` lets\n",
    "PostgreSQL round it):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "query: NCc1ccc(CNC(=O)c2ccc(C(F)(F)F)cc2)cc1\n",
      "    1  1.000  NCc1ccc(CNC(=O)c2ccc(C(F)(F)F)cc2)cc1\n",
      "  698  0.368  NCNC(=O)C(COC(F)(F)F)NC(=O)c1cc(CN)cc(C(F)(F)F)c1\n",
      "  147  0.345  CNC(=O)C(CC(=O)OC)NC(=O)c1cc(CN)cc(C(F)(F)F)c1\n",
      "  203  0.327  NCc1cc(Br)cc(C(=O)NC(CF)C(=O)NC(F)(F)F)c1\n",
      "  751  0.323  NCc1cc(C(=O)NC(Cc2cn[nH]c2)C(=O)Nc2ccc(F)cc2)cc(C(F)(F)F)c1\n"
     ]
    }
   ],
   "source": [
    "%%needs postgres\n",
    "# needs: postgres\n",
    "query = compounds.smiles[0]\n",
    "print(\"query:\", query)\n",
    "for compound_id, smiles, similarity in pg.execute(\"\"\"\n",
    "    SELECT compound_id, smiles,\n",
    "           round(tanimoto_sml(morganbv_fp(mol), morganbv_fp(%s::mol))::numeric, 3) AS similarity\n",
    "    FROM compound\n",
    "    ORDER BY similarity DESC, compound_id\n",
    "    LIMIT 5\"\"\", (query,)).fetchall():  # fmt: skip\n",
    "    print(f\"{compound_id:5}  {similarity}  {smiles}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first hit is the query itself, at 1.000. The others share about a third of its fingerprint\n",
    "bits: this library has no close analogue of compound 1, and the nearest compounds are the ones\n",
    "that share its trifluoromethyl-benzamide and aminomethyl pieces. Values above about 0.6 usually\n",
    "mean a close analogue. A real\n",
    "database would store the fingerprints in their own column, made once when the molecule is loaded,\n",
    "rather than recalculating them for every question.\n",
    "\n",
    "### Indexes, and how to see one at work\n",
    "\n",
    "To answer \"which molecules contain this pattern?\", PostgreSQL could test every molecule in turn.\n",
    "An **index** lets it skip most of them: the cartridge's index (of the kind PostgreSQL calls\n",
    "**GiST**) stores a summary of each molecule, so the database tests in full only the molecules whose\n",
    "summary could match. `EXPLAIN` shows the database's **query plan**, how it intends to answer a\n",
    "question, without running it. Before and after making the index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "without an index: Seq Scan on compound\n",
      "with the index:   Bitmap Heap Scan on compound\n"
     ]
    }
   ],
   "source": [
    "%%needs postgres\n",
    "# needs: postgres\n",
    "search = sql.SQL(\"SELECT compound_id FROM compound WHERE mol @> {}::qmol\").format(sql.Literal(ACID_SMARTS))\n",
    "\n",
    "\n",
    "def plan(query: sql.Composable) -> str:\n",
    "    \"\"\"The first line of PostgreSQL's plan for a query: how it will find the rows.\"\"\"\n",
    "    return pg.execute(sql.SQL(\"EXPLAIN \") + query).fetchall()[0][0].split(\"  (\")[0]\n",
    "\n",
    "\n",
    "print(\"without an index:\", plan(search))\n",
    "pg.execute(\"CREATE INDEX compound_mol ON compound USING gist (mol)\")\n",
    "pg.execute(\"ANALYZE compound\")\n",
    "print(\"with the index:  \", plan(search))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A **Seq Scan** (sequential scan) reads every row. A **Bitmap Heap Scan** first asks the index which\n",
    "rows could match, then reads only those. On 1,500 molecules both take a few milliseconds; on two\n",
    "million the index is the difference between a second and a minute. Indexes are not free: each one\n",
    "takes space and slows every insert a little, because it must be updated too. Make them for the\n",
    "searches people really run, and check with `EXPLAIN` that they are used.\n",
    "\n",
    "## 8. Safe access: accounts, rights and passwords\n",
    "\n",
    "Our lesson logs in as `learn`, the account that created the tables and can do anything to them. A\n",
    "colleague who only needs to search should not be able to delete the compound table by mistake.\n",
    "PostgreSQL controls this with **roles** (accounts) and **privileges** (what each role may do):\n",
    "`CREATE ROLE ... LOGIN PASSWORD ...` makes an account, and `GRANT` gives it rights. We give the\n",
    "analyst the right to read our tables, and nothing else:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "the analyst can read: 1,500 compounds\n",
      "the analyst cannot delete: permission denied for table compound\n"
     ]
    }
   ],
   "source": [
    "%%needs postgres\n",
    "# needs: postgres\n",
    "pg.execute(sql.SQL(\"CREATE ROLE {} LOGIN PASSWORD {}\").format(analyst, sql.Literal(ANALYST_PASSWORD)))\n",
    "pg.execute(sql.SQL(\"GRANT USAGE ON SCHEMA {} TO {}\").format(schema, analyst))\n",
    "pg.execute(sql.SQL(\"GRANT SELECT ON ALL TABLES IN SCHEMA {} TO {}\").format(schema, analyst))\n",
    "\n",
    "analyst_url = make_conninfo(DATABASE_URL, user=ANALYST, password=ANALYST_PASSWORD)\n",
    "with psycopg.connect(analyst_url, autocommit=True) as colleague:\n",
    "    colleague.execute(sql.SQL(\"SET search_path TO {}, public\").format(schema))\n",
    "    count = colleague.execute(\"SELECT count(*) FROM compound\").fetchone()[0]\n",
    "    print(f\"the analyst can read: {count:,} compounds\")\n",
    "    try:\n",
    "        colleague.execute(\"DELETE FROM compound\")\n",
    "    except psycopg.errors.InsufficientPrivilege as error:\n",
    "        print(\"the analyst cannot delete:\", str(error).strip())\n",
    "pg.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`make_conninfo` builds the analyst's connection details from ours, with the user name and password\n",
    "changed. This is the **principle of least privilege**: every account gets the rights its job needs\n",
    "and no more. A loading program gets `INSERT`; a dashboard gets `SELECT`; only the people who change\n",
    "the tables' design get to create and drop them.\n",
    "\n",
    "**Passwords never go in code.** Code is copied, shared, emailed and pushed to GitHub, and a\n",
    "password written in it goes wherever the code goes: once it is in a repository's history, assume it\n",
    "is public. The habits that prevent this:\n",
    "\n",
    "- read passwords and addresses from **environment variables**, as this lesson does with\n",
    "  `DATABASE_URL` and `ANALYST_PASSWORD`;\n",
    "- on your own computer, keep them in a file called `.env` (one `NAME=value` per line), loaded with\n",
    "  the small package python-dotenv, and list `.env` in the repository's `.gitignore` file so Git\n",
    "  never stores it. This course does exactly that: the repository holds `.env.example`, with the\n",
    "  names and placeholder passwords, and each learner copies it to `.env` and chooses their own;\n",
    "- never print or log a connection string: [Module 14](../14-monitoring-pipelines/) removes\n",
    "  passwords from logs automatically;\n",
    "- never open a database to the network: the course's `compose.yml` lets the databases be reached\n",
    "  from your own computer only.\n",
    "\n",
    "Even the passwords for these practice databases, which nobody else can reach, live in `.env` and\n",
    "not in the code: good habits are cheapest to learn on something that does not matter yet. A\n",
    "database on a server gets long random passwords, kept by whoever runs it, and changed if they ever\n",
    "leak.\n",
    "\n",
    "### Values from outside: SQL injection\n",
    "\n",
    "Every program that puts a value from outside into SQL (a search box, a form, a file name, a row of\n",
    "a supplier's file) must do it one way only: as a **parameter**, sent to the database separately from\n",
    "the SQL. This lesson has done so all along: psycopg's `%s` in section 7, and the way names of\n",
    "schemas and accounts are quoted with `sql.Identifier`. Here is why, on the DuckDB database of\n",
    "sections 3 to 6, so it runs anywhere.\n",
    "\n",
    "Imagine a small search page for the lab, where a chemist types a supplier's name. The page's\n",
    "connection is **read-only** (`read_only=True`): a search never needs to change anything, so by the\n",
    "principle of least privilege above it should not be able to. The search below is written the wrong\n",
    "way, by pasting the text into the SQL with an f-string:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[('Vendor A', 'United Kingdom')]\n",
      "[('Vendor A', 'United Kingdom'), ('Vendor B', 'Germany'), ('Vendor C', 'India')]\n",
      "[('AAPXMIQKYKFYCQ-UHFFFAOYSA-N', 'CCONC(=O)C(CC)NC(=O)c1cc(C)cc(N(C)C)c1'), ('AAPYJNIARROXBV-UHFFFAOYSA-N', 'CS(=O)(=O)c1cc(C(=O)NC(CC(N)=O)C(=O)Nc2ccc(F)cc2)cc(-c2ccc(F)cc2)c1')]\n",
      "refused: Invalid Input Error: Cannot execute statement of type \"DROP\" on database \"chem\" which is attached in read-only mode!\n"
     ]
    }
   ],
   "source": [
    "shop = duckdb.connect(DUCKDB_FILE, read_only=True)  # the search page's connection: reading only\n",
    "\n",
    "\n",
    "def find_supplier_unsafe(name: str) -> list:\n",
    "    \"\"\"A search written the WRONG way: the user's text is pasted into the SQL.\"\"\"\n",
    "    return shop.execute(f\"SELECT name, country FROM supplier WHERE name = '{name}'\").fetchall()\n",
    "\n",
    "\n",
    "print(find_supplier_unsafe(\"Vendor A\"))\n",
    "print(find_supplier_unsafe(\"nobody' OR '1'='1\"))\n",
    "print(find_supplier_unsafe(\"nobody' UNION SELECT inchikey, smiles FROM compound ORDER BY 1 LIMIT 2 --\"))\n",
    "try:\n",
    "    find_supplier_unsafe(\"nobody'; DROP TABLE measurement; --\")\n",
    "except duckdb.Error as error:\n",
    "    print(\"refused:\", str(error).splitlines()[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first search does what it should. The other three are **SQL injection**: text written so that,\n",
    "once pasted in, it changes what the SQL means.\n",
    "\n",
    "- `nobody' OR '1'='1` closes the quote early and adds a condition that is always true, so the search\n",
    "  returns every supplier. On a login page the same trick can log someone in without a password.\n",
    "- `nobody' UNION SELECT ... --` closes the quote and adds a second query: `UNION` joins its rows to\n",
    "  the first query's, so the search page now shows compounds, data it was never meant to give out.\n",
    "  `--` starts an SQL comment, which hides the stray quote at the end.\n",
    "- `nobody'; DROP TABLE measurement; --` adds a second statement, to delete a table. The read-only\n",
    "  connection refused it, which is least privilege doing its job: it limits the damage, but it did\n",
    "  not stop the first two attacks, which only read.\n",
    "\n",
    "The cure is a parameter. `?` marks where a value goes (psycopg writes `%s`), and the value is passed\n",
    "separately, as a list. The database receives the SQL and the value apart, so the value can only\n",
    "ever be a value: a name containing quotes is just an odd name, which matches no supplier."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "'Vendor A'                               -> [('Vendor A', 'United Kingdom')]\n",
      "\"nobody' OR '1'='1\"                      -> []\n",
      "\"nobody'; DROP TABLE measurement; --\"    -> []\n"
     ]
    }
   ],
   "source": [
    "def find_supplier(name: str) -> list:\n",
    "    \"\"\"The same search, written safely: the name is passed as a parameter, never as SQL.\"\"\"\n",
    "    return shop.execute(\"SELECT name, country FROM supplier WHERE name = ?\", [name]).fetchall()\n",
    "\n",
    "\n",
    "for attempt in [\"Vendor A\", \"nobody' OR '1'='1\", \"nobody'; DROP TABLE measurement; --\"]:\n",
    "    print(f\"{attempt!r:40} -> {find_supplier(attempt)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Parameters carry values only. The *names* of tables and columns cannot be parameters, so when a\n",
    "user chooses one (a column to sort by, say), check it against a list of names you allow, and refuse\n",
    "anything else. In PostgreSQL, psycopg's `sql.Identifier` quotes a name safely, as section 7 does for\n",
    "the schema's name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['Vendor B', 'Vendor C', 'Vendor A']\n",
      "refused: cannot sort by 'name; DROP TABLE measurement'\n"
     ]
    }
   ],
   "source": [
    "SORTABLE = {\"name\", \"country\"}  # the columns the search page may sort by\n",
    "\n",
    "\n",
    "def suppliers_sorted_by(column: str) -> list:\n",
    "    \"\"\"Suppliers sorted by a column the user chose, checked against the allowed names first.\"\"\"\n",
    "    if column not in SORTABLE:\n",
    "        raise ValueError(f\"cannot sort by {column!r}\")\n",
    "    return [row[0] for row in shop.execute(f\"SELECT name FROM supplier ORDER BY {column}\").fetchall()]\n",
    "\n",
    "\n",
    "print(suppliers_sorted_by(\"country\"))\n",
    "try:\n",
    "    suppliers_sorted_by(\"name; DROP TABLE measurement\")\n",
    "except ValueError as error:\n",
    "    print(\"refused:\", error)\n",
    "shop.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You will often read that an **ORM** (object-relational mapper, such as SQLAlchemy or Django's\n",
    "models, which let code treat tables as Python classes) prevents SQL injection. It does, for the\n",
    "queries it writes, and for exactly this reason: an ORM always sends values as parameters. But every\n",
    "ORM also lets you write raw SQL (SQLAlchemy's `text()`, for example), and raw SQL built with an\n",
    "f-string is as open to injection there as it is here. The rule is the same with or without one:\n",
    "values as parameters, names checked against a list, and no text from outside ever pasted into SQL.\n",
    "\n",
    "## 9. Which database for which job\n",
    "\n",
    "What this module built, and when to reach for each:\n",
    "\n",
    "- **Planning first.** Whatever the database, write down the things you store, how they link, and\n",
    "  the rules each value follows, and draw the diagram before creating tables. Changing a plan is\n",
    "  cheap; changing a database full of data is not ([Module 13](../13-versioning-everything/) shows\n",
    "  how it is done safely).\n",
    "- **A relational database** (PostgreSQL) for the records a group shares and changes: compounds,\n",
    "  batches, results. Normalised tables, keys and rules keep them correct; roles keep them safe; the\n",
    "  RDKit cartridge searches them by structure.\n",
    "- **An analytical database** (DuckDB) for questions over many rows, and a star schema to make those\n",
    "  questions simple. It reads Parquet files directly ([Module 8](../08-larger-than-memory/)).\n",
    "- **A graph database** (Neo4j) when the questions are about links many steps deep (Module 5).\n",
    "- **The others** (document, key-value, wide-column, vector) when a specific need outweighs what\n",
    "  they give up: records with fields that vary, very fast lookups, enormous scale, or similarity on\n",
    "  learned embeddings.\n",
    "\n",
    "## Try it yourself\n",
    "\n",
    "The homework is a few questions, answered by running code like the code above: in a new cell at\n",
    "the end of the notebook, or in a script. It is at the end of the lesson's page, and in\n",
    "`homework.md` in the module's folder. The answers are published after the cohort's deadline.\n",
    "\n",
    "## Further reading\n",
    "\n",
    "- Codd, E. F. (1970). A relational model of data for large shared data banks. *Communications of\n",
    "  the ACM*, 13(6), 377-387. <https://doi.org/10.1145/362384.362685>\n",
    "- Kleppmann, M. (2017). *Designing Data-Intensive Applications: The Big Ideas Behind Reliable,\n",
    "  Scalable, and Maintainable Systems*. O'Reilly Media. ISBN 978-1-449-37332-0. Chapter 2 (data\n",
    "  models: relational, document and graph).\n",
    "- Kimball, R. & Ross, M. (2013). *The Data Warehouse Toolkit: The Definitive Guide to Dimensional\n",
    "  Modeling* (3rd ed.). Wiley. ISBN 978-1-118-53080-1.\n",
    "- The RDKit documentation. *The RDKit database cartridge*. <https://www.rdkit.org/docs/Cartridge.html>\n",
    "- The PostgreSQL documentation. *Data definition* (tables, constraints, schemas, privileges).\n",
    "  <https://www.postgresql.org/docs/current/ddl.html>\n",
    "- The DuckDB documentation. *SQL introduction*. <https://duckdb.org/docs/stable/sql/introduction>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
