Bancos de Dados Relacionais (SQL) na AWS com Amazon RDS.

Overview

Bancos de Dados Relacionais (SQL) na AWS com Amazon RDS

     Explorando o Amazon RDS, um serviço de provisionamente e gerenciamento de banco de dados relacional na AWS.

Serviços utilizados
     Amazon RDS;
     AWS Lambda; e
     MySQL Workbench.

O que é um banco de dados relacional?
     Um banco de dados relacional é um mecanismo de armanezamento que permite a persistência de dados e opcionalmente implementar funcionalidades, armazenando os dados em tabelas, que possuem relacionamentos entre si.

Tabelas de um banco de dados relacional
     São organizadas em colunas, onde cada coluna armazena um tipo de dados;
     Os dados são armazenados em linhas da tabela;
     Possuem uma chave primária (PK) que identificam de forma única cada registro de uma linha;
     Possuem chaves estrangeiras (FK) que estabelecem o relacionamento entre tabelas; e
     Utilizam índices para pesquisa rápida de dados.

Relacionamento entre tabelas em um banco de dados relacional
     1:1 duas tabelas se relacionam de forma direta onde a chave primária de uma tabela é utilizada uma única vez em outra.
     1:n duas tabelas se relacionam de forma direta onde a chave primária de uma tabela é utilizada várias vezes em outra.
     n:n acontece de forma indireta entre duas tabelas, gerando de uma terceira tabela. Na prática ocorrem dois ou mais relacionamentos um para vários.

Sobre o Amazon RDS
     O Amazon Relational Database Service (Amazon RDS) facilita a configuração, a operação e a escalabilidade de bancos de dados relacionais na nuvem. Fornece capacidade econômica e redimensionável e automiza o provisionamento de hardware, configuração de bancos de dados, aplicação de patches e backups.

Mecanismos de banco de dados na Amazon RDS: Amazon Aurora, PostgreSQL, MySQL, MariaDB, Oracle e SQL Server.

Preços do Amazon RDS
     Preços baseados na dimensão de instâncias EC2
     Free tier: 750 horas de uso de instâncias db.t2.micro Single-AZ do Amazon RDS, 20 GB de armazenamento de banco de dados de SSD e 20 GB de armanezamento de backup.

Documentação da AWS sobre o Amazon RDS

Atividade prática
     Criar uma instância RDS;
     Acessar com o MySQ Workbench e criar tabelas e inserir dados;
     Criar uma função Lambda para consultar dados em tabelas do RDS; e
     Código do instrutor

Arquitetura de Tabelas

Arquitetura de Sistemas

Criando queries

  • Criar um database:
CREATE DATABASE PERMISSIONS_DB;
  • Acessar o db criado:
USE PERMISSIONS_DB;
  • Criar uma tabela de usuários:
CREATE TABLE user (
  id bigint(20) NOT NULL, 
  email varchar(40) NOT NULL,
  username varchar(15) NOT NULL,
  password varchar(100) NOT NULL,
  PRIMARY KEY (id)
);
  • Criar uma tabela de carrinho de compras:
CREATE TABLE role (
  id bigint(20) NOT NULL,
  name varchar(60) NOT NULL, 
  PRIMARY KEY (id)
);
  • Criar uma tabela user roles:
CREATE TABLE user_roles (
  user_id bigint(20) NOT NULL,
  role_id bigint(20) NOT NULL,
  FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE RESTRICT ON UPDATE CASCADE,
  FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE RESTRICT ON UPDATE CASCADE,
  PRIMARY KEY (user_id, role_id)
);
  • Descrição da tabela:
DESC user
  • Inserindo dados em tabelas:
INSERT INTO user VALUES (1, '[email protected]', 'Lucas', 'strongpasswd');
INSERT INTO user VALUES (2, '[email protected]', 'Igla', 'strongpasswd');

INSERT INTO role VALUES (3, 'ADMIN');
INSERT INTO role VALUES (4, 'USER');

INSERT INTO user_roles VALUES (1, 3);
INSERT INTO user_roles VALUES (1, 4);
INSERT INTO user_roles VALUES (2, 4);
  • Verificando:
SELECT * FROM user_roles;
  • Selecionando dados da tabela associativa:
SELECT user.id, user.email, user.username, role.id AS role_id, role.name AS role_name
FROM user 
JOIN user_roles on (user.id=user_roles.user_id)
JOIN role on (role.id=user_roles.role_id);

Configurando permissões de acesso ao RDS
     Selecionar a função criada -> Configuration -> Permissions -> Selecionar a função criada e abrir no console do AWS IAM; e
     Attach policies -> Pesquisar pela policy AWSLambdaVPCAccessExecutionRole -> Attach policy.

import json
import pymysql

endpoint = 'endpoint-name'
username = 'user-name'
password = 'user-password'
database_name = 'db-name'

connection = pymysql.connect(host=endpoint, user=username, password=password, db=database_name)

def lambda_handler(event, context):
    
    cursor = connection.cursor()
    
    cursor.execute('SELECT user.id, user.email, user.username, role.id AS role_id, role.name AS role_name FROM user JOIN user_roles on (user.id=user_roles.user_id)JOIN role on (role.id=user_roles.role_id)')
    
    rows = cursor.fetchall()
    
    return {
        'statusCode': 200,
        'body': json.dumps(rows)
    }

Comando pip - Solução

pip install pymysql -t .
explorer .
Owner
Lucas Magalhães
“Talk is cheap. Show me the code.”
Lucas Magalhães
Yet another random discord bot.

YARDB (r!) Yet another fully functional and random discord bot. I might add more features if I'm bored also don't criticize on my code. Commands: 4 Di

kayle 1 Oct 21, 2021
Telegram group manager moderen and simple.

Upin Robot A Advanced Powerful, Smart And Intelligent Group Management Bot With New And Powerful Features ... Written with Pyrogram and Telethon... If

Muhammad Nawawi 3 Dec 23, 2021
Thread-safe Python RabbitMQ Client & Management library

AMQPStorm Thread-safe Python RabbitMQ Client & Management library. Introduction AMQPStorm is a library designed to be consistent, stable and thread-sa

Erik Olof Gunnar Andersson 167 Nov 20, 2022
Home Assistant custom integration for controlling Powered by Tuya (PBT) devices using Tuya Open API, officially maintained by the Tuya Developer Team.

Tuya Home Assistant Integration Home Assistant custom integration for controlling Powered by Tuya (PBT) devices using Tuya Open API, officially mainta

Tuya 704 Jan 03, 2023
KiKi bare dogs can share your joys and sorrows with you.

Kiki-FangLee-DiscordBot KiKi bare dogs can share your joys and sorrows with you. $help: Kiki will show you my talent, aw-aw. $list: Show Kiki's knowle

Fang Lee 0 Feb 12, 2022
A Telegram Userbot to play Audio and Video songs / files in Telegram Voice Chats

TG-MusicPlayer A Telegram Userbot to play Audio and Video songs / files in Telegram Voice Chats. It's made with PyTgCalls and Pyrogram Requirements Py

Mᴏᴏɴʟɪɢʜᴛ 4 Dec 14, 2022
Available slots checker for Spanish Passport

Bot that checks for available slots to make an appointment to issue the Spanish passport at the Uruguayan consulate page

1 Nov 30, 2021
fhempy is a FHEM binding to write modules in Python language

fhempy (BETA) fhempy allows the usage of Python 3 (NOT 2!) language to write FHEM modules. Python 3.7 or higher is required, therefore I recommend usi

Dominik 27 Dec 14, 2022
Instagram - Instagram Account Reporting Tool

Instagram Instagram Account Reporting Tool Installation On Termux $ apt update $

Aryan 6 Nov 18, 2022
Fun telegram bot =)

Recolor Bot About Fun telegram bot, that can change your hair color. Preparations Update package lists sudo apt-get update; Make sure Git and docker-c

Just Koala 4 Jul 09, 2022
Github action for automatically determine the version for next release by using repository tags

This action will automatically determine the version for next release by using repository tags

Igor Gov 7 Oct 25, 2022
Bot per controllare la disponibilità di appuntamenti per la vaccinazione Covid-19 in Veneto

VaxBot9000 Prerequisites Python 3.9 Poetry latest version of geckodriver Firefox Setup poetry install Copy config.sample.toml to config.toml and edit

Augusto Zanellato 5 Jun 13, 2021
Python library for the DeepL language translation API.

The DeepL API is a language translation API that allows other computer programs to send texts and documents to DeepL's servers and receive high-quality translations. This opens a whole universe of op

DeepL 535 Jan 04, 2023
A bot i made for a dead com server lol it gets updated daily etc

6ix-Bot-Source A bot i made for a dead com server lol it gets updated daily etc For The UserAgent CMD https://developers.whatismybrowser.com/ thats a

Swiper 9 Mar 10, 2022
This is Telegram Files Store Bot by @AbirHasan2005

PyroFilesStoreBot This is Telegram Parmanent Files Store Bot by @AbirHasan2005. Language: Python3 Library: Pyrogram Features: In PM Just Forward or Se

Abir Hasan 168 Dec 19, 2022
Telegram bot for stream music or video on telegram

KYURA MUSIC Telegram bot for stream music or video on telegram, powered by PyTgCalls and Pyrogram Help Need Help me to translate this repo, click the

0 Dec 08, 2022
tgEasy's Official Assistant Bot and Example Bot

tgEasy Assistant The assistant bot that helps people with tgEasy directly on Telegram. This repository contains the source code of @tgEasyRobot and th

Divide Projects™ 4 Dec 26, 2022
Telegram bot implementing Lex Arcana using python-telegram-bot library.

Lex Arcana Telegram Bot 🤖 Telegram bot implementing Lex Arcana using python-telegram-bot library. This bot was evaluated for the course "Computer Eng

Nicolò Sonnino 6 Jun 22, 2022
Tsar-Bot - Crypto auto trade bot that use sentiment analysis from twitter

Tsar Bot - Crypto Sentiment Bot Tsar Bot is a Twitter Crypto Sentiment Bot that

Hilmi Azizi 26 Dec 15, 2022
API de mi aplicación de Biblioteca

BOOKSTORE API Instalación/Configuración Previo Es una buena idea crear un entorno virtual antes de instalar las dependencias. Puedes hacerlo con el si

Gabriel Morales 1 Jan 09, 2022