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
A Python wrapper around the Pushbullet API to send different types of push notifications to your phone or/and computer.

pushbullet-python A Python wrapper around the Pushbullet API to send different types of push notifications to your phone or/and computer. Installation

Janu Lingeswaran 1 Jan 14, 2022
Herramienta para transferir eventos de Sucuri WAF hacia Azure Data Tables.

Transfiere eventos de Sucuri hacia Azure Data Tables Script para transferir eventos del Sucuri Web Application Firewall (WAF) hacia Azure Data Tables,

CSIRT-RD 1 Dec 22, 2021
The official wrapper for spyse.com API, written in Python, aimed to help developers build their integrations with Spyse.

Python wrapper for Spyse API The official wrapper for spyse.com API, written in Python, aimed to help developers build their integrations with Spyse.

Spyse 15 Nov 22, 2022
fair-test is a library to build and deploy FAIR metrics tests APIs supporting the specifications used by the FAIRMetrics working group.

☑️ FAIR test fair-test is a library to build and deploy FAIR metrics tests APIs supporting the specifications used by the FAIRMetrics working group. I

Maastricht University IDS 6 Oct 30, 2022
Zaid Vc Player Allows u to steam Songs/music on vc chat

ᴢᴀɪᴅ ᴠᴄ ᴘʟᴀʏᴇʀ 🔥 SORRY FOR OUR PROJECTS DELETED BY GITHUB FLAGGED ᴢᴀɪᴅ ᴠᴄ ᴘʟᴀᴇʀ ɪꜱ ᴀ ᴛᴇʟᴇɢʀᴀᴍ ᴘʀᴏᴊᴇᴄᴛ ʙᴀꜱᴇᴅ ᴏɴ ᴘʏʀᴏɢʀᴀᴍ ꜰᴏʀ ᴘʟᴀʏ ᴍᴜꜱɪᴄꜱ ɪɴ ᴠᴄ ᴄʜᴀᴛꜱ..

Zaid 117 Dec 29, 2022
Simple python program to execute terminal commands on telegram chats directly.

Small python code which can be handy when using telegram and you don't want to use VPS again and again. By configuring the code in your VPS, You can execute commands and get your output within telegr

Veshraj Ghimire 34 Dec 05, 2022
Role Based Access Control for Slack-Bolt Applications

Role Based Access Control for Slack-Bolt Apps Role Based Access Control (RBAC) is a term applied to limiting the authorization for a specific operatio

Jeremy Schulman 7 Jan 06, 2022
Proxy-Bot - Python proxy bot for telegram

Proxy-Bot 🤖 Proxy bot between the main chat and a newcomer, allows all particip

Anton Shumakov 3 Apr 01, 2022
A Wide AOI tool for discord.

drkdiscord - drk#1337 A Wide AOI tool for discord. Installation To Install you have to have python 3.x and pip installed on your system. If you have t

Darkest Surface 6 Dec 17, 2022
Eva Maria Telegram Bot

Eva Maria Bot Features Auto Filter Manuel Filter IMDB Admin Commands Broadcast Index IMDB search Inline Search Random pics ids and User info Stats, Us

Eva Maria TG 477 Dec 31, 2022
股票量化

StockQuant Gary-Hertel 请勿提交issue!可以加入交流群与其他朋友一起自学交流,加微信mzjimmy 一、配置文件的设置 启动框架需要先导入必要的模块,并且载入一次配置文件! 配置文件是一个json格式的文件config.json,在docs文件夹中有模板

218 Dec 25, 2022
A discord bot that moderates your server!

Staff Bot para Discord O que é? É um bot que modera o seu servidor no Discord, apagando mensagens indesejadas que os usuários mandem! Como usar Primei

Isac Gonçalves Cunha 3 Oct 07, 2021
⚡️ Get notified as soon as your next CPU, GPU, or game console is in stock

Inventory Hunter This bot helped me snag an RTX 3070... hopefully it will help you get your hands on your next CPU, GPU, or game console. Requirements

Eric Marti 1.1k Dec 26, 2022
A Terminal User Interface (TUI) for automated trading with Komodo Platform's AtomicDEX-API

PytomicDEX Makerbot A Terminal User Interface (TUI) for automated trading with Komodo Platform's AtomicDEX-API Install sudo apt install wget curl jq g

6 Aug 25, 2022
Telegram Group Calls Streaming bot with some useful features, written in Python with Pyrogram and Py-Tgcalls. Supporting platforms like Youtube, Spotify, Resso, AppleMusic, Soundcloud and M3u8 Links.

Yukki Music Bot Yukki Music Bot is a Powerful Telegram Music+Video Bot written in Python using Pyrogram and Py-Tgcalls by which you can stream songs,

Team Yukki 996 Dec 28, 2022
Algofi Python SDK is useful for developers who want to programatically interact with the Algofi lending protocol

algofi-py-sdk Algofi Python SDK Documentation https://algofi-py-sdk.readthedocs.

Algofi 41 Dec 15, 2022
One of the best Telegram renamer bot with many new features

Renamer-Bot I think this repo gonna become one of the best renamer open source 🥰 . Please Give a ⭐ if you like this repo and also try following me fo

Ns Bots 97 Jan 06, 2023
A fast, easy to set up telegram userbot running Python 3 which uses fork of the Telethon Library.

forked from friendly-telegram/friendly-telegram Friendly Telegram Userbot A fast, easy to set up telegram userbot running Python 3 which uses fork of

GeekTG 75 Jan 04, 2023
A Discord API Wrapper for Userbots/Selfbots written in Python.

DisCum A simple, easy to use, non-restrictive, synchronous Discord API Wrapper for Selfbots/Userbots written in Python. -using requests and websockets

Liam 450 Dec 27, 2022
Project for QVault Hackathon which plays sounds based on the letters of a user's name

virtual_instrument Project for QVault Hackathon which plays sounds based on the letters of a user's name I created a virtual instrument using Python a

Paolo Sidera 2 Feb 11, 2022