{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "# Pony ORM: bike-share days and World Bank countries"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "**Two lessons, one notebook.** This notebook follows two lessons of the course, one after the other: part 1, [Tables as Python Objects: A First Look at Pony ORM](https://dvirross.com/courses/intro-data-science/python-orm-pony) (tasks 1 to 8); part 2, [Pony ORM Relations: A Table That Points to Another Table](https://dvirross.com/courses/intro-data-science/python-orm-pony-relations) (tasks 9 to 13). A heading marks the place where each part starts. The tasks are numbered from 1 to 13 without a break, so `check(N)` always belongs to the task N of the part that holds it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "# Part 1: Tables as Python Objects: A First Look at Pony ORM\n",
    "\n",
    "The lesson page of this part: [Tables as Python Objects: A First Look at Pony ORM](https://dvirross.com/courses/intro-data-science/python-orm-pony)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "## Can a program use the rows of a table as ordinary objects?\n",
    "\n",
    "The question is whether a row of a table can be kept in a variable, like any Python object, with its columns read by name, for example `day.rentals`, instead of reading a value from a tuple by its position. To see why that matters, here are two problems of the way we have worked so far.\n",
    "\n",
    "In [SQL from Python](https://dvirross.com/courses/intro-data-science/sql-from-python), the program sent SQL as text and got tuples back. Python does not check the text of a query, so a typo in a column name shows up only when the line runs, as the error `no such column: total_ride`:\n",
    "\n",
    "```python\n",
    "c.execute(\"SELECT observation_date, total_ride FROM daily_ridership\")\n",
    "```\n",
    "\n",
    "A second failure: a column of a tuple is read by its position, such as `row[4]`, so when someone adds a column before `total_rides`, the same line of code will read another column, without reporting an error. The people who rely on the numbers pay for it: the daily bike-share rentals report stops at night or shows another column.\n",
    "\n",
    "An **[ORM](https://dvirross.com/courses/intro-data-science/glossary#orm)** (object-relational mapper) changes the division of work: you describe a table as a Python **[class](https://dvirross.com/courses/intro-data-science/glossary#class)**, each row becomes an **[object](https://dvirross.com/courses/intro-data-science/glossary#object)** of that class, and the ORM writes the SQL for you. This lesson uses **Pony ORM**, a Python library, and works on the bike-share days as before.\n",
    "\n",
    "In Pony you write a query as a **[generator expression](https://dvirross.com/courses/intro-data-science/glossary#generator-expression)**, as in the [lesson on objects and generator expressions](https://dvirross.com/courses/intro-data-science/python-objects-and-generators). It is a Python expression that describes which items to take and under what condition, for example:\n",
    "\n",
    "```python\n",
    "d for d in Day if d.season == 'Summer'\n",
    "```\n",
    "\n",
    "Pony does not run that expression as it stands; it reads its structure and translates it into SQL. It is important to understand what each part of the expression says: what comes before `for` is what to take, what comes after `in` is from where, and the condition after `if` is which items. Each of them becomes a different part of the SQL query."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c005",
   "metadata": {},
   "source": [
    "**How to work:** run the cells from top to bottom, because the cells share their variables. A cell that says `# Your turn` is empty or holds the set-up of the task: write your code there, run it, and run the cell under it, which checks your answer without showing the solution. The notebook with solutions has the solution, the common mistakes and the expected output under every task. A database object and its entities are defined once in each run: if you run the cell that defines `db` or `Day` a second time, Pony stops with an error, so restart the session (in Colab: **Runtime**, then **Restart session**) and run the cells again from the top."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c006",
   "metadata": {},
   "source": [
    "## Setup: install Pony and get the data file\n",
    "\n",
    "No account and no key are needed. The next cell installs Pony, the library of this lesson, if the session does not have it yet (Colab does not include it, and the installation takes a few seconds). The cell after it downloads the small CSV file of the lesson from the public site and saves it next to the notebook (in Colab it appears in the **Files** panel). If the download fails, open the address below in a browser, download the file, and upload it to the **Files** panel of Colab.\n",
    "\n",
    "`https://dvirross.com/materials/courses/intro-data-science/world-bank-more-countries.csv`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c007",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.224678Z",
     "iopub.status.busy": "2026-11-14T21:13:30.224473Z",
     "iopub.status.idle": "2026-11-14T21:13:30.230273Z",
     "shell.execute_reply": "2026-11-14T21:13:30.229270Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pony is ready, version 0.7.20\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    import pony\n",
    "except ImportError:\n",
    "    !pip install -q pony\n",
    "    import pony\n",
    "print('Pony is ready, version', pony.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c008",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.232986Z",
     "iopub.status.busy": "2026-11-14T21:13:30.232793Z",
     "iopub.status.idle": "2026-11-14T21:13:30.241893Z",
     "shell.execute_reply": "2026-11-14T21:13:30.240348Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data file ready: world-bank-more-countries.csv\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import urllib.request\n",
    "\n",
    "FILE_URL = 'https://dvirross.com/materials/courses/intro-data-science/world-bank-more-countries.csv'\n",
    "FILE_PATH = 'world-bank-more-countries.csv'\n",
    "\n",
    "if not os.path.exists(FILE_PATH):\n",
    "    # the site refuses the default user agent of Python, so the request names one\n",
    "    request = urllib.request.Request(FILE_URL, headers={'User-Agent': 'Mozilla/5.0'})\n",
    "    with urllib.request.urlopen(request) as response, open(FILE_PATH, 'wb') as file:\n",
    "        file.write(response.read())\n",
    "print('Data file ready:', FILE_PATH)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "The next cell defines the function `check(task_number)`. After you run the cell of a task, run the cell under it: `check` runs your cell again, collects what it prints, and compares it with the expected output. It tells you whether the output is right, and where it differs if not; it never shows the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c010",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.244854Z",
     "iopub.status.busy": "2026-11-14T21:13:30.244687Z",
     "iopub.status.idle": "2026-11-14T21:13:30.254048Z",
     "shell.execute_reply": "2026-11-14T21:13:30.252780Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast, contextlib, hashlib, io\n",
    "\n",
    "# The expected output of each task, as hashes of its lines (the solutions are not stored here).\n",
    "EXPECTED = {int(k): v for k, v in {\n",
    "    '1': [\n",
    "        '72d0a22ca59f'\n",
    "    ],\n",
    "    '2': [\n",
    "        '2dd29fb6f518',\n",
    "        'e1ae88365d47',\n",
    "        '396a1bf61e9a'\n",
    "    ],\n",
    "    '3': [\n",
    "        '6f42ae6ab479',\n",
    "        '5c558c73b770'\n",
    "    ],\n",
    "    '4': [\n",
    "        '2dd29fb6f518',\n",
    "        'e1ae88365d47',\n",
    "        '396a1bf61e9a'\n",
    "    ],\n",
    "    '5': [\n",
    "        'f5ca38f748a1',\n",
    "        'e7f6c011776e'\n",
    "    ],\n",
    "    '6': [\n",
    "        '1d564088a318',\n",
    "        'e18cad10fc80'\n",
    "    ],\n",
    "    '7': [\n",
    "        '2b2bc2ccad4c',\n",
    "        '51b2762f9f61'\n",
    "    ],\n",
    "    '8': [\n",
    "        '59e1e5985094'\n",
    "    ],\n",
    "    '9': [\n",
    "        'ce5c8dfe2fc5',\n",
    "        'e4c78f5bf10e',\n",
    "        'b701d7030a71',\n",
    "        'f0333be7b81b'\n",
    "    ],\n",
    "    '10': [\n",
    "        'dc289ab8c8fa',\n",
    "        '7b2c7298ef49',\n",
    "        '401cb6939b81',\n",
    "        '7413e6942dbb',\n",
    "        '6cceb9bc987f',\n",
    "        '5e0fdfdc44f9'\n",
    "    ],\n",
    "    '11': [\n",
    "        '8ee58a0b6923',\n",
    "        '770859d608eb'\n",
    "    ],\n",
    "    '12': [\n",
    "        'ee7e860a857f'\n",
    "    ],\n",
    "    '13': [\n",
    "        '809c025ba41f',\n",
    "        'dc937b598926'\n",
    "    ]\n",
    "}.items()}\n",
    "\n",
    "\n",
    "def check(task):\n",
    "    \"\"\"Run the last cell that ran (not a check) again and compare what it prints with the expected output of the task.\"\"\"\n",
    "    if task not in EXPECTED:\n",
    "        print('There is no such task: ', task)\n",
    "        return\n",
    "    cells = [s for s in In[:-1] if s.strip() and not s.lstrip().startswith('check(')]   # In: the cells that ran, kept by IPython\n",
    "    tree = ast.parse(cells[-1] if cells else '')\n",
    "    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None   # a bare last expression counts as printed\n",
    "    out = io.StringIO()\n",
    "    try:\n",
    "        with contextlib.redirect_stdout(out):\n",
    "            exec(compile(tree, '<task>', 'exec'), globals())\n",
    "            if last is not None:\n",
    "                value = eval(compile(ast.Expression(last.value), '<task>', 'eval'), globals())\n",
    "                if value is not None:\n",
    "                    print(repr(value))\n",
    "    except Exception as error:\n",
    "        print('The cell raised an error:', type(error).__name__ + ':', error)\n",
    "        return\n",
    "    got = [hashlib.sha256(line.rstrip().encode()).hexdigest()[:12] for line in out.getvalue().rstrip().splitlines()]\n",
    "    want = EXPECTED[task]\n",
    "    if not got:\n",
    "        print('Nothing was printed. Print the answer in the task cell, run it, and run `check` straight after it.')\n",
    "    elif len(got) != len(want):\n",
    "        print('The cell printed {got} line(s) and the task expects {want}. Re-read the task and the hint.'.format(got=len(got), want=len(want)))\n",
    "    elif got != want:\n",
    "        print('Line {k} is different from the expected output. Re-read the task and the hint.'.format(k=next(i for i in range(len(want)) if got[i] != want[i]) + 1))\n",
    "    else:\n",
    "        print('OK: the output is as expected.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c011",
   "metadata": {},
   "source": [
    "## Describe a table as a class\n",
    "\n",
    "The object `db` represents the database that Pony works with. The first line of the next box, `from pony.orm import *`, brings in every name that Pony offers. `Database()` creates `db`, and `db.bind(...)` connects it to SQLite; `':memory:'` is again a temporary database in memory, as in [SQL from Python](https://dvirross.com/courses/intro-data-science/sql-from-python)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c012",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.255674Z",
     "iopub.status.busy": "2026-11-14T21:13:30.255520Z",
     "iopub.status.idle": "2026-11-14T21:13:30.291372Z",
     "shell.execute_reply": "2026-11-14T21:13:30.290175Z"
    }
   },
   "outputs": [],
   "source": [
    "from pony.orm import *\n",
    "\n",
    "db = Database()\n",
    "db.bind(provider='sqlite', filename=':memory:')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c013",
   "metadata": {},
   "source": [
    "A class that stands for a table is called an **[entity](https://dvirross.com/courses/intro-data-science/glossary#entity)**. The class name is written with `(db.Entity)` after it, as in `class Day(db.Entity):`, and the brackets mark it as an entity of the database `db`: Pony stores its objects as rows of a table named `Day`. Each column is a line that names the attribute and its kind: `Required(str)` is a text that must have a value, and `Required(int)` is a whole number that must have a value. After all the entities, `db.generate_mapping(...)` finishes the description of the tables; when `create_tables=True` the method also creates the table in the database, if the table does not exist yet."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c014",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.293712Z",
     "iopub.status.busy": "2026-11-14T21:13:30.293538Z",
     "iopub.status.idle": "2026-11-14T21:13:30.300105Z",
     "shell.execute_reply": "2026-11-14T21:13:30.298756Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Day']\n"
     ]
    }
   ],
   "source": [
    "class Day(db.Entity):\n",
    "    date = Required(str)\n",
    "    season = Required(str)\n",
    "    working_day = Required(int)\n",
    "    rentals = Required(int)\n",
    "\n",
    "db.generate_mapping(create_tables=True)\n",
    "print(list(db.entities))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "Pony also adds to the entity a column `id` that numbers the rows. It is the **[primary key](https://dvirross.com/courses/intro-data-science/glossary#primary-key)**, so you did not need to write it.\n",
    "\n",
    "**Check yourself:** how many columns does the created table `Day` have, and which of them did we not write?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c016",
   "metadata": {},
   "source": [
    "## Add rows as objects\n",
    "\n",
    "In a program, Pony talks to the database only inside a `with db_session:` block (see [db_session](https://dvirross.com/courses/intro-data-science/glossary#db-session)). The block groups actions that must be saved together, like a bank transfer in which both the withdrawal from one account and the deposit into another must succeed. When the block ends normally, Pony saves all the changes; if an error stops the block, Pony cancels all of them, and none of them is saved. Creating a row is creating an object: call the class with the values of the columns. After the loop, the box counts the rows of the table with `Day.select().count()` and fetches the object whose `id` is 1 with `Day[1]`; the text below the box explains both."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c017",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.302549Z",
     "iopub.status.busy": "2026-11-14T21:13:30.302328Z",
     "iopub.status.idle": "2026-11-14T21:13:30.308452Z",
     "shell.execute_reply": "2026-11-14T21:13:30.307462Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "Day[1] 2011-01-01 985\n"
     ]
    }
   ],
   "source": [
    "rows = [\n",
    "    ('2011-01-01', 'Winter', 0, 985),\n",
    "    ('2011-01-02', 'Winter', 0, 801),\n",
    "    ('2011-01-03', 'Winter', 1, 1349),\n",
    "    ('2011-07-04', 'Summer', 0, 6043),\n",
    "    ('2011-07-05', 'Summer', 1, 4665),\n",
    "    ('2011-07-06', 'Summer', 1, 4629),\n",
    "]\n",
    "\n",
    "with db_session:\n",
    "    for date, season, working_day, rentals in rows:\n",
    "        Day(\n",
    "            date=date, season=season, working_day=working_day,\n",
    "            rentals=rentals\n",
    "        )\n",
    "    print(Day.select().count())\n",
    "    day = Day[1]\n",
    "    print(day, day.date, day.rentals)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c018",
   "metadata": {},
   "source": [
    "The loop uses the [unpacking](https://dvirross.com/courses/intro-data-science/glossary#unpacking) from [loops and functions](https://dvirross.com/courses/intro-data-science/python-loops-and-functions), and the six rows are the real days from the SQL lessons. `Day[1]` fetches the object whose primary key is 1. The values of its columns are called its attributes, and you read one by writing a dot after the object followed by the attribute name, as in `day.date`, exactly as in [objects and generator expressions](https://dvirross.com/courses/intro-data-science/python-objects-and-generators). Printing the object shows the class name and the key. Use the objects inside the `with db_session:` block, where Pony is connected to the database.\n",
    "\n",
    "**Try it yourself.** Inside a `with db_session:` block, print on one line the date, the season and the number of rentals of the day whose primary key is 4."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c019",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.310994Z",
     "iopub.status.busy": "2026-11-14T21:13:30.310783Z",
     "iopub.status.idle": "2026-11-14T21:13:30.314183Z",
     "shell.execute_reply": "2026-11-14T21:13:30.312927Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c020",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>-<number>-<number> Summer <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c021",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.316099Z",
     "iopub.status.busy": "2026-11-14T21:13:30.315838Z",
     "iopub.status.idle": "2026-11-14T21:13:30.319366Z",
     "shell.execute_reply": "2026-11-14T21:13:30.318569Z"
    }
   },
   "outputs": [],
   "source": [
    "check(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c022",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Fetch the object with `Day[4]`, keep it in a variable, and read its attributes `date`, `season` and `rentals` with a dot."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c023",
   "metadata": {},
   "source": [
    "### What happens outside a db_session block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c024",
   "metadata": {},
   "source": [
    "Every use of entities belongs inside `with db_session:` in a program that Python runs from a file: a query outside the block stops with the error `TransactionError: db_session is required when working with the database`. A notebook behaves differently, as the explanation below says, so the cells of this notebook keep the block in every query, as the page does."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c025",
   "metadata": {},
   "source": [
    "**Pony in a notebook (Jupyter or Colab)**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c026",
   "metadata": {},
   "source": [
    "When Pony is first imported, it checks what kind of environment it is running in, and decides from that how strictly to require the `with db_session:` block. A program that Python runs from a file is not interactive, meaning nobody types a line and sees the result right away, so a query outside the block stops there with an error. A notebook (Jupyter or Colab) is an **interactive** console: Pony notices that and lets a query run outside `with db_session:`. The same line `print(Day.select().count())` prints the number of rows there instead of stopping with an error.\n",
    "\n",
    "Keep writing `with db_session:` in a notebook anyway. The code then works unchanged when it moves into a program, and the end of the block is where Pony saves the changes, or cancels them after an error. In Colab, Pony is installed with `pip install pony` in a cell, because Colab does not include it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c027",
   "metadata": {},
   "source": [
    "## Read rows: a query as a generator expression\n",
    "\n",
    "`select(...)` takes a generator expression. The part before `for` says what to return, the part after `in` says which entity, and the condition after `if` filters the rows, just like `SELECT`, `FROM` and `WHERE`. Looping over the result runs the query and gives one object for each row. The method `order_by` sorts the rows of a result by the value of the small function you give it, and `desc(...)` makes the order from the largest down, like `ORDER BY ... DESC`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c028",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.323917Z",
     "iopub.status.busy": "2026-11-14T21:13:30.323748Z",
     "iopub.status.idle": "2026-11-14T21:13:30.330144Z",
     "shell.execute_reply": "2026-11-14T21:13:30.328038Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2011-07-04 6043\n",
      "2011-07-05 4665\n",
      "2011-07-06 4629\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    summer = select(d for d in Day if d.season == 'Summer')\n",
    "    for d in summer.order_by(lambda d: desc(d.rentals)):\n",
    "        print(d.date, d.rentals)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c029",
   "metadata": {},
   "source": [
    "An entity column is read by its name, such as `d.rentals`, so the order of the columns does not matter, and a wrong name such as `d.rentalz` stops at the line of the query, with a message that names it.\n",
    "\n",
    "To see the SQL that Pony wrote, the method `get_sql` of a query returns it as text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c030",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.332046Z",
     "iopub.status.busy": "2026-11-14T21:13:30.331841Z",
     "iopub.status.idle": "2026-11-14T21:13:30.336589Z",
     "shell.execute_reply": "2026-11-14T21:13:30.335336Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT \"d\".\"id\", \"d\".\"date\", \"d\".\"season\", \"d\".\"working_day\", \"d\".\"rentals\"\n",
      "FROM \"Day\" \"d\"\n",
      "WHERE \"d\".\"season\" = 'Summer'\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    print(\n",
    "        select(\n",
    "            d for d in Day if d.season == 'Summer'\n",
    "        ).get_sql()\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c031",
   "metadata": {},
   "source": [
    "This is a query you could have typed in DB Browser. Pony also uses the **parameters** of [SQL from Python](https://dvirross.com/courses/intro-data-science/sql-from-python): a Python variable inside the expression is not pasted into the text, but sent as a value for a question mark."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c032",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.338672Z",
     "iopub.status.busy": "2026-11-14T21:13:30.338478Z",
     "iopub.status.idle": "2026-11-14T21:13:30.344302Z",
     "shell.execute_reply": "2026-11-14T21:13:30.342522Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT \"d\".\"id\", \"d\".\"date\", \"d\".\"season\", \"d\".\"working_day\", \"d\".\"rentals\"\n",
      "FROM \"Day\" \"d\"\n",
      "WHERE \"d\".\"rentals\" > ?\n",
      "['2011-07-04', '2011-07-05', '2011-07-06']\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    limit = 4600\n",
    "    busy = select(d for d in Day if d.rentals > limit)\n",
    "    print(busy.get_sql())\n",
    "    print([d.date for d in busy])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c033",
   "metadata": {},
   "source": [
    "A **[slice](https://dvirross.com/courses/intro-data-science/glossary#slice)** takes the first rows only, as with a list: `select(...)[:2]` returns the first two objects.\n",
    "\n",
    "When only one object is needed, the method `first()` is shorter than `list(...)[0]`. It returns the first object of a result, and `None` when the result is empty, where `list(...)[0]` stops with an error on an empty list.\n",
    "\n",
    "`first()` differs from the slice `[:1]` as well: the slice returns a list that holds at most one object, and `first()` returns the object itself. After `order_by(...)`, the first object is the first in that order. The box takes the day with the fewest rentals, and then asks for a day above 10000 rentals, which does not exist:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c034",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.346544Z",
     "iopub.status.busy": "2026-11-14T21:13:30.346372Z",
     "iopub.status.idle": "2026-11-14T21:13:30.353739Z",
     "shell.execute_reply": "2026-11-14T21:13:30.352412Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2011-01-02 801\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    quietest = select(d for d in Day).order_by(\n",
    "        lambda d: d.rentals\n",
    "    ).first()\n",
    "    print(quietest.date, quietest.rentals)\n",
    "    huge = select(d for d in Day if d.rentals > 10000).first()\n",
    "    print(huge)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c035",
   "metadata": {},
   "source": [
    "The first call returns an object, whose attributes are read by writing a dot and then the attribute name, and the second finds no day and returns `None`, so check for `None` before reading an attribute of the result.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** Inside a `with db_session:` block, print the dates of the days of `'Winter'`, one on each line, from the earliest date to the latest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c036",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.355640Z",
     "iopub.status.busy": "2026-11-14T21:13:30.355458Z",
     "iopub.status.idle": "2026-11-14T21:13:30.360511Z",
     "shell.execute_reply": "2026-11-14T21:13:30.359334Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>-<number>-<number>\n",
    "<number>-<number>-<number>\n",
    "<number>-<number>-<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c038",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.362229Z",
     "iopub.status.busy": "2026-11-14T21:13:30.362029Z",
     "iopub.status.idle": "2026-11-14T21:13:30.366044Z",
     "shell.execute_reply": "2026-11-14T21:13:30.364787Z"
    }
   },
   "outputs": [],
   "source": [
    "check(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Keep the winter days with a condition after `if`, sort the result with `order_by(lambda d: d.date)`, and loop over it to print one attribute on each line."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c040",
   "metadata": {},
   "source": [
    "## Summaries and groups\n",
    "\n",
    "The summary functions of SQL have names in Pony too: `count`, `sum`, `avg`, `min` and `max`. Each takes a generator expression that gives the values to summarize; `sum`, `min` and `max` keep working on ordinary lists, as in [values and collections](https://dvirross.com/courses/intro-data-science/python-values-and-collections)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c041",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.367708Z",
     "iopub.status.busy": "2026-11-14T21:13:30.367528Z",
     "iopub.status.idle": "2026-11-14T21:13:30.373636Z",
     "shell.execute_reply": "2026-11-14T21:13:30.372638Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "5112.333333333333\n",
      "6043\n",
      "10643\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    print(count(d for d in Day))\n",
    "    print(avg(d.rentals for d in Day if d.season == 'Summer'))\n",
    "    print(max(d.rentals for d in Day))\n",
    "    print(sum(d.rentals for d in Day if d.working_day == 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c042",
   "metadata": {},
   "source": [
    "When the expression returns a pair, such as the season and a summary, Pony groups by the part that is not summarized:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c043",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.375521Z",
     "iopub.status.busy": "2026-11-14T21:13:30.375338Z",
     "iopub.status.idle": "2026-11-14T21:13:30.381009Z",
     "shell.execute_reply": "2026-11-14T21:13:30.379611Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT \"d\".\"season\", AVG(\"d\".\"rentals\")\n",
      "FROM \"Day\" \"d\"\n",
      "GROUP BY \"d\".\"season\"\n",
      "[('Summer', 5112.333333333333), ('Winter', 1045.0)]\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    by_season = select(\n",
    "        (d.season, avg(d.rentals)) for d in Day\n",
    "    )\n",
    "    print(by_season.get_sql())\n",
    "    print(list(by_season))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c044",
   "metadata": {},
   "source": [
    "The same shape counts the rows of each group: with `count(d)` in the pair, where `d` is the whole day, Pony counts the days of each season. It counts each day once, by its primary key, which is why the SQL that it writes includes `COUNT(DISTINCT ...)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c045",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.383523Z",
     "iopub.status.busy": "2026-11-14T21:13:30.383346Z",
     "iopub.status.idle": "2026-11-14T21:13:30.387863Z",
     "shell.execute_reply": "2026-11-14T21:13:30.386912Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT \"d\".\"season\", COUNT(DISTINCT \"d\".\"id\")\n",
      "FROM \"Day\" \"d\"\n",
      "GROUP BY \"d\".\"season\"\n",
      "[('Summer', 3), ('Winter', 3)]\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    days_per_season = select(\n",
    "        (d.season, count(d)) for d in Day\n",
    "    )\n",
    "    print(days_per_season.get_sql())\n",
    "    print(list(days_per_season))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c046",
   "metadata": {},
   "source": [
    "The SQL has a `GROUP BY` that you did not write: the [SQL guide, Part 1](https://dvirross.com/courses/intro-data-science/sql-in-db-browser) taught it, and here the ORM adds it from the shape of the expression.\n",
    "\n",
    "### The same total in two ways\n",
    "\n",
    "A question about a total can be answered by a loop in Python or by a summary function, and both give the same number. The method `select()` of an entity, with no arguments, returns all its objects. The loop below takes every day from the database and adds the rentals of the summer days one by one, in Python. The summary function asks the database for the total instead.\n",
    "\n",
    "**Predict:** both ways print the same number. Which of them moves fewer rows from the database into Python, and why?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c047",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.389770Z",
     "iopub.status.busy": "2026-11-14T21:13:30.389585Z",
     "iopub.status.idle": "2026-11-14T21:13:30.395537Z",
     "shell.execute_reply": "2026-11-14T21:13:30.394351Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15337\n",
      "15337\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    total = 0\n",
    "    for d in Day.select():\n",
    "        if d.season == 'Summer':\n",
    "            total = total + d.rentals\n",
    "    print(total)\n",
    "    print(sum(d.rentals for d in Day if d.season == 'Summer'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "### A summary that feeds a second query\n",
    "\n",
    "A summary is an ordinary Python value, so it can be stored in a variable and used in the next query. The first query below finds the largest rentals with `max`, and `Day.get(rentals=top)` then returns the day with that value.\n",
    "\n",
    "The method `get` expects exactly one match: when two days share the value, Pony stops with an error, and `select(...).first()` is the way to take one of them.\n",
    "\n",
    "The second query finds the average rentals of all days with `avg`, and a query keeps the days above it. Pony sends the stored value as a parameter, as in the query with `limit` above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c049",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.397330Z",
     "iopub.status.busy": "2026-11-14T21:13:30.397141Z",
     "iopub.status.idle": "2026-11-14T21:13:30.403598Z",
     "shell.execute_reply": "2026-11-14T21:13:30.402452Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2011-07-04 6043\n",
      "3079 3\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    top = max(d.rentals for d in Day)\n",
    "    busiest = Day.get(rentals=top)\n",
    "    print(busiest.date, top)\n",
    "\n",
    "    mean = avg(d.rentals for d in Day)\n",
    "    above = select(d for d in Day if d.rentals > mean)\n",
    "    print(round(mean), above.count())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c050",
   "metadata": {},
   "source": [
    "The average of the six days is about 3079, and three days have more rentals than that: the three summer days."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c051",
   "metadata": {},
   "source": [
    "> **Self-study, importance 2.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Practice that repeats the summary functions on the winter days. It helps with: summary functions (maximum, average) over a group of rows."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c052",
   "metadata": {},
   "source": [
    "### Practice\n",
    "\n",
    "**Your turn.** Inside a `with db_session:` block, print the largest rentals among the winter days, using `max`, and on the next line the average rentals of the winter days, using `avg`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c053",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.405372Z",
     "iopub.status.busy": "2026-11-14T21:13:30.405198Z",
     "iopub.status.idle": "2026-11-14T21:13:30.408304Z",
     "shell.execute_reply": "2026-11-14T21:13:30.407151Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c054",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "<number>.<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c055",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.409939Z",
     "iopub.status.busy": "2026-11-14T21:13:30.409781Z",
     "iopub.status.idle": "2026-11-14T21:13:30.413328Z",
     "shell.execute_reply": "2026-11-14T21:13:30.412046Z"
    }
   },
   "outputs": [],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c056",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Each summary function takes a generator expression, and both lines need the same condition after `if`: the season is `'Winter'`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c057",
   "metadata": {},
   "source": [
    "**Your turn.** Inside a `with db_session:` block, store the average rentals of all the days in a variable. Then print the dates of the days with fewer rentals than that average, one on each line, from the earliest date to the latest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c058",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.415025Z",
     "iopub.status.busy": "2026-11-14T21:13:30.414858Z",
     "iopub.status.idle": "2026-11-14T21:13:30.421410Z",
     "shell.execute_reply": "2026-11-14T21:13:30.420177Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>-<number>-<number>\n",
    "<number>-<number>-<number>\n",
    "<number>-<number>-<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c060",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.423368Z",
     "iopub.status.busy": "2026-11-14T21:13:30.423192Z",
     "iopub.status.idle": "2026-11-14T21:13:30.426792Z",
     "shell.execute_reply": "2026-11-14T21:13:30.425648Z"
    }
   },
   "outputs": [],
   "source": [
    "check(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c061",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Write the average in a variable inside the block, use that variable after `if` in a `select(...)`, and sort the result with `order_by(lambda d: d.date)`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c062",
   "metadata": {},
   "source": [
    "## Change and delete rows\n",
    "\n",
    "To change a column, assign to the attribute of the object. To delete a row, call `delete()` on its object. We first add a **test day** that is not real data, so that the real days stay as they are. `Day.get(...)` returns the one object that matches, or `None` if there is none. **Predict:** the second block sets `rentals` to 2, and the third is a new `with db_session:`. What does the third print on its first line: 1, 2 or an error?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c063",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.428900Z",
     "iopub.status.busy": "2026-11-14T21:13:30.428709Z",
     "iopub.status.idle": "2026-11-14T21:13:30.435430Z",
     "shell.execute_reply": "2026-11-14T21:13:30.434278Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "2\n",
      "6\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    Day(\n",
    "        date='2099-01-01', season='Summer', working_day=1,\n",
    "        rentals=1\n",
    "    )\n",
    "\n",
    "with db_session:\n",
    "    test_day = Day.get(date='2099-01-01')\n",
    "    test_day.rentals = 2\n",
    "    print(test_day.rentals)\n",
    "\n",
    "with db_session:\n",
    "    print(Day.get(date='2099-01-01').rentals)\n",
    "    Day.get(date='2099-01-01').delete()\n",
    "    print(count(d for d in Day))\n",
    "    print(Day.get(date='2099-01-01'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c064",
   "metadata": {},
   "source": [
    "Compare this with [SQL from Python](https://dvirross.com/courses/intro-data-science/sql-from-python), where you wrote `UPDATE` and `DELETE` as SQL text and decided when to call `commit()`. Here the end of the `db_session` block is the commit, and an error inside the block is the rollback. The call `commit()` inside the block saves the changes made so far at once, and the block goes on."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c065",
   "metadata": {},
   "source": [
    "> **Self-study, importance 1.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Cancelling a change on purpose, and practice on changing and deleting a test day. It helps with: changing and deleting rows, and cancelling a change inside a block."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c066",
   "metadata": {},
   "source": [
    "You can also cancel on purpose: the call `rollback()` inside the block cancels every change made since the block began, as `conn.rollback()` does in [the section on changing data and saving it](https://dvirross.com/courses/intro-data-science/sql-from-python#changing-data-and-saving-it), and the block then continues with the database as it was.\n",
    "\n",
    "After a `commit()` inside the block, a later `rollback()` cancels only what came after the `commit()`. The box below adds a test day, saves it with `commit()`, adds a second test day and cancels it with `rollback()`. A new block then reads what the database holds, and deletes the first test day, so that the table has its six real days again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "c067",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.437708Z",
     "iopub.status.busy": "2026-11-14T21:13:30.437469Z",
     "iopub.status.idle": "2026-11-14T21:13:30.445089Z",
     "shell.execute_reply": "2026-11-14T21:13:30.444114Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "None\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    Day(\n",
    "        date='2097-01-01', season='Summer', working_day=1,\n",
    "        rentals=1\n",
    "    )\n",
    "    commit()\n",
    "    Day(\n",
    "        date='2097-01-02', season='Summer', working_day=1,\n",
    "        rentals=2\n",
    "    )\n",
    "    rollback()\n",
    "\n",
    "with db_session:\n",
    "    print(Day.get(date='2097-01-01').rentals)\n",
    "    print(Day.get(date='2097-01-02'))\n",
    "    Day.get(date='2097-01-01').delete()\n",
    "    print(count(d for d in Day))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c068",
   "metadata": {},
   "source": [
    "The first test day was saved by `commit()`, so it is still there, and the second was cancelled before it was saved, so `Day.get` finds nothing and returns `None`.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** In one `with db_session:` block, create a test day with the date `'2098-01-01'`, the season `'Winter'`, `working_day` 0 and rentals 10. Change its rentals to 20 and print them. Then delete the day and print `count(d for d in Day)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "c069",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.447766Z",
     "iopub.status.busy": "2026-11-14T21:13:30.447574Z",
     "iopub.status.idle": "2026-11-14T21:13:30.450421Z",
     "shell.execute_reply": "2026-11-14T21:13:30.449615Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c070",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "20\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c071",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.452941Z",
     "iopub.status.busy": "2026-11-14T21:13:30.452764Z",
     "iopub.status.idle": "2026-11-14T21:13:30.457262Z",
     "shell.execute_reply": "2026-11-14T21:13:30.455240Z"
    }
   },
   "outputs": [],
   "source": [
    "check(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c072",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Keep the object that `Day(...)` returns in a variable. Assign to its attribute `rentals` to change it, and call `delete()` on the object to remove the row."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c073",
   "metadata": {},
   "source": [
    "## Practice\n",
    "\n",
    "Each question has its own code box: write your answer there and select **Run**. Open a hint if you are stuck, and the solution only after you try.\n",
    "\n",
    "Before the questions, notice what stays the same from the SQL lessons: the tables, the keys and the thinking about which rows and which summary you need. Only the way you write the request changes.\n",
    "\n",
    "**Question 1.** Print the date and rentals of the working days (`working_day` is 1) with more than 4600 rentals, from the busiest day down."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "c074",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.459498Z",
     "iopub.status.busy": "2026-11-14T21:13:30.459328Z",
     "iopub.status.idle": "2026-11-14T21:13:30.462769Z",
     "shell.execute_reply": "2026-11-14T21:13:30.461347Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c075",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>-<number>-<number> <number>\n",
    "<number>-<number>-<number> <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "c076",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.464416Z",
     "iopub.status.busy": "2026-11-14T21:13:30.464255Z",
     "iopub.status.idle": "2026-11-14T21:13:30.467671Z",
     "shell.execute_reply": "2026-11-14T21:13:30.466607Z"
    }
   },
   "outputs": [],
   "source": [
    "check(6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c077",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Put both conditions after `if`, joined with `and`, and sort with the function:\n",
    ">\n",
    "> ```python\n",
    "> order_by(lambda d: desc(d.rentals))\n",
    "> ```\n",
    ">\n",
    "> Loop over the result and print two attributes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c078",
   "metadata": {},
   "source": [
    "> **Self-study, importance 3.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Questions 2 and 3, and the summary of the lesson. It helps with: grouping rows, and calculations inside a query."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c079",
   "metadata": {},
   "source": [
    "**Question 2.** For each season, print how many days had more than 1000 rentals, one line for each season: the season, a space, the number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "c080",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.469247Z",
     "iopub.status.busy": "2026-11-14T21:13:30.469040Z",
     "iopub.status.idle": "2026-11-14T21:13:30.471970Z",
     "shell.execute_reply": "2026-11-14T21:13:30.470909Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c081",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Summer <number>\n",
    "Winter <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "c082",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.473685Z",
     "iopub.status.busy": "2026-11-14T21:13:30.473539Z",
     "iopub.status.idle": "2026-11-14T21:13:30.476727Z",
     "shell.execute_reply": "2026-11-14T21:13:30.475791Z"
    }
   },
   "outputs": [],
   "source": [
    "check(7)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c083",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Return a pair, the season and `count(d)`, and put the condition on `d.rentals` after `if`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c084",
   "metadata": {},
   "source": [
    "**Question 3.** Add the real day `'2011-07-07'` (a summer working day with 4592 rentals), then print the average rentals of the summer days, rounded to a whole number. Finish with `rollback()`, which cancels the new day, so that the other boxes of the page still see the same six days."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "c085",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.479890Z",
     "iopub.status.busy": "2026-11-14T21:13:30.479716Z",
     "iopub.status.idle": "2026-11-14T21:13:30.483245Z",
     "shell.execute_reply": "2026-11-14T21:13:30.481943Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c086",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "c087",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.484878Z",
     "iopub.status.busy": "2026-11-14T21:13:30.484703Z",
     "iopub.status.idle": "2026-11-14T21:13:30.488092Z",
     "shell.execute_reply": "2026-11-14T21:13:30.487145Z"
    }
   },
   "outputs": [],
   "source": [
    "check(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c088",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Create the object with `Day(...)` inside a `db_session` block, then call `avg` on a generator expression about the summer days. Wrap it in `round(...)`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c089",
   "metadata": {},
   "source": [
    "## Keep in mind\n",
    "\n",
    "- An **ORM** maps a table to a class and a row to an object. **Pony** writes the SQL from a generator expression, so the form of the expression matters.\n",
    "- `db.Entity` classes describe tables, `Required(...)` describes a column, and `db.generate_mapping(...)` creates the tables.\n",
    "- Work with the database inside `with db_session:`: creating objects, running queries and reading related objects. A program that runs outside it stops with an error. The end of the block saves the changes, and an error inside cancels them.\n",
    "- `select(...)`, `count`, `avg`, `sum`, `min` and `max` correspond to `SELECT`, `COUNT`, `AVG`, `SUM`, `MIN` and `MAX`; `get_sql()` shows the SQL that Pony wrote.\n",
    "- To change a column, assign to the attribute; to delete a row, call `delete()`.\n",
    "- `commit()` inside the block saves the changes so far; a later `rollback()` cancels only what came after it.\n",
    "- A summary can be stored in a variable and used in a second query; `get(...)` returns the one object that matches and stops with an error when several do.\n",
    "- `first()` returns the first object of a query result, or `None` when it is empty.\n",
    "- A notebook lets a query run outside `with db_session:` and a program does not; keep the block in both."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c090",
   "metadata": {},
   "source": [
    "# Part 2: Pony ORM Relations: A Table That Points to Another Table\n",
    "\n",
    "The lesson page of this part: [Pony ORM Relations: A Table That Points to Another Table](https://dvirross.com/courses/intro-data-science/python-orm-pony-relations)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c091",
   "metadata": {},
   "source": [
    "## Where did life expectancy rise the most?\n",
    "\n",
    "To answer, keep a table with the life expectancy of several countries in two years, and the income level of the country next to each measurement. Then the name of a country and its income level are written again on every row of that country, and this causes two problems. The first: when the classification of a country changes, it must be corrected on every row, and one row that is forgotten puts the same country on two income levels. The second: a typo in a name, such as `'Isreal'`, splits one country into two. The remedy is to keep each country once, and give each measurement a pointer to its country: two tables that point to each other.\n",
    "\n",
    "This lesson builds on [Tables as Python Objects: A First Look at Pony ORM](https://dvirross.com/courses/intro-data-science/python-orm-pony), which taught entities, `with db_session:`, `select`, `get`, the summary functions and `first()`.\n",
    "\n",
    "In the [SQL guide](https://dvirross.com/courses/intro-data-science/sql-change-and-join), the department column of a table of employees holds the primary key of a row in another table, the departments. A column like that is a **[foreign key](https://dvirross.com/courses/intro-data-science/glossary#foreign-key)**, and a `JOIN` follows it to put each row next to the row it points to. When one row of the first table is pointed to by many rows of the second, as one country is pointed to by its yearly measurements, this is a **[one-to-many relation](https://dvirross.com/courses/intro-data-science/glossary#one-to-many-relation)**. An ORM writes the same link as attributes: an observation object holds its country object, and a country object holds all of its observation objects.\n",
    "\n",
    "The data are real and come from the World Bank's **World Development Indicators** (license CC BY 4.0), retrieved through the World Bank API: the first two indicators on 30 October 2026 and the third on 8 November 2026. Three indicators are used. `SP.DYN.LE00.IN` is the **life expectancy at birth**: the number of years a newborn would live if the death rates of that year stayed the same for life. `NY.GDP.PCAP.PP.CD` is the **GDP per capita, PPP**: the value of what a country produces in a year per person, in current international dollars, a unit that corrects for differences in prices between countries. `SP.POP.TOTL` is the **total population**: the number of residents of a country, as the World Bank estimates it for the middle of the year. The extract has 10 countries chosen to span regions and income levels, for the years 2000 and 2020. The income level of each country is the World Bank's own classification, as published at retrieval.\n",
    "\n",
    "Three cautions come with the data. A few countries are not the world, so the extract can show a pattern but not measure it. Two measurements that move together are an association and not a proof that one causes the other. Also, a value that the source does not have stays missing: it is not zero. The GDP of Syria in 2000 is missing in the source.\n",
    "\n",
    "**Your turn:** one country has many measurements, and each measurement has one country. How do you describe this in two classes, and in which of them is the pointer stored?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c092",
   "metadata": {},
   "source": [
    "The first line of the next box brings in the names of Pony, and `geo` is the database object of this lesson. A few names describe the relation and the new kinds of columns:\n",
    "\n",
    "- `Set('Observation')` is the attribute `observations` of a country. It holds the set of all the observations that point to that country, and it is not a column of the table: Pony reads it from the column on the other side. The class name is in quotes because `Observation` is defined below it.\n",
    "- `Required(Country)` is the attribute `country` of an observation. Its value must be one `Country` object, so every observation belongs to a country. `Optional(Country)` would allow an observation with no country.\n",
    "- `Optional(float)` is a number with a decimal point that may be missing, and `Optional(int)` is a whole number that may be missing; a missing value is `None`.\n",
    "\n",
    "The function `show(Observation)` prints the description of an entity as Pony understood it: its attributes and their kinds, including the `id` that Pony added. The `id` is a primary key that Pony chooses when we do not. We can choose our own: with `code = PrimaryKey(str)` the code of a country is its primary key, Pony adds no `id`, and a country is found by `Country['ISR']`. This lesson keeps the `id`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "c093",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.489720Z",
     "iopub.status.busy": "2026-11-14T21:13:30.489550Z",
     "iopub.status.idle": "2026-11-14T21:13:30.496336Z",
     "shell.execute_reply": "2026-11-14T21:13:30.495308Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "class Observation(Entity):\n",
      "    id = PrimaryKey(int, auto=True)\n",
      "    year = Required(int)\n",
      "    life_expectancy = Optional(float)\n",
      "    gdp_per_capita = Optional(float)\n",
      "    population = Optional(int)\n",
      "    country = Required(Country)\n"
     ]
    }
   ],
   "source": [
    "from pony.orm import *\n",
    "\n",
    "geo = Database()\n",
    "geo.bind(provider='sqlite', filename=':memory:')\n",
    "\n",
    "class Country(geo.Entity):\n",
    "    code = Required(str)\n",
    "    name = Required(str)\n",
    "    income_level = Required(str)\n",
    "    observations = Set('Observation')\n",
    "\n",
    "class Observation(geo.Entity):\n",
    "    year = Required(int)\n",
    "    life_expectancy = Optional(float)\n",
    "    gdp_per_capita = Optional(float)\n",
    "    population = Optional(int)\n",
    "    country = Required(Country)\n",
    "\n",
    "geo.generate_mapping(create_tables=True)\n",
    "show(Observation)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c094",
   "metadata": {},
   "source": [
    "### Create the objects and connect them\n",
    "\n",
    "The extract is two lists of tuples: the countries, and the observations, each with the code of its country, the year, the life expectancy, the GDP per capita and the population. The values are rounded, and the rounding changes no result in the lesson. In practice such rows usually come from a file, and the section [Rows from a file](#rows-from-a-file) shows how to load them from one. Here we write them in the code so that we can concentrate on creating the objects and connecting them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "c095",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.498142Z",
     "iopub.status.busy": "2026-11-14T21:13:30.497923Z",
     "iopub.status.idle": "2026-11-14T21:13:30.501824Z",
     "shell.execute_reply": "2026-11-14T21:13:30.500741Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "country_rows = [\n",
    "    ('ISR', 'Israel', 'High income'),\n",
    "    ('JPN', 'Japan', 'High income'),\n",
    "    ('USA', 'United States', 'High income'),\n",
    "    ('NOR', 'Norway', 'High income'),\n",
    "    ('BRA', 'Brazil', 'Upper middle income'),\n",
    "    ('CHN', 'China', 'Upper middle income'),\n",
    "    ('EGY', 'Egypt, Arab Rep.', 'Lower middle income'),\n",
    "    ('IND', 'India', 'Lower middle income'),\n",
    "    ('ETH', 'Ethiopia', 'Low income'),\n",
    "    ('SYR', 'Syrian Arab Republic', 'Low income'),\n",
    "]\n",
    "print(len(country_rows))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "c096",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.503685Z",
     "iopub.status.busy": "2026-11-14T21:13:30.503527Z",
     "iopub.status.idle": "2026-11-14T21:13:30.508223Z",
     "shell.execute_reply": "2026-11-14T21:13:30.507180Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n"
     ]
    }
   ],
   "source": [
    "observation_rows = [\n",
    "    ('ISR', 2000, 78.954, 25746.83, 6289000),\n",
    "    ('ISR', 2020, 82.649, 40969.3, 9215100),\n",
    "    ('JPN', 2000, 81.076, 27694.54, 126843000),\n",
    "    ('JPN', 2020, 84.56, 43560.02, 126261000),\n",
    "    ('USA', 2000, 76.637, 36329.97, 282162411),\n",
    "    ('USA', 2020, 76.98, 64465.3, 331578104),\n",
    "    ('NOR', 2000, 78.634, 36813.84, 4490967),\n",
    "    ('NOR', 2020, 83.21, 69779.29, 5379475),\n",
    "    ('BRA', 2000, 69.584, 9091.77, 174018282),\n",
    "    ('BRA', 2020, 74.506, 16101.62, 208660842),\n",
    "    ('CHN', 2000, 72.288, 2963.43, 1262645000),\n",
    "    ('CHN', 2020, 78.019, 18267.48, 1411100000),\n",
    "    ('EGY', 2000, 67.332, 5451.52, 73083284),\n",
    "    ('EGY', 2020, 69.79, 15231.87, 109315124),\n",
    "    ('IND', 2000, 62.749, 2030.77, 1057922733),\n",
    "    ('IND', 2020, 70.156, 6766.06, 1402617695),\n",
    "    ('ETH', 2000, 50.88, 473.9, 67411494),\n",
    "    ('ETH', 2020, 65.969, 2406.79, 118917671),\n",
    "    ('SYR', 2000, 70.856, None, 16637888),\n",
    "    ('SYR', 2020, 71.944, 3878.43, 21049429),\n",
    "]\n",
    "print(len(observation_rows))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c097",
   "metadata": {},
   "source": [
    "The values of a dictionary can be any objects, not only numbers and text: here the keys are the country codes and the values are the `Country` objects. To create an observation of a country, we look the country object up by its code and pass it as `country=...`. That connects the two rows: Pony stores the key of the country in the column `country` of the observation. The value `None` in a row goes into an `Optional` column as a missing value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "c098",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.510459Z",
     "iopub.status.busy": "2026-11-14T21:13:30.510297Z",
     "iopub.status.idle": "2026-11-14T21:13:30.517327Z",
     "shell.execute_reply": "2026-11-14T21:13:30.515880Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 20\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    countries = {}\n",
    "    for code, name, income in country_rows:\n",
    "        countries[code] = Country(\n",
    "            code=code, name=name, income_level=income\n",
    "        )\n",
    "    for code, year, life, gdp, people in observation_rows:\n",
    "        Observation(\n",
    "            year=year, life_expectancy=life,\n",
    "            gdp_per_capita=gdp, population=people,\n",
    "            country=countries[code]\n",
    "        )\n",
    "    print(\n",
    "        Country.select().count(),\n",
    "        Observation.select().count()\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c099",
   "metadata": {},
   "source": [
    "### Follow the relation in both directions\n",
    "\n",
    "Inside a `db_session`, a dot follows the relation. For an observation `obs`, `obs.country` is its `Country` object, and `obs.country.name` is the name of that country. In the other direction, `country.observations` is the set of the observations of a country. A set can be looped over like a list, and it has three methods: `count()` returns the number of objects in it, `order_by(...)` sorts it as for a query, and `select(...)` keeps the objects for which the function you give is true. To take one object by its place, as from a list, first turn the result of `order_by` or `select` into a list with `list(...)`. The function `round(x, 1)` rounds `x` to one digit after the decimal point."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "c100",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.518970Z",
     "iopub.status.busy": "2026-11-14T21:13:30.518810Z",
     "iopub.status.idle": "2026-11-14T21:13:30.525281Z",
     "shell.execute_reply": "2026-11-14T21:13:30.524039Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Israel High income\n",
      "2\n",
      "Israel 2020 82.6\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    israel = Country.get(code='ISR')\n",
    "    print(israel.name, israel.income_level)\n",
    "    print(israel.observations.count())\n",
    "    in_2020 = list(\n",
    "        israel.observations.select(lambda o: o.year == 2020)\n",
    "    )\n",
    "    obs = in_2020[0]\n",
    "    print(\n",
    "        obs.country.name, obs.year,\n",
    "        round(obs.life_expectancy, 1)\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c101",
   "metadata": {},
   "source": [
    "The method `first()` works on a set of related objects as well: the box takes the latest observation of Israel, then looks for a year with no observation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "c102",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.527390Z",
     "iopub.status.busy": "2026-11-14T21:13:30.527158Z",
     "iopub.status.idle": "2026-11-14T21:13:30.536481Z",
     "shell.execute_reply": "2026-11-14T21:13:30.535300Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2020 82.6\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    israel = Country.get(code='ISR')\n",
    "    latest = israel.observations.order_by(\n",
    "        lambda o: desc(o.year)\n",
    "    ).first()\n",
    "    print(latest.year, round(latest.life_expectancy, 1))\n",
    "    missing = israel.observations.select(\n",
    "        lambda o: o.year == 1990\n",
    "    ).first()\n",
    "    print(missing)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c103",
   "metadata": {},
   "source": [
    "### Questions that the related objects answer\n",
    "\n",
    "For each country, `list(country.observations.order_by(lambda o: o.year))` holds its two observations, the earlier year first: the index `[0]` is 2000 and `[1]` is 2020. The change in life expectancy is the value of 2020 minus the value of 2000. We collect each change with the name of its country in a list of tuples, and `sorted(..., reverse=True)` puts the largest change first:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "c104",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.538663Z",
     "iopub.status.busy": "2026-11-14T21:13:30.538476Z",
     "iopub.status.idle": "2026-11-14T21:13:30.546706Z",
     "shell.execute_reply": "2026-11-14T21:13:30.545364Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(15.1, 'Ethiopia'), (7.4, 'India'), (5.7, 'China')]\n",
      "(0.3, 'United States')\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    gains = []\n",
    "    for country in Country.select():\n",
    "        years = list(\n",
    "            country.observations.order_by(lambda o: o.year)\n",
    "        )\n",
    "        early = years[0].life_expectancy\n",
    "        late = years[1].life_expectancy\n",
    "        gains.append((round(late - early, 1), country.name))\n",
    "    ranked = sorted(gains, reverse=True)\n",
    "    print(ranked[:3])\n",
    "    print(ranked[-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c105",
   "metadata": {},
   "source": [
    "Life expectancy rose in every country, most in Ethiopia, which started lowest. The extract does not say why: the smallest change, 0.3 years in the United States, can come from the long trend, from the pandemic of 2020, or from both, and two points cannot separate them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c106",
   "metadata": {},
   "source": [
    "> **Self-study, importance 4.** This part is for self-study: it is not taught in the lecture, and you read it on your own. The second question of this section: the GDP per capita and a missing value. It helps with: a missing value in a calculation over related objects."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c107",
   "metadata": {},
   "source": [
    "For the GDP per capita, a value can be missing, and then there is nothing to divide. The loop keeps the countries without a value apart (`x is None` is true when `x` is missing), and for the others it computes how many times the GDP grew, the value of 2020 divided by the value of 2000:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "c108",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.548636Z",
     "iopub.status.busy": "2026-11-14T21:13:30.548449Z",
     "iopub.status.idle": "2026-11-14T21:13:30.556050Z",
     "shell.execute_reply": "2026-11-14T21:13:30.554697Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(6.2, 'China'), (5.1, 'Ethiopia'), (3.3, 'India')]\n",
      "missing: ['Syrian Arab Republic']\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    multiples = []\n",
    "    missing = []\n",
    "    for country in Country.select():\n",
    "        years = list(\n",
    "            country.observations.order_by(lambda o: o.year)\n",
    "        )\n",
    "        early = years[0].gdp_per_capita\n",
    "        late = years[1].gdp_per_capita\n",
    "        if early is None or late is None:\n",
    "            missing.append(country.name)\n",
    "        else:\n",
    "            multiples.append(\n",
    "                (round(late / early, 1), country.name)\n",
    "            )\n",
    "    print(sorted(multiples, reverse=True)[:3])\n",
    "    print('missing:', missing)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c109",
   "metadata": {},
   "source": [
    "> **Self-study, importance 2.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Conditions and sums that cross the relation, and task 9. It helps with: a condition that follows a relation, and a sum over the related objects of each object."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c110",
   "metadata": {},
   "source": [
    "### A condition across the relation\n",
    "\n",
    "Inside a query, a dot can follow the relation as well: `o.country.income_level` is the income level of the country of the observation `o`. Such a query needs both tables, and Pony writes the join that the SQL guide wrote by hand. We group the observations of 2020 by income level and average the two indicators; `avg` skips the missing values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "c111",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.558178Z",
     "iopub.status.busy": "2026-11-14T21:13:30.557957Z",
     "iopub.status.idle": "2026-11-14T21:13:30.564140Z",
     "shell.execute_reply": "2026-11-14T21:13:30.562915Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT \"country\".\"income_level\", AVG(\"o\".\"life_expectancy\"), AVG(\"o\".\"gdp_per_capita\")\n",
      "FROM \"Observation\" \"o\", \"Country\" \"country\"\n",
      "WHERE \"o\".\"year\" = 2020\n",
      "  AND \"o\".\"country\" = \"country\".\"id\"\n",
      "GROUP BY \"country\".\"income_level\"\n",
      "Low income 69.0 3143\n",
      "Lower middle income 70.0 10999\n",
      "Upper middle income 76.3 17185\n",
      "High income 81.8 54693\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    by_level = select(\n",
    "        (\n",
    "            o.country.income_level,\n",
    "            avg(o.life_expectancy),\n",
    "            avg(o.gdp_per_capita)\n",
    "        )\n",
    "        for o in Observation if o.year == 2020\n",
    "    )\n",
    "    print(by_level.get_sql())\n",
    "    by_gdp = sorted(by_level, key=lambda row: row[2])\n",
    "    for level, life, gdp in by_gdp:\n",
    "        print(level, round(life, 1), round(gdp))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c112",
   "metadata": {},
   "source": [
    "The `WHERE` has the condition on the year and the line that connects the foreign key `\"o\".\"country\"` to the primary key `\"country\".\"id\"`, as `ON` does in a `JOIN`. On income level: higher income levels go with a longer life expectancy here, an association between averages of two to four countries.\n",
    "\n",
    "### A sum over countries of the same level\n",
    "\n",
    "A population is counted in people, so it can be added: `sum` adds the number of residents of the measurements of the countries of one income level. GDP per capita is a ratio, GDP divided by population, so adding it across countries is not the GDP per capita of all of them.\n",
    "\n",
    "**Your turn.** Inside a `with db_session:` block, print for each income level how many people lived in 2020 in the countries of that level in the extract, in millions rounded to a whole number: one line for each level, with the income level, a space and the number, from the level with the most residents to the level with the fewest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "c113",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.566214Z",
     "iopub.status.busy": "2026-11-14T21:13:30.565982Z",
     "iopub.status.idle": "2026-11-14T21:13:30.569158Z",
     "shell.execute_reply": "2026-11-14T21:13:30.568019Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c114",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Upper middle income <number>\n",
    "Lower middle income <number>\n",
    "High income <number>\n",
    "Low income <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "c115",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.571302Z",
     "iopub.status.busy": "2026-11-14T21:13:30.571130Z",
     "iopub.status.idle": "2026-11-14T21:13:30.574691Z",
     "shell.execute_reply": "2026-11-14T21:13:30.573544Z"
    }
   },
   "outputs": [],
   "source": [
    "check(9)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c116",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Return a pair, `o.country.income_level` and the `sum(...)` of the population, over the observations of 2020, as in the grouping above. Sort the pairs with `sorted(..., key=lambda row: row[1], reverse=True)`, and divide by 1000000 before rounding."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c117",
   "metadata": {},
   "source": [
    "> **Self-study, importance 3.** This part is for self-study: it is not taught in the lecture, and you read it on your own. The SQL that Pony sends while a relation is followed, and a sum over the collection of one country. It helps with: the SQL that Pony sends, and a sum over the related objects of one object."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c118",
   "metadata": {},
   "source": [
    "### A sum over the collection of one country\n",
    "\n",
    "The set `country.observations` of one country can be added up too, with Python's own `sum`: `sum(o.population for o in collection)` adds `o.population` of every object of the collection. Here we go over the set itself and keep the observations of Israel in 2020:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c119",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.576317Z",
     "iopub.status.busy": "2026-11-14T21:13:30.576169Z",
     "iopub.status.idle": "2026-11-14T21:13:30.580412Z",
     "shell.execute_reply": "2026-11-14T21:13:30.579300Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9215100\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    israel = Country.get(code='ISR')\n",
    "    print(sum(\n",
    "        o.population for o in israel.observations\n",
    "        if o.year == 2020 and o.population is not None\n",
    "    ))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c120",
   "metadata": {},
   "source": [
    "A country has one observation for each year, so the collection has one object and the sum has one term: the box shows the form, not a larger total. The trap: the box goes over the set itself, so Python adds the values one by one and cannot add `None` to a number: it stops with a `TypeError`, the error for a value of the wrong kind. The `sum` of a query made with `select(...)` is different: it becomes SQL, and the database skips a missing value. The column `population` is `Optional(int)`, so `if o.population is not None` keeps only objects with a value.\n",
    "\n",
    "### The SQL that actually runs\n",
    "\n",
    "The function `set_sql_debug(True)` is wider than `get_sql`, which shows one query: until `set_sql_debug(False)`, Pony prints every SQL command as it sends it to the database, with a few lines about the connection. Here it shows what following a relation costs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "c121",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.582172Z",
     "iopub.status.busy": "2026-11-14T21:13:30.581990Z",
     "iopub.status.idle": "2026-11-14T21:13:30.586141Z",
     "shell.execute_reply": "2026-11-14T21:13:30.585048Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GET CONNECTION FROM THE LOCAL POOL\n",
      "SWITCH TO AUTOCOMMIT MODE\n",
      "SELECT \"id\", \"code\", \"name\", \"income_level\"\n",
      "FROM \"Country\"\n",
      "WHERE \"code\" = ?\n",
      "LIMIT 2\n",
      "['NOR']\n",
      "\n",
      "SELECT COUNT(*)\n",
      "FROM \"Observation\"\n",
      "WHERE \"country\" = ?\n",
      "[4]\n",
      "\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "with db_session:\n",
    "    set_sql_debug(True)\n",
    "    norway = Country.get(code='NOR')\n",
    "    print(norway.observations.count())\n",
    "    set_sql_debug(False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c122",
   "metadata": {},
   "source": [
    "### A database that already exists\n",
    "\n",
    "A database file that exists already, made by another program, is connected with its file name: `geo.bind(provider='sqlite', filename='wdi_extract.db')`. Without the argument `create_db=True`, Pony does not create the file, so a wrong file name is an error and not a new empty database. The call `generate_mapping()` without `create_tables=True` creates nothing: it checks that the tables of the file exist with the names and columns that the classes describe, and it stops with an error if they do not match.\n",
    "\n",
    "The block below is shown and not run, because it needs the file. We made the file `wdi_extract.db` in advance, from the classes of this section with `create_db=True`:\n",
    "\n",
    "```python\n",
    "geo = Database()\n",
    "geo.bind(provider='sqlite', filename='wdi_extract.db')\n",
    "\n",
    "# the classes Country and Observation, exactly as in the first box\n",
    "\n",
    "geo.generate_mapping()\n",
    "\n",
    "with db_session:\n",
    "    israel = Country.get(code='ISR')\n",
    "    print(israel.name, israel.observations.count())\n",
    "```\n",
    "\n",
    "```text\n",
    "Israel 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c123",
   "metadata": {},
   "source": [
    "> **Self-study, importance 1.** This part is for self-study: it is not taught in the lecture, and you read it on your own. Loading rows from a CSV file, the practice tasks and the summary of the lesson. It helps with: creating many objects from the rows of a file."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c124",
   "metadata": {},
   "source": [
    "### Rows from a file\n",
    "\n",
    "A table often arrives as a [CSV file](https://dvirross.com/courses/intro-data-science/python-values-and-collections#data-file-formats), with the names of the columns on the first line. The file `world-bank-more-countries.csv` has the same three indicators, with full values and no rounding, for four more countries, for the years 2000 and 2020, with one line for each country and year. The source and the license are those of the extract above; the first two indicators in the file were retrieved on 5 November 2026 and the population on 8 November 2026. The GDP per capita of Eritrea for 2020 is missing in the source, so that field in the file is empty.\n",
    "\n",
    "Python reads such a file with the module `csv`. The function `open(name, newline='', encoding='utf-8')` opens a file, and a `with` block closes it when the block ends; the option `newline=''` is what the module `csv` asks for. The function `csv.DictReader(file)` goes over the lines after the first one, and gives each line as a [dictionary](https://dvirross.com/courses/intro-data-science/glossary#dictionary) whose keys are the names of the columns. Every value that comes from a file is text, even a number, and an empty field is the empty text `''`. The function `int(text)` makes a whole number from text, and `float(text)` makes a number with a decimal point."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "c125",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.588048Z",
     "iopub.status.busy": "2026-11-14T21:13:30.587845Z",
     "iopub.status.idle": "2026-11-14T21:13:30.594366Z",
     "shell.execute_reply": "2026-11-14T21:13:30.592779Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n",
      "Chile 20002000\n",
      "Chile 2001\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "import csv\n",
    "\n",
    "with open(\n",
    "    'world-bank-more-countries.csv', newline='', encoding='utf-8'\n",
    ") as file:\n",
    "    rows = list(csv.DictReader(file))\n",
    "\n",
    "print(len(rows))\n",
    "print(rows[0]['name'], rows[0]['year'] * 2)\n",
    "print(rows[0]['name'], int(rows[0]['year']) + 1)\n",
    "print(rows[7]['gdp_per_capita'] == '')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c126",
   "metadata": {},
   "source": [
    "The year is text, so repeating it twice joins two copies of the text, and only `int(...)` makes it a number that can be added to. A missing value must not become a number: an empty field becomes `None` with a conditional expression, `float(text) if text != '' else None`.\n",
    "\n",
    "Loading the lines into entities is the loop of [Create the objects and connect them](#create-the-objects-and-connect-them), with `row['code']` in place of the unpacked code. A `Country` is created only the first time that its code appears: the test `code not in countries` is true when the dictionary has no key `code` yet. The method `get` takes several conditions at once: `Observation.get(year=2020, country=some_country)` returns the one observation that matches all of them.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**Your turn.** Create a database object `wb_db` in memory, as in this section. Then write two entities, in this order. `Economy` has the attributes `code` and `name`, each a text that must have a value, and `readings`, a set of `Reading` objects. `Reading` has `indicator` (a text that must have a value), `year` (a whole number that must have a value), `value` (a number with a decimal point that may be missing) and `economy` (an `Economy` object that must have a value). Then create the tables with `generate_mapping` and call `show(Reading)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "c127",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.598755Z",
     "iopub.status.busy": "2026-11-14T21:13:30.598581Z",
     "iopub.status.idle": "2026-11-14T21:13:30.602220Z",
     "shell.execute_reply": "2026-11-14T21:13:30.600867Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c128",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "class Reading(Entity):\n",
    "    id = PrimaryKey(int, auto=True)\n",
    "    indicator = Required(str)\n",
    "    year = Required(int)\n",
    "    value = Optional(float)\n",
    "    economy = Required(Economy)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "c129",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.603899Z",
     "iopub.status.busy": "2026-11-14T21:13:30.603742Z",
     "iopub.status.idle": "2026-11-14T21:13:30.607270Z",
     "shell.execute_reply": "2026-11-14T21:13:30.606147Z"
    }
   },
   "outputs": [],
   "source": [
    "check(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c130",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Each class is written with `(wb_db.Entity)` after its name. `Reading` is named inside `Set(...)` in quotes, because it is defined below `Economy`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c131",
   "metadata": {},
   "source": [
    "**Your turn.** The classes `Economy` and `Reading` below are ready, `names` holds the name of each code, and `rows` holds real readings of two economies: South Africa (`ZAF`) and Syria (`SYR`), whose GDP for 2000 is missing in the source. In a `with db_session:` block, create a dictionary `economies` whose keys are the codes and whose values are `Economy` objects, then create a `Reading` for each row, connected to its economy through the dictionary. Then print, for each code in the dictionary, the code and the number of its readings, with `count()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "c132",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.609350Z",
     "iopub.status.busy": "2026-11-14T21:13:30.609166Z",
     "iopub.status.idle": "2026-11-14T21:13:30.616688Z",
     "shell.execute_reply": "2026-11-14T21:13:30.614737Z"
    }
   },
   "outputs": [],
   "source": [
    "wb_db = Database()\n",
    "wb_db.bind(provider='sqlite', filename=':memory:')\n",
    "\n",
    "class Economy(wb_db.Entity):\n",
    "    code = Required(str)\n",
    "    name = Required(str)\n",
    "    readings = Set('Reading')\n",
    "\n",
    "class Reading(wb_db.Entity):\n",
    "    indicator = Required(str)\n",
    "    year = Required(int)\n",
    "    value = Optional(float)\n",
    "    economy = Required(Economy)\n",
    "\n",
    "wb_db.generate_mapping(create_tables=True)\n",
    "names = {'ZAF': 'South Africa', 'SYR': 'Syrian Arab Republic'}\n",
    "rows = [\n",
    "    ('ZAF', 'life', 2000, 58.368),\n",
    "    ('ZAF', 'life', 2020, 65.15),\n",
    "    ('ZAF', 'gdp', 2020, 12671.0862436851),\n",
    "    ('SYR', 'life', 2000, 70.856),\n",
    "    ('SYR', 'life', 2020, 71.944),\n",
    "    ('SYR', 'gdp', 2000, None),\n",
    "    ('SYR', 'gdp', 2020, 3878.42802993832),\n",
    "]\n",
    "\n",
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c133",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "ZAF <number>\n",
    "SYR <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "c134",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.618923Z",
     "iopub.status.busy": "2026-11-14T21:13:30.618763Z",
     "iopub.status.idle": "2026-11-14T21:13:30.624539Z",
     "shell.execute_reply": "2026-11-14T21:13:30.623277Z"
    }
   },
   "outputs": [],
   "source": [
    "check(11)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c135",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> In a `with db_session:` block, first loop over `names` and put `Economy(code=..., name=...)` in the dictionary under each code. Then loop over `rows`, and pass `economy=economies[code]` to `Reading`. A last loop over `economies` prints the code and `economies[code].readings.count()`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c136",
   "metadata": {},
   "source": [
    "**Your turn.** The box below stores the economy with the code `'ZAF'` and three of its readings. In a new `with db_session:` block, get that economy with `Economy.get(code='ZAF')` and print the change in its life expectancy between 2000 and 2020, rounded to one digit after the decimal point: the value of 2020 minus the value of 2000, using the readings with the indicator `'life'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "c137",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.626236Z",
     "iopub.status.busy": "2026-11-14T21:13:30.626005Z",
     "iopub.status.idle": "2026-11-14T21:13:30.633123Z",
     "shell.execute_reply": "2026-11-14T21:13:30.631883Z"
    }
   },
   "outputs": [],
   "source": [
    "wb_db = Database()\n",
    "wb_db.bind(provider='sqlite', filename=':memory:')\n",
    "\n",
    "class Economy(wb_db.Entity):\n",
    "    code = Required(str)\n",
    "    name = Required(str)\n",
    "    readings = Set('Reading')\n",
    "\n",
    "class Reading(wb_db.Entity):\n",
    "    indicator = Required(str)\n",
    "    year = Required(int)\n",
    "    value = Optional(float)\n",
    "    economy = Required(Economy)\n",
    "\n",
    "wb_db.generate_mapping(create_tables=True)\n",
    "\n",
    "rows = [\n",
    "    ('life', 2020, 65.15),\n",
    "    ('life', 2000, 58.368),\n",
    "    ('gdp', 2020, 12671.0862436851),\n",
    "]\n",
    "\n",
    "with db_session:\n",
    "    zaf = Economy(code='ZAF', name='South Africa')\n",
    "    for indicator, year, value in rows:\n",
    "        Reading(\n",
    "            indicator=indicator, year=year,\n",
    "            value=value, economy=zaf\n",
    "        )\n",
    "\n",
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c138",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>.<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "c139",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.635186Z",
     "iopub.status.busy": "2026-11-14T21:13:30.634982Z",
     "iopub.status.idle": "2026-11-14T21:13:30.641552Z",
     "shell.execute_reply": "2026-11-14T21:13:30.639939Z"
    }
   },
   "outputs": [],
   "source": [
    "check(12)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c140",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> The set `readings` of the economy has the methods `select` and `order_by`. Keep the readings whose indicator is `'life'`, sort them by year, and subtract the value at index `[0]` from the value at index `[1]`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c141",
   "metadata": {},
   "source": [
    "**Your turn.** The classes `FileCountry` and `FileObservation` on the database `file_db` below are ready, and the file `world-bank-more-countries.csv` is in the working folder. Read the file with `csv.DictReader`. In a `with db_session:` block, create a dictionary `countries` from each code to its `FileCountry` object, creating each country once, and create an `FileObservation` for each line, with the year and the population as whole numbers, and the life expectancy and the GDP per capita as numbers with a decimal point, or `None` when the field is empty. Print the number of countries and the number of observations on one line, separated by a space, and on the next line the GDP per capita of Eritrea (`ERI`) in 2020."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "c142",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.643437Z",
     "iopub.status.busy": "2026-11-14T21:13:30.643279Z",
     "iopub.status.idle": "2026-11-14T21:13:30.648633Z",
     "shell.execute_reply": "2026-11-14T21:13:30.647530Z"
    }
   },
   "outputs": [],
   "source": [
    "file_db = Database()\n",
    "file_db.bind(provider='sqlite', filename=':memory:')\n",
    "\n",
    "class FileCountry(file_db.Entity):\n",
    "    code = Required(str)\n",
    "    name = Required(str)\n",
    "    income_level = Required(str)\n",
    "    observations = Set('FileObservation')\n",
    "\n",
    "class FileObservation(file_db.Entity):\n",
    "    year = Required(int)\n",
    "    life_expectancy = Optional(float)\n",
    "    gdp_per_capita = Optional(float)\n",
    "    population = Optional(int)\n",
    "    country = Required(FileCountry)\n",
    "\n",
    "file_db.generate_mapping(create_tables=True)\n",
    "\n",
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c143",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number> <number>\n",
    "None\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "c144",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-14T21:13:30.650681Z",
     "iopub.status.busy": "2026-11-14T21:13:30.650507Z",
     "iopub.status.idle": "2026-11-14T21:13:30.655889Z",
     "shell.execute_reply": "2026-11-14T21:13:30.654516Z"
    }
   },
   "outputs": [],
   "source": [
    "check(13)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c145",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> Import `csv`, open the file as in the box above, and make a list of the lines with `list(csv.DictReader(file))`. In the block, loop over the lines: create the `FileCountry` only when its code is not yet a key of `countries`, and always create the `FileObservation`, with `country=countries[code]`. The last line is `FileObservation.get(...)` with the country and the year, and then the attribute `gdp_per_capita`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c146",
   "metadata": {},
   "source": [
    "## Keep in mind\n",
    "\n",
    "- A **one-to-many relation** is a foreign key seen from both sides: `Required(Country)` or `Optional(Country)` on the many side, `Set('Observation')` on the one side. A dot follows it in both directions, and inside a query a dot such as `o.country.income_level` makes Pony write the join.\n",
    "- `Optional(float)` allows a missing value, which is `None`; test it with `is None` before calculating. A missing value is not zero.\n",
    "- A dictionary from a code to an object (`countries[code]`) connects new objects to the right related object.\n",
    "- `csv.DictReader` reads a CSV file: every value is text, so convert it with `int(...)` or `float(...)`, and turn an empty field into `None`.\n",
    "- `show(Entity)` prints how Pony understood an entity, and `set_sql_debug(True)` prints every SQL command that runs. To use a database file that exists, `bind` it without `create_db=True` and call `generate_mapping()` without `create_tables=True`."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
