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
python based bot Sends notification to your telegram whenever a new video is released on a youtube channel!

YTnotifier python based bot Sends notification to your telegram whenever a new video is released on a youtube channel! REQUIREMENTS telethon python-de

Mohamed Rizad 6 Jul 23, 2022
A client interface for Scrapinghub's API

Client interface for Scrapinghub API The scrapinghub is a Python library for communicating with the Scrapinghub API. Requirements Python 2.7 or above

Scrapinghub 184 Sep 28, 2022
Innocent-Bot - A Discord client self-bot for destroying, nuking and causing mischief in servers

Innocent-bot A Discord client self-bot for destroying, nuking and causing mischi

†† 5 Jan 26, 2022
Add members to unlimited telegram channels and groups

Program Features 📌 Coded with Python version 10. 📌 without the need for a proxy. 📌 without the need for a Telegram ID. 📌 Ability to add infinite p

hack4lx 10 Nov 25, 2022
Discord Bot written in Python that plays music in your voice channel

Discord Bot that plays music! I decided to create a simple Discord bot using Python in order to advance my coding skills. Please don't ask me for help

Eric Yeung 39 Jan 01, 2023
Manage gmail account using python, forget about imap and just code what you supposed to do.

GGmail Manage gmail account using python, forget about imap and just code what you supposed to do. Help See documentation for more details. Install In

Dylan Do Amaral 6 Sep 23, 2022
Search all history of Chrome in terminal

Chrotry Search all history of Chrome in terminal. Demo Usages Move the Chrome history file to current directory by running move_history.sh Rename hist

Xiaoxu HU 2 Jun 13, 2022
Rhythm bot clone for discord written in Python and uses YouTube to get media files.

Tunebot About Rhythm bot clone for discord written in Python and uses YouTube to get media files. Usage You need a .env file within the same directory

1 Oct 21, 2021
Morpy Bot Linux - Morpy Bot Linux With Python

Morpy_Bot_Linux Guide to using the robot : 🔸 Lsmod = to identify admins and st

2 Jan 20, 2022
Powerful Telegram userbot to turn your PROFILE PICTURE & LAST NAME into a real time clock & to change your BIO automatically.

DATE_TIME_USERBOT-TeLeTiPs Powerful Telegram userbot to turn your PROFILE PICTURE & LAST NAME into a real time clock & to change your BIO automaticall

53 Jan 05, 2023
A Discord bot for osu!

This is the mostly-complete repo for the owo Discord osu! bot which you can invite here. As you look through this repo, please keep in mind that all o

Stevy 43 Dec 28, 2022
This repository contains ready to deploy automations on AWS

aws-automation-plugins This repository contains ready to deploy automations on AWS. How-To All projects in this repository contain a deploy.sh file wh

Akesh Patil 8 Sep 20, 2022
Cyber Userbot

Cyber Userbot

Irham 0 May 26, 2022
Crypto Signal Provider - A web application that allows users to select a cryptocurrency

Crypto_Signal_Provider This is a web application that allows users to select a c

Raul 2 Dec 11, 2022
ABACUS Aroio API for Webinterfaces and App-Connections

ABACUS Aroio API for Webinterfaces and App-Connections Setup Start virtual python environment if you don't have python3 running setup: $ python3 -m ve

Abacus Aroio Developer Team 1 Apr 01, 2021
Deezer client for python

Deezer Python Client A friendly Python wrapper around the Deezer API. Installation The package is published on PyPI and can be installed by running: p

Bruno Alla 103 Dec 19, 2022
Crud-python-sqlite: used to manage telephone contacts through python and sqlite

crud-python-sqlite This program is used to manage telephone contacts through python and sqlite. Dependencicas python3 sqlite3 Installation Clone the r

Luis Negrón 0 Jan 24, 2022
An async-ready Python wrapper around FerrisChat's API.

FerrisWheel An async-ready Python wrapper around FerrisChat's API. Installation Instructions Linux: $ python3.9 -m pip install -U ferriswheel Python 3

FerrisChat 8 Feb 08, 2022
Fully Dockerized cryptocurrencies Trading Bot, based on Freqtrade engine. Multi instances.

Cryptocurrencies Trading Bot - Freqtrade Manager This automated Trading Bot is based on the amazing Freqtrade one. It allows you to manage many Freqtr

Cédric Dugat 47 Dec 06, 2022
Complete portable pipeline for masking of Aadhaar Number adhering to Govt. Privacy Guidelines.

Aadhaar Number Masking Pipeline Implementation of a complete pipeline that masks the Aadhaar Number in given images to adhere to Govt. of India's Priv

1 Nov 06, 2021