|
| 1 | +""" |
| 2 | +This module demonstrates the use of SQLAlchemy's Core functionality for |
| 3 | + building and executing database queries. |
| 4 | +The example shows how to define table schemas and perform queries using the |
| 5 | + SQLAlchemy Core expression language. |
| 6 | +It provides functionality to query books based on author names from a |
| 7 | + structured database. |
| 8 | +""" |
| 9 | + |
| 10 | +from typing import Any, Sequence |
| 11 | + |
| 12 | +from sqlalchemy import ( |
| 13 | + Column, |
| 14 | + Engine, |
| 15 | + ForeignKey, |
| 16 | + Integer, |
| 17 | + MetaData, |
| 18 | + Row, |
| 19 | + Select, |
| 20 | + String, |
| 21 | + Table, |
| 22 | + create_engine, |
| 23 | + select, |
| 24 | +) |
| 25 | + |
| 26 | +engine: Engine = create_engine( |
| 27 | + "mysql+pymysql://user:password@server/database", |
| 28 | +) |
| 29 | +metadata: MetaData = MetaData() |
| 30 | +authors: Table = Table( |
| 31 | + "authors", |
| 32 | + metadata, |
| 33 | + Column( |
| 34 | + "id", |
| 35 | + Integer, |
| 36 | + primary_key=True, |
| 37 | + ), |
| 38 | + Column( |
| 39 | + "name", |
| 40 | + String, |
| 41 | + ), |
| 42 | +) |
| 43 | +books: Table = Table( |
| 44 | + "books", |
| 45 | + metadata, |
| 46 | + Column( |
| 47 | + "id", |
| 48 | + Integer, |
| 49 | + primary_key=True, |
| 50 | + ), |
| 51 | + Column( |
| 52 | + "title", |
| 53 | + String, |
| 54 | + ), |
| 55 | + Column( |
| 56 | + "author_id", |
| 57 | + Integer, |
| 58 | + ForeignKey("authors.id"), |
| 59 | + ), |
| 60 | + Column( |
| 61 | + "year", |
| 62 | + Integer, |
| 63 | + ), |
| 64 | +) |
| 65 | + |
| 66 | + |
| 67 | +def fetch_books_by_author( |
| 68 | + author_name: str, |
| 69 | +) -> Sequence[Row[Any]]: |
| 70 | + """ |
| 71 | + Retrieves all books written by the specified author. |
| 72 | + :param author_name: The name of the author whose books to find. |
| 73 | + :type author_name: str |
| 74 | + :return: A list of all books from the given author name |
| 75 | + :rtype: Sequence[Row[Any]] |
| 76 | + """ |
| 77 | + select_statement: Select[Any] = ( |
| 78 | + select([books.c.title, books.c.year]) # type: ignore |
| 79 | + .select_from(books.join(authors)) |
| 80 | + .where(authors.c.name == author_name) |
| 81 | + ) |
| 82 | + with engine.connect() as connection: |
| 83 | + return connection.execute( |
| 84 | + select_statement, |
| 85 | + ).fetchall() |
| 86 | + |
| 87 | + |
| 88 | +books_by_author: list[Row[Table]] = list( # type: ignore |
| 89 | + fetch_books_by_author("Gabriel García Márquez") |
| 90 | +) |
| 91 | +for book in books_by_author: |
| 92 | + print(book) |
0 commit comments