Skip to content

Commit

Permalink
feat: implement listar_expedicoes
Browse files Browse the repository at this point in the history
  • Loading branch information
diksown committed Nov 26, 2023
1 parent 72abcfd commit 3d78e60
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/shell.py
Expand Up @@ -4,8 +4,12 @@
import webbrowser

from rich import print
from rich.console import Console

from .conn import CantConnectToDbError, get_db_connection
from .utils import query_to_rich_table

console = Console()


class VueiShell(cmd.Cmd):
Expand Down Expand Up @@ -43,6 +47,10 @@ def _populate_db(self):
print()
self.conn.commit()

def pretty_query(self, query: str):
table = query_to_rich_table(self.cur, query)
return table

def do_apagar_banco(self, arg):
"""Apaga o banco de dados conectado INTEIRO. Use com cuidado!"""
SECONDS = 10
Expand All @@ -56,20 +64,33 @@ def do_apagar_banco(self, arg):

def do_listar_expedicoes(self, arg):
"""Lista expedições disponíveis para reserva."""
print("Expedições disponíveis: Fim do Mundo, Marte, Lua")
try:
table = self.pretty_query(
"""
SELECT EX.ROTA, EX.NAVE, EX.DH_INICIO, ((NV.CAPACIDADE - 1) - COUNT(ET.TURISTA)) AS VAGAS_RESTANTES
FROM EXPEDICAO EX JOIN NAVE NV
ON EX.NAVE = NV.NUMERO_REGISTRO
LEFT JOIN EXPEDICAO_TURISTA ET
ON ET.NAVE = EX.NAVE AND ET.DH_INICIO = EX.DH_INICIO
GROUP BY EX.NAVE, EX.DH_INICIO, NV.CAPACIDADE
HAVING COUNT(ET.TURISTA) < NV.CAPACIDADE - 1
AND CURRENT_DATE < EX.DH_INICIO;"""
)
console.print(table)
except Exception as e:
print(e)

def do_listar_turistas(self, arg):
"""Lista todos os turistas."""
try:
self.cur.execute(
table = self.pretty_query(
"""
SELECT NOME, TURISTA.EMAIL
FROM TURISTA JOIN PESSOA
ON TURISTA.EMAIL = PESSOA.EMAIL;
"""
)
for row in self.cur.fetchall():
print(f"[bold]{row[0]}[/bold] [blue]<{row[1]}>[/blue]")
console.print(table)
except Exception as e:
print(e)

Expand Down
18 changes: 18 additions & 0 deletions src/utils.py
@@ -0,0 +1,18 @@
from psycopg2.extensions import cursor
from rich.console import Console
from rich.table import Column, Table


def query_to_rich_table(cursor: cursor, query: str):
cursor.execute(query)
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()

table = Table(show_header=True, header_style="bold magenta")
for col in columns:
table.add_column(col)

for row in data:
table.add_row(*[str(item) for item in row])

return table

0 comments on commit 3d78e60

Please sign in to comment.