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

Overview

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

Repositório para o Live Coding DIO do dia 24/11/2021

Serviços utilizados

  • Amazon RDS
  • AWS Lambda
  • MySQL Workbench

Criando o banco de dados no Amazon RDS

  • AWS Console -> Amazon RDS -> Create database -> Standard create -> MySQL -> Versão padrão -> Free Tier -> DB instance identifier [dio-live-db] -> Master username [admin] -> Master password [sua_senha_forte] -> DB instance size - padrão -> Storage - configurações padrão -> Connectivity - vpc padrão -> Publicly accessible [yes] -> VPC Security - padrão -> Database authentication [password authentication] -> Create database
  • Selecionar o DB criado -> Connectivity & security -> Copiar endpoint.

No MySQL Workbench

  • MySQL Connections -> New -> Connection name [DioLive] -> Hostname - colar o endpoint copiado no passo anterior -> Username [admin] -> Teste Connection -> Password [sua_senha]

Em caso de problemas na conexão

  • Security -> VPC security groups -> Acessar o SG criado -> Inbound -> Edit -> Add rule -> type [All traffic] -> Source [Anywhere] -> Save

No MySQL Workbench

  • Selecionar a conexão criada -> Password [sua_senha_forte]

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 associativa de itens em um carrinho de compras

    CREATE TABLE ITEMS (
      cart_id INT NOT NULL,
      product_id INT NOT NULL,
      quantity DECIMAL(15,2) NOT NULL,
      FOREIGN KEY (cart_id) REFERENCES CARTS (id),
      FOREIGN KEY (product_id) REFERENCES PRODUCTS (id)
    );
    
  • Descrevendo o esquema de uma tabela

    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)
    );
    
  • Inserindo dados em tabelas

    INSERT INTO user VALUES (1, '[email protected]', 'Cassiano', 'strongpasswd');
    INSERT INTO user VALUES (2, '[email protected]', 'Joao', '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);
    
  • Selecionando todos os registros de uma tabela

    SELECT * FROM [table_name];
    
  • 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);
    

Realizando queries no Amazon RDS a partir de uma função no AWS Lambda

Criando a função Lambda

  • Acessar o AWS Lambda console -> Create function -> Author from scratch -> Function name [RDSQuery] -> Runtime - Python3.9 -> Create new role from AWS policy template -> Role name [RDSQueryFromLambdaRole] -> Create function

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
  • Attach policies -> Pesquisar pela policy AWSLambdaVPCAccessExecutionRole -> Attach policy

Desenvolvendo o código da função Lambda

  • Editor de código da função criada -> Inserir o código disponível na pasta src deste projeto

Importando a biblioteca pymysql utilizando Lambda Layers

  • Lambda Dashboard -> Layers -> Create layer -> Name [pymysql_layer] -> Upload a .zip file - o arquivo pyton.zip está disponível na pasta src do projeto -> Compatible architectures x86_64 -> Compatible runtimes - Python 3.9 -> Create
  • Lambda Dashboard -> selecionar a função criada -> Layers -> Add a layer -> Custom layers -> selecionar o layer criado anteriormente -> Add

Testando a função criada

  • Test -> New event -> Template -> Hello World -> Name [test] -> Save changes -> Test
Owner
Cassiano Ricardo de Oliveira Peres
NodeJs, blockchain and cloud developer. Cryptocurrency enthusiastic.
Cassiano Ricardo de Oliveira Peres
Using multiple API sources, create an app that allows users to filter through random locations based on their temperature range choices.

World_weather_analysis Overview Using multiple API sources, create an app that allows users to filter through random locations based on their temperat

Jason Boyer 2 Sep 16, 2022
A simple discord tool that translates english to either spanish, german or french and sends it. Free to rework but please give me credit.

discord-translator A simple discord tool that translates english to either spanish, german or french and sends it. Free to rework but please give me c

TrolledTooHard 2 Oct 04, 2021
Zipper-s-Father - A simple telegram bot that takes a list of files sent by the user and returns them zipped

ZIP files telegram bot A simple telegram bot that takes a list of files sent by

Dr.Caduceus 1 Jan 29, 2022
Python SDK for Facebook's Graph API

Facebook Python SDK This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical

Mobolic 2.7k Jan 07, 2023
An Advanced Python Playing Card Module that makes creating playing card games simple and easy!

playingcards.py An Advanced Python Playing Card Module that makes creating playing card games simple and easy! Features Easy to Understand Class Objec

Blake Potvin 5 Aug 30, 2022
471 Dec 24, 2022
Widevine CDM API

wvproxy Widevine CDM API Setup Install Python 3.6 or newer and Poetry Install Python package dependencies using poetry install Activate the virtual en

24 Dec 09, 2022
Телеграм бот решающий задания ЦДЗ, написанный на библиотеке libmesh.

MESHBot-Telegram Телеграм бот решающий задания ЦДЗ. Описание: Бот написан с использованием библиотеки libmesh. Для начала работы отправьте ему ссылку

2 Jun 19, 2022
Example app to be deployed to AWS as an API Gateway / Lambda Stack

Disclaimer I won't answer issues or emails regarding the project anymore. The project is old and not maintained anymore. I'm not sure if it still work

Ben 123 Jan 01, 2023
Amanda-A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules.

Amanda-A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules.

Team Amanda 4 Oct 21, 2022
A Python Program to determine Degree of Profanity of Tweets

tweetx tweetx is a program to detect racial slurs in Twitter Tweets. Racial Abuse on Twitter is becoming quite a serious issue in recent times. tweetx

Kartik Poojari 3 Nov 11, 2021
An advanced Filter Bot with nearly unlimitted filters

Telegram MTProto API Framework for Python Documentation • Releases • Community Pyrogram from pyrogram import Client, filters app = Client("my_account

Pyrogram 3.2k Jan 05, 2023
This is a telegram bot hosted by a Raspberry Pi equipped with a temperature and humidity sensor. The bot is capable of sending plots and readings.

raspy-temperature-bot This is a telegram bot hosted by a Raspberry Pi equipped with a temperature and humidity sensor. The bot is capable of sending p

31 May 22, 2022
Fully automated YouTube Channel. Using Reddit and YouTube API.

Fully Automated YouTube Shorts Channel This code will show you how to setup and fully autmated YouTube Channel. Content is gathered from Reddit using

Jacob Lower 96 Dec 25, 2022
Discord feeder for AIL

ail-feeder-discord Discord feeder for AIL Warning! Automating user accounts is technically against TOS, so use at your own risk! Discord API https://d

ail project 6 Mar 09, 2022
A results generator and automatic token checker for Yandex Contest

Yandex contest Python checking tools A results generator and automatic token checker for Yandex Contest. Версия на русском языке Installation Clone th

Nikolay Chechulin 9 Dec 14, 2022
A python package for AxisVM

PyAxisVM The package is under development. Follow us on social media, where we'll announce the first release! Overview The PyAxisVM project offers a h

AxisVM - InterCAD 8 Nov 19, 2022
Easy way to use Telegram bot to hide your identity.

telegram-support-bot Easy way to use Telegram bot to hide your identity. Useful for support, anonymous channel management. Free clone of Livegram Bot.

Daniil Okhlopkov 197 Dec 23, 2022
An automated, headless YouTube Uploader

An automated, headless YouTube Uploader Authors: Christian C., Moritz M., Luca S. Related Projects: YouTube Watcher, Twitch Compilation Creator, Neura

127 Dec 23, 2022
Python wrapper for CoWin API's

Cowin Tracker Python API wrapper for CoWin, India's digital platform launched by the government to help citizens register themselves for the vaccinati

Saiprasad Balasubramanian 43 Jun 11, 2022