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
List of twitch bots n bigots

This is a collection of bot account names NamelistMASTER contains all the names we reccomend you ban in your channel Sometimes people get on that list

62 Sep 05, 2021
Simple, yet effective moderator bot for telegram. With reports, logs, profanity filter and more :3

👹 Samurai Telegram Bot Simple, yet effective moderator bot for telegram. With reports, logs, profanity filter and more :3 Description Personal bot, m

Abraham Tugalov 106 Dec 13, 2022
Parse 11.000 free proxies!

Proxy Machine Description I did this project in order to boost views with the teleboost ✈️ in my Telegram channel. You can use it not only for boostin

VLDSLV 77 Jan 08, 2023
A combination between python-flask, that fetch and send data from league client during champion select thanks to LCU

A combination between python-flask, that fetch data and send from league client during champion select thanks to LCU and compare picked champs to the gamesDataBase that we need to collect using my ot

Anas Hamrouni 1 Jan 19, 2022
Opencontactbook - Bulk-manage large numbers of vCard contacts with built-in geolocation

Open Contact Book Open Contact Book is a buiness-oriented, cross-platform, Pytho

Aurélien PIERRE 2 Aug 08, 2022
A module grouping multiple translation APIs

translatepy (originally: translate) An aggregation of multiple translation API Translate, transliterate, get the language of texts in no time with the

349 Jan 06, 2023
An API wrapper for discord; maintained and improved from discord.py

Fusion.py Documentation What is Fusion.py you might ask; Fusion.py is a Discord.py fork that has most of the good features from most of the big Discor

Senarc Studios 5 Apr 19, 2022
SUPPORTS 500 GROUPS NO NEED OF BOT 😉

LOVELY RADIO SUPPORTS 500 GROUPS NO NEED OF BOT 😉 Requirements Telegram API_ID , API_HASH and SESSION_NAME HEROKU Get YouTube live stream link instal

6 Nov 24, 2021
微信支付接口V3版python库

wechatpayv3 介绍 微信支付接口V3版python库。 适用对象 wechatpayv3支持微信支付直连商户,接口说明详见 官网。 特性 平台证书自动更新,无需开发者关注平台证书有效性,无需手动下载更新; 支持本地缓存平台证书,初始化时指定平台证书保存目录即可。 适配进度 微信支付V3版A

chen gang 258 Jan 06, 2023
This is a script to export logs from AWS CloudTrail to a local file.

cloudtrail-export-logs This is a script to export logs from AWS CloudTrail to a local file. Getting Started Prerequisites python 3 boto3 pip Installin

Claick Assunção de Oliveira 2 Jan 02, 2022
A Twitter Bot that retweets and likes tweets with the hashtag #girlscriptwoc and #girlscript, and also follows the user.

GirlScript Winter of Contributing Twitter Bot A Twitter Bot that retweets and likes tweets with the hashtag #girlscriptwoc and #girlscript, and also f

Pranay Gupta 9 Dec 15, 2022
Simple progressbar for discord

⚙️ DiscordProgressbar 📂 Установка | Installation pip install discordbar 📚 Документация | Documentation 📞 Связаться со мной | Сontact with me 📜 Ли

DenyS 26 Nov 30, 2022
iCloudPy is a simple iCloud webservices wrapper library written in Python

iCloudPy 🤟 Please star this repository if you end up using the library. It will help me continue supporting this product. 🙏 iCloudPy is a simple iCl

Mandar Patil 49 Dec 26, 2022
Automatic login to Microsoft Teams conferences

Automatic login to Microsoft Teams conferences

Xhos 1 Jan 24, 2022
Stock market bot that will be used to learn about API calls and database connections.

Stock market bot that will be used to learn about API calls and database connections.

1 Dec 24, 2021
A multi-tenant multi-client scalable product categorising demo stack

Better Categories 4All: A multi-tenant multi-client product categorising stack The steps to reproduce training and inference are in the end of this fi

7 Feb 15, 2022
Python binding for Terraform.

Python libterraform Python binding for Terraform. Installation $ pip install libterraform NOTE Please install version 0.3.1 or above, which solves the

Prodesire 28 Dec 29, 2022
A simple API Wrapper for Guilded.

Guildr A simple API Wrapper for Guilded. Frequently updated! I am not a user of Guilded, meaning I do not keep track of new Guilded updates or patches

2 Mar 07, 2022
You can connect with Sanila Ranatunga using this bot😉😉

Sanila-Ranatunga-s-Assistant-Bot You can connect with Sanila Ranatunga using this bot 😉 😉 Reach me on Telegram Sanila's Assistant Bot What is Telegr

Sanila Ranatunga 5 Feb 01, 2022
SkyzoMusicBot - Bot Music Telegram By Skyzo

SKYZO MUSIC BOT Telegram Music Bot And Stream Feature New Version Ready to use m

Skyzo 19 Apr 08, 2022