6.5. SQL Alter

6.5.1. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Database Alter Table
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3

# %% English
# 1. Write SQL query to add column:
#    - table: `contacts`
#    - column: `group`
#    - type: text
#    - default: guest
# 2. Run doctests - all must succeed

# %% Polish
# 1. Napisz zapytanie SQL aby dodać kolumnę:
#    - tabela: `contacts`
#    - kolumna: `group`
#    - type: text
#    - wartość domyślna: guest
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> from pathlib import Path
>>> import sqlite3

>>> database = Path(__file__).parent.parent / 'shop.db'
>>> db = sqlite3.connect(database)
>>> try:
...     _ = db.execute(result)
...     db.commit()
... except sqlite3.OperationalError as e:
...    assert 'duplicate column name: group' in str(e)

>>> PRAGMA = '''
...     SELECT
...         `m`.`name` AS `table_name`,
...         `p`.`name` AS `col_name`,
...         `p`.`type` AS `col_type`,
...         `p`.`pk` AS `col_is_pk`,
...         `p`.`dflt_value` AS `col_default_val`,
...         `p`.[notnull] AS `col_is_not_null`
...     FROM `sqlite_master` AS `m`
...     LEFT OUTER JOIN `pragma_table_info`((`m`.`name`)) AS `p`
...                  ON `m`.`name` != `p`.`name`
...     WHERE `m`.`type` = 'table'
...     ORDER BY `table_name`
... '''

>>> pragma = db.execute(PRAGMA).fetchall()
>>> assert ('contacts', 'group', 'TEXT', 0, 'guest', 0) in pragma

>>> db.close()
"""

# Write SQL query to add column:
# - table: `contacts`
# - column: `group`
# - type: text
# - default: guest
# type: str
result = """

-- replace this comment
-- with your sql query

"""