Advertisement
ksieradzinski

Untitled

Feb 27th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. import psycopg2
  2. from psycopg2.extras import RealDictCursor
  3.  
  4.  
  5. def _get_connection():
  6. return psycopg2.connect(dbname="books", user="postgres", password="Password!")
  7.  
  8.  
  9. def create_tables():
  10. print("Tworzę tabele...")
  11. with _get_connection() as connection:
  12. cursor = connection.cursor()
  13. cursor.execute("""CREATE TABLE IF NOT EXISTS authors(
  14. id SERIAL PRIMARY KEY,
  15. first_name VARCHAR(50) NOT NULL,
  16. last_name VARCHAR(50) NOT NULL
  17. )""")
  18.  
  19. cursor.execute("""CREATE TABLE IF NOT EXISTS books(
  20. id SERIAL PRIMARY KEY,
  21. title VARCHAR(50) NOT NULL,
  22. author_id INTEGER NOT NULL REFERENCES authors(id)
  23. )""")
  24.  
  25.  
  26. def add_author(author_name: str):
  27. try:
  28. first_name, last_name = author_name.split(" ")
  29. print(f"Dodaję autora {first_name} {last_name}.")
  30.  
  31. with _get_connection() as connection:
  32. cursor = connection.cursor()
  33. cursor.execute(
  34. "INSERT INTO authors(first_name, last_name) VALUES(%s,%s)",
  35. (
  36. first_name,
  37. last_name
  38. )
  39. )
  40. connection.commit()
  41. except ValueError:
  42. print("Autor musi posiadać imię i nazwisko np. Henryk Sienkiewicz.")
  43.  
  44.  
  45. def list_authors():
  46. with _get_connection() as connection:
  47. cursor = connection.cursor(cursor_factory=RealDictCursor)
  48. cursor.execute("SELECT id, first_name, last_name FROM authors")
  49. return cursor.fetchall()
  50.  
  51.  
  52. def add_book(title: str, author: str):
  53. first_name, last_name = author.split(" ")
  54. with _get_connection() as connection:
  55. cursor = connection.cursor(cursor_factory=RealDictCursor)
  56. # 1. Pobieram konkretnego autora
  57. author = get_author(first_name, last_name)
  58. # 2. Jeżeli autora nie ma to wyrzucam wyjątek
  59. if author is None:
  60. raise ValueError(f"Nie mam w bazie autora {first_name} {last_name}.")
  61.  
  62. # 3. Dodaję nową książkę
  63. cursor.execute(
  64. "INSERT INTO books(title, author_id) VALUES(%s, %s)",
  65. (title, author["id"])
  66. )
  67.  
  68.  
  69. def get_author(first_name: str, last_name: str):
  70. with _get_connection() as connection:
  71. cursor = connection.cursor(cursor_factory=RealDictCursor)
  72. cursor.execute(
  73. "SELECT id, first_name, last_name FROM authors WHERE first_name=%s AND last_name=%s",
  74. (first_name, last_name)
  75. )
  76. return cursor.fetchone()
  77.  
  78.  
  79. def list_books():
  80. with _get_connection() as connection:
  81. cursor = connection.cursor(cursor_factory=RealDictCursor)
  82. cursor.execute(
  83. """select
  84. authors.first_name,
  85. authors.last_name,
  86. books.title
  87. from authors
  88. inner join books on authors.id=books.author_id"""
  89. )
  90. return cursor.fetchall()
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement