├── .gitignore ├── pedido ├── pedido_project │ ├── pedido │ │ ├── __init__.py │ │ ├── views.py │ │ ├── admin.py │ │ ├── tests.py │ │ └── models.py │ ├── pedido_project │ │ ├── __init__.py │ │ ├── urls.py │ │ ├── wsgi.py │ │ └── settings.py │ ├── pedido.db │ ├── my_project.png │ ├── manage.py │ └── pedido2.sql ├── modelagem │ ├── tikz-er2.sty │ ├── modelagemPedido.jpg │ ├── modelagemPedido.pdf │ ├── relacionamentosPedido.jpg │ ├── relacionamentosPedido.pdf │ ├── relacionamentosPedido.tex │ ├── modelagemPedido.tex │ └── pedido.sql └── README.md ├── agenda ├── mer.jpg ├── mer.pdf ├── tikz-er2.sty ├── modelagem.png ├── agenda_django.png ├── admin.py ├── mer.tex ├── README.md ├── agenda.sql ├── agenda_mysql_workbench.sql └── models.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc -------------------------------------------------------------------------------- /pedido/pedido_project/pedido/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pedido/pedido_project/pedido_project/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pedido/pedido_project/pedido/views.py: -------------------------------------------------------------------------------- 1 | # Create your views here. 2 | -------------------------------------------------------------------------------- /agenda/mer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/agenda/mer.jpg -------------------------------------------------------------------------------- /agenda/mer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/agenda/mer.pdf -------------------------------------------------------------------------------- /agenda/tikz-er2.sty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/agenda/tikz-er2.sty -------------------------------------------------------------------------------- /agenda/modelagem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/agenda/modelagem.png -------------------------------------------------------------------------------- /agenda/agenda_django.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/agenda/agenda_django.png -------------------------------------------------------------------------------- /pedido/modelagem/tikz-er2.sty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/modelagem/tikz-er2.sty -------------------------------------------------------------------------------- /pedido/pedido_project/pedido.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/pedido_project/pedido.db -------------------------------------------------------------------------------- /pedido/modelagem/modelagemPedido.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/modelagem/modelagemPedido.jpg -------------------------------------------------------------------------------- /pedido/modelagem/modelagemPedido.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/modelagem/modelagemPedido.pdf -------------------------------------------------------------------------------- /pedido/pedido_project/my_project.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/pedido_project/my_project.png -------------------------------------------------------------------------------- /pedido/modelagem/relacionamentosPedido.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/modelagem/relacionamentosPedido.jpg -------------------------------------------------------------------------------- /pedido/modelagem/relacionamentosPedido.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rg3915/banco_de_dados/master/pedido/modelagem/relacionamentosPedido.pdf -------------------------------------------------------------------------------- /pedido/pedido_project/pedido/admin.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | from pedido.models import * 3 | from django.contrib import admin 4 | 5 | admin.site.register((Cliente, Produto, Categoria, Pedido, DetPedido)) -------------------------------------------------------------------------------- /pedido/README.md: -------------------------------------------------------------------------------- 1 | ##PEDIDO 2 | 3 | Exemplo de pedido de compras para teste dos comandos sql. 4 | 5 | Agora o pedido faz parte de um projeto django. 6 | O projeto será feito com sqlite3 para mais simplicidade. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | banco_de_dados 2 | ============== 3 | 4 | Modelagem de dados e testes em SGBD. 5 | 6 | # Objetivo 7 | 8 | O objetivo deste projeto é fazer algumas modelagens de banco de dados, além de experimentar e testar alguns SGBD. -------------------------------------------------------------------------------- /pedido/pedido_project/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pedido_project.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /pedido/pedido_project/pedido_project/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import patterns, include, url 2 | 3 | # Uncomment the next two lines to enable the admin: 4 | from django.contrib import admin 5 | admin.autodiscover() 6 | 7 | urlpatterns = patterns('', 8 | # Examples: 9 | # url(r'^$', 'pedido_project.views.home', name='home'), 10 | # url(r'^pedido_project/', include('pedido_project.foo.urls')), 11 | url(r'^admin/', include(admin.site.urls)), 12 | ) 13 | -------------------------------------------------------------------------------- /pedido/pedido_project/pedido/tests.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file demonstrates writing tests using the unittest module. These will pass 3 | when you run "manage.py test". 4 | 5 | Replace this with more appropriate tests for your application. 6 | """ 7 | 8 | from django.test import TestCase 9 | 10 | 11 | class SimpleTest(TestCase): 12 | def test_basic_addition(self): 13 | """ 14 | Tests that 1 + 1 always equals 2. 15 | """ 16 | self.assertEqual(1 + 1, 2) 17 | -------------------------------------------------------------------------------- /agenda/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.contrib import admin 3 | from agenda.models import * 4 | 5 | 6 | class RelacionamentoInline(admin.StackedInline): 7 | model = Relacionamento 8 | fk_name = 'contato' 9 | 10 | 11 | class FoneInline(admin.TabularInline): 12 | model = Fone 13 | 14 | 15 | class EnderecoInline(admin.TabularInline): 16 | model = Endereco 17 | 18 | 19 | class ContatoTagInline(admin.TabularInline): 20 | model = ContatoTag 21 | fk_name = 'contato' 22 | 23 | 24 | class ContatoAdmin(admin.ModelAdmin): 25 | inlines = [RelacionamentoInline, FoneInline, 26 | EnderecoInline, ContatoTagInline] 27 | 28 | 29 | admin.site.register(Contato, ContatoAdmin) 30 | admin.site.register(Endereco) 31 | admin.site.register(Relacionamento) 32 | admin.site.register(Tag) 33 | -------------------------------------------------------------------------------- /pedido/modelagem/relacionamentosPedido.tex: -------------------------------------------------------------------------------- 1 | \documentclass[tikz]{standalone} 2 | \usepackage[utf8]{inputenc} 3 | \usepackage[T1]{fontenc} 4 | \usepackage{tikz-uml} 5 | \usepackage[pdfpagelayout=SinglePage]{hyperref} 6 | 7 | \begin{document} 8 | 9 | \begin{tikzpicture} 10 | \umlclass[x=0,y=0]{clientes}{ 11 | - idCliente \\ 12 | - nome \\ 13 | }{} 14 | \umlclass[x=5,y=0,fill=green!20]{pedidos}{ 15 | - idPedido \\ 16 | - dataPedido \\ 17 | + idCliente \\ 18 | }{} 19 | \umlclass[x=5,y=-5,fill=green!20]{detPedidos}{ 20 | - iddetPedido \\ 21 | + idPedido \\ 22 | + idProduto \\ 23 | - quantidade \\ 24 | }{} 25 | \umlclass[x=10,y=-5]{produtos}{ 26 | - idProduto \\ 27 | + idCategoria \\ 28 | - produto \\ 29 | - preco \\ 30 | }{} 31 | \umlclass[x=15,y=-5]{categorias}{ 32 | - idCategoria \\ 33 | - categoria \\ 34 | }{} 35 | 36 | \umlassoc{clientes}{pedidos} 37 | \umlassoc[geometry=-|-]{pedidos}{detPedidos} 38 | \umlassoc[geometry=-|-]{detPedidos}{produtos} 39 | \umlassoc[geometry=-|-]{produtos}{categorias} 40 | \end{tikzpicture} 41 | 42 | \end{document} -------------------------------------------------------------------------------- /agenda/mer.tex: -------------------------------------------------------------------------------- 1 | \documentclass{standalone} 2 | \usepackage{tikz-er2} 3 | %\usetikzlibrary{positioning} 4 | 5 | \begin{document} 6 | 7 | \tikzstyle{every entity} = [fill=blue!20] 8 | \tikzstyle{every relationship} = [fill=red!20] 9 | \begin{tikzpicture}[node distance=4cm] 10 | % Contato 11 | \node[entity] (contato) {Contato}; 12 | \node[relationship] (mora) [above right of=contato] {mora em} edge node[auto,swap] {1} (contato); 13 | \node[relationship,fill=orange!50] (tem) [right of=contato] {tem} edge node[auto,swap] {n} (contato); 14 | \node[relationship] (possui) [below right of=contato] {possui} edge node[auto,swap] {1} (contato); 15 | \node[relationship] (relaciona) [left of=contato] {relaciona com} edge [total] (contato); 16 | 17 | % Endereco 18 | \node[entity] (endereco) [right of=mora] {Endere\c {c}o} edge node[auto,swap] {n} (mora); 19 | 20 | % Fone 21 | \node[entity] (fone) [right of=possui] {Fone} edge node[auto,swap] {n} (possui); 22 | 23 | % Tag 24 | \node[entity] (tag) [right of=tem] {Tag} edge node[auto,swap] {n} (tem); 25 | 26 | \end{tikzpicture} 27 | 28 | \end{document} -------------------------------------------------------------------------------- /pedido/pedido_project/pedido/models.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | from django.db import models 3 | from datetime import date 4 | 5 | class Cliente(models.Model): 6 | nome = models.CharField('Nome', max_length=50) 7 | 8 | class Meta: 9 | verbose_name=u'cliente' 10 | verbose_name_plural=u'clientes' 11 | 12 | def __unicode__(self): 13 | return self.nome 14 | 15 | class Categoria(models.Model): 16 | categoria = models.CharField('Categoria', max_length=50) 17 | 18 | class Meta: 19 | verbose_name=u'categoria' 20 | verbose_name_plural=u'categorias' 21 | 22 | def __unicode__(self): 23 | return self.categoria 24 | 25 | class Produto(models.Model): 26 | categoria = models.ForeignKey(Categoria) 27 | produto = models.CharField('Produto', max_length=50) 28 | preco = models.DecimalField('Preço', max_digits=8, decimal_places=2) 29 | 30 | class Meta: 31 | verbose_name=u'produto' 32 | verbose_name_plural=u'produtos' 33 | 34 | def __unicode__(self): 35 | return self.produto 36 | 37 | class Pedido(models.Model): 38 | data_pedido = models.DateField('Data do pedido') 39 | cliente = models.ForeignKey(Cliente) 40 | 41 | def __unicode__(self): 42 | return unicode(self.data_pedido) 43 | 44 | class DetPedido(models.Model): 45 | pedido = models.ForeignKey(Pedido) 46 | produto = models.ForeignKey(Produto) 47 | quantidade = models.IntegerField() 48 | 49 | def __unicode__(self): 50 | return unicode(self.pedido) 51 | -------------------------------------------------------------------------------- /pedido/pedido_project/pedido_project/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for pedido_project project. 3 | 4 | This module contains the WSGI application used by Django's development server 5 | and any production WSGI deployments. It should expose a module-level variable 6 | named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover 7 | this application via the ``WSGI_APPLICATION`` setting. 8 | 9 | Usually you will have the standard Django WSGI application here, but it also 10 | might make sense to replace the whole Django WSGI application with a custom one 11 | that later delegates to the Django one. For example, you could introduce WSGI 12 | middleware here, or combine a Django application with an application of another 13 | framework. 14 | 15 | """ 16 | import os 17 | 18 | # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks 19 | # if running multiple sites in the same mod_wsgi process. To fix this, use 20 | # mod_wsgi daemon mode with each site in its own daemon process, or use 21 | # os.environ["DJANGO_SETTINGS_MODULE"] = "pedido_project.settings" 22 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pedido_project.settings") 23 | 24 | # This application object is used by any WSGI server configured to use this 25 | # file. This includes Django's development server, if the WSGI_APPLICATION 26 | # setting points here. 27 | from django.core.wsgi import get_wsgi_application 28 | application = get_wsgi_application() 29 | 30 | # Apply WSGI middleware here. 31 | # from helloworld.wsgi import HelloWorldApplication 32 | # application = HelloWorldApplication(application) 33 | -------------------------------------------------------------------------------- /agenda/README.md: -------------------------------------------------------------------------------- 1 | Agenda 2 | ====== 3 | 4 | # Objetivo 5 | 6 | Modelar uma agenda de contatos onde um contato possa se relacionar com outras pessoas, semelhante aos relacionamentos do Facebook e Google+. 7 | 8 | Além disso o contato pode possuir vários endereços, telefones e tags. As tags servem para melhorar a identificação de cada contato. 9 | 10 | # Itens 11 | 12 | **mer.tex** é a modelagem conceitual (coloquei apenas as entidades). Para fazer este documento eu usei o [LaTeX][0] junto com o pacote [tikz-er2][2]. 13 | 14 | Para compilar o documento use o comando 15 | 16 | $ latexmk -pdf mer.tex && latexmk -c 17 | 18 | Para converter o **pdf** em **jpg** use o [Imagemagick][3]. 19 | 20 | $ convert -density 300 mer.pdf mer.jpg 21 | 22 | ![mer](mer.jpg) 23 | 24 | **modelagem.png** mostra as tabelas feitas no *Workbench*. 25 | 26 | ![a](modelagem.png) 27 | 28 | **agenda_django.png** são as tabelas feitas no *Django*. 29 | 30 | ![b](agenda_django.png) 31 | 32 | **agenda_mysql_workbench.sql** é o schema exportado do *Workbench*. 33 | 34 | **agenda.sql** é o schema exportado do sqlite3. 35 | 36 | **models.py** é a *receita* de como fazer o modelo no *Django*. 37 | 38 | **admin.py** mostra em especial o uso do *TabularInline*. 39 | 40 | **Todo**: Leia [Como criar um site com formulário e lista em 30 minutos][1] e tente você mesmo recriar o modelo no Django. 41 | 42 | [0]: http://latexbr.blogspot.com.br/ 43 | [1]: http://pythonclub.com.br/criar-site-com-form-lista-30-min.html 44 | [2]: https://bitbucket.org/pavel_calado/tikz-er2/wiki/Home 45 | [3]: http://grandeportal.blogspot.com.br/2012/06/editando-imagens-no-imagemagick.html -------------------------------------------------------------------------------- /agenda/agenda.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE "agenda_contato" ( 2 | "id" integer NOT NULL PRIMARY KEY, 3 | "confidencial" boolean NOT NULL, 4 | "tratamento" varchar(4) NOT NULL, 5 | "nome" varchar(50) NOT NULL, 6 | "sobrenome" varchar(50) NOT NULL, 7 | "nome_fantasia" varchar(50) NOT NULL, 8 | "razao_social" varchar(50) NOT NULL, 9 | "tipo_contato" varchar(1) NOT NULL, 10 | "cargo" varchar(50) NOT NULL, 11 | "email" varchar(75) NOT NULL, 12 | "cnpj" varchar(13) NOT NULL, 13 | "ie" varchar(15) NOT NULL, 14 | "cpf" varchar(11) NOT NULL, 15 | "rg" varchar(10) NOT NULL, 16 | "criado_em" datetime NOT NULL, 17 | "modificado_em" datetime NOT NULL 18 | ); 19 | CREATE TABLE "agenda_relacionamento" ( 20 | "id" integer NOT NULL PRIMARY KEY, 21 | "contato_id" integer NOT NULL REFERENCES "agenda_contato" ("id"), 22 | "relaciona_com_id" integer NOT NULL REFERENCES "agenda_contato" ("id") 23 | ); 24 | CREATE TABLE "agenda_contatotag" ( 25 | "id" integer NOT NULL PRIMARY KEY, 26 | "contato_id" integer NOT NULL REFERENCES "agenda_contato" ("id"), 27 | "tag_id" integer NOT NULL 28 | ); 29 | CREATE TABLE "agenda_tag" ( 30 | "id" integer NOT NULL PRIMARY KEY, 31 | "tag" varchar(100) NOT NULL 32 | ); 33 | CREATE TABLE "agenda_endereco" ( 34 | "id" integer NOT NULL PRIMARY KEY, 35 | "contato_id" integer NOT NULL REFERENCES "agenda_contato" ("id"), 36 | "tipo_endereco" varchar(1) NOT NULL, 37 | "logradouro" varchar(200) NOT NULL, 38 | "complemento" varchar(100) NOT NULL, 39 | "bairro" varchar(100) NOT NULL, 40 | "cidade" varchar(100) NOT NULL, 41 | "uf" varchar(100) NOT NULL, 42 | "pais" varchar(100) NOT NULL, 43 | "cep" varchar(50) NOT NULL 44 | ); 45 | CREATE TABLE "agenda_fone" ( 46 | "id" integer NOT NULL PRIMARY KEY, 47 | "contato_id" integer NOT NULL REFERENCES "agenda_contato" ("id"), 48 | "fone" varchar(50) NOT NULL, 49 | "tipo_fone" varchar(3) NOT NULL 50 | ); 51 | -------------------------------------------------------------------------------- /pedido/modelagem/modelagemPedido.tex: -------------------------------------------------------------------------------- 1 | \documentclass{standalone} 2 | \usepackage{tikz-er2} 3 | 4 | \begin{document} 5 | 6 | \tikzstyle{every entity} = [fill=blue!20] 7 | \tikzstyle{every attribute} = [fill=yellow!20,node distance=2cm] 8 | \tikzstyle{every relationship} = [fill=red!20] 9 | \tikzstyle{every edge} = [link] 10 | \begin{tikzpicture}[node distance=3cm] 11 | \node[weak entity] (cliente) {Cliente}; 12 | \node[attribute] (idCliente) [above left of=cliente] {\key{idCliente}} edge (cliente); 13 | \node[attribute] (nome) [left of=cliente] {nome} edge (cliente); 14 | \node[ident relationship] (faz) [right of=cliente] {faz} edge node[auto,swap] {n} (cliente); 15 | 16 | \node[entity] (pedido) [right of=faz] {Pedido} edge node[auto,swap] {1} (faz); 17 | \node[attribute] (idPedido) [above right of=pedido] {\key{idPedido}} edge (pedido); 18 | \node[attribute] (dataPedido) [right of=pedido,node distance=3cm] {dataPedido} edge (pedido); 19 | \node[relationship] (tem) [below of=pedido] {tem} edge node[auto,swap] {1} (pedido); 20 | \node[attribute] (idClienteFK) [below right of=pedido,node distance=2.5cm] {\key{idCliente}} edge (pedido); 21 | 22 | \node[entity] (detPedido) [below of=tem] {detPedido} edge node[auto,swap] {n} (tem); 23 | \node[attribute] (iddetPedido) [above left of=detPedido] {\key{iddetPedido}} edge (detPedido); 24 | \node[attribute] (idPedidoFK) [left of=detPedido,node distance=3cm] {\key{idPedido}} edge (detPedido); 25 | \node[attribute] (quant) [below of=detPedido] {Quantidade} edge (detPedido); 26 | \node[ident relationship] (pede) [right of=detPedido] {pede} edge node[auto,swap] {1} (detPedido); 27 | 28 | \node[weak entity] (produto) [right of=pede] {Produto} edge node[auto,swap] {n} (pede); 29 | \node[attribute] (idProduto) [above left of=produto] {\key{idProduto}} edge (produto); 30 | \node[attribute] (nomeproduto) [below left of=produto] {Produto} edge (produto); 31 | \node[attribute] (preco) [below right of=produto] {Preco} edge (produto); 32 | \node[attribute] (idCategoriaFK) [above right of=produto] {\key{idCategoria}} edge (produto); 33 | 34 | \node[attribute] (idProdutoFK) [below left of=detPedido,node distance=2cm] {\key{idProduto}} edge (detPedido); 35 | \node[relationship] (possui) [right of=produto] {possui} edge node[auto,swap] {n} (produto); 36 | 37 | \node[entity] (categoria) [right of=possui] {Categoria} edge node[auto,swap] {1} (possui); 38 | \node[attribute] (idCategoria) [above right of=categoria] {\key{idCategoria}} edge (categoria); 39 | \node[attribute] (nomeCategoria) [below right of=categoria] {Categoria} edge (categoria); 40 | \end{tikzpicture} 41 | 42 | \end{document} -------------------------------------------------------------------------------- /agenda/agenda_mysql_workbench.sql: -------------------------------------------------------------------------------- 1 | SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; 2 | SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; 3 | SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; 4 | 5 | CREATE SCHEMA IF NOT EXISTS `agenda` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; 6 | USE `agenda` ; 7 | 8 | -- ----------------------------------------------------- 9 | -- Table `agenda`.`Contato` 10 | -- ----------------------------------------------------- 11 | CREATE TABLE IF NOT EXISTS `agenda`.`Contato` ( 12 | `id` INT NOT NULL, 13 | `confidencial` TINYINT(1) NULL, 14 | `tratamento` VARCHAR(100) NULL, 15 | `nome` VARCHAR(100) NULL, 16 | `sobrenome` VARCHAR(100) NULL, 17 | `nome_fantasia` VARCHAR(100) NULL, 18 | `razao_social` VARCHAR(100) NULL, 19 | `tipo_contato` VARCHAR(5) NULL, 20 | `cargo` VARCHAR(45) NULL, 21 | `email` VARCHAR(45) NULL, 22 | `cnpj` VARCHAR(13) NULL, 23 | `ie` VARCHAR(15) NULL, 24 | `cpf` VARCHAR(11) NULL, 25 | `rg` VARCHAR(15) NULL, 26 | `criado_em` DATETIME NULL, 27 | `modificado_em` DATETIME NULL, 28 | PRIMARY KEY (`id`)) 29 | ENGINE = InnoDB; 30 | 31 | 32 | -- ----------------------------------------------------- 33 | -- Table `agenda`.`Relacionamento` 34 | -- ----------------------------------------------------- 35 | CREATE TABLE IF NOT EXISTS `agenda`.`Relacionamento` ( 36 | `id` INT NOT NULL, 37 | `contato_id` INT NOT NULL, 38 | `relaciona_com_id` INT NOT NULL, 39 | PRIMARY KEY (`id`), 40 | INDEX `fk_Relacionamento_Contato_idx` (`contato_id` ASC), 41 | INDEX `fk_Relacionamento_Contato1_idx` (`relaciona_com_id` ASC), 42 | CONSTRAINT `fk_Relacionamento_Contato` 43 | FOREIGN KEY (`contato_id`) 44 | REFERENCES `agenda`.`Contato` (`id`) 45 | ON DELETE NO ACTION 46 | ON UPDATE NO ACTION, 47 | CONSTRAINT `fk_Relacionamento_Contato1` 48 | FOREIGN KEY (`relaciona_com_id`) 49 | REFERENCES `agenda`.`Contato` (`id`) 50 | ON DELETE NO ACTION 51 | ON UPDATE NO ACTION) 52 | ENGINE = InnoDB; 53 | 54 | 55 | -- ----------------------------------------------------- 56 | -- Table `agenda`.`Endereco` 57 | -- ----------------------------------------------------- 58 | CREATE TABLE IF NOT EXISTS `agenda`.`Endereco` ( 59 | `id` INT NOT NULL, 60 | `contato_id` INT NOT NULL, 61 | `tipo_endereco` VARCHAR(1) NULL, 62 | `logradouro` VARCHAR(45) NULL, 63 | `complemento` VARCHAR(45) NULL, 64 | `bairro` VARCHAR(45) NULL, 65 | `cidade` VARCHAR(45) NULL, 66 | `estado` VARCHAR(45) NULL, 67 | `pais` VARCHAR(45) NULL, 68 | `cep` VARCHAR(45) NULL, 69 | PRIMARY KEY (`id`), 70 | INDEX `fk_Endereco_Contato1_idx` (`contato_id` ASC), 71 | CONSTRAINT `fk_Endereco_Contato1` 72 | FOREIGN KEY (`contato_id`) 73 | REFERENCES `agenda`.`Contato` (`id`) 74 | ON DELETE NO ACTION 75 | ON UPDATE NO ACTION) 76 | ENGINE = InnoDB; 77 | 78 | 79 | -- ----------------------------------------------------- 80 | -- Table `agenda`.`Fone` 81 | -- ----------------------------------------------------- 82 | CREATE TABLE IF NOT EXISTS `agenda`.`Fone` ( 83 | `id` INT NOT NULL, 84 | `contato_id` INT NOT NULL, 85 | `fone` VARCHAR(45) NULL, 86 | `tipo_fone` VARCHAR(45) NULL, 87 | PRIMARY KEY (`id`), 88 | INDEX `fk_Fone_Contato1_idx` (`contato_id` ASC), 89 | CONSTRAINT `fk_Fone_Contato1` 90 | FOREIGN KEY (`contato_id`) 91 | REFERENCES `agenda`.`Contato` (`id`) 92 | ON DELETE NO ACTION 93 | ON UPDATE NO ACTION) 94 | ENGINE = InnoDB; 95 | 96 | 97 | -- ----------------------------------------------------- 98 | -- Table `agenda`.`Tag` 99 | -- ----------------------------------------------------- 100 | CREATE TABLE IF NOT EXISTS `agenda`.`Tag` ( 101 | `id` INT NOT NULL, 102 | `tag` VARCHAR(45) NULL, 103 | PRIMARY KEY (`id`)) 104 | ENGINE = InnoDB; 105 | 106 | 107 | -- ----------------------------------------------------- 108 | -- Table `agenda`.`Contato_Tag` 109 | -- ----------------------------------------------------- 110 | CREATE TABLE IF NOT EXISTS `agenda`.`Contato_Tag` ( 111 | `id` INT NOT NULL, 112 | `contato_id` INT NOT NULL, 113 | `tag_id` INT NOT NULL, 114 | PRIMARY KEY (`id`), 115 | INDEX `fk_Contato_Tag_Contato1_idx` (`contato_id` ASC), 116 | INDEX `fk_Contato_Tag_Tag1_idx` (`tag_id` ASC), 117 | CONSTRAINT `fk_Contato_Tag_Contato1` 118 | FOREIGN KEY (`contato_id`) 119 | REFERENCES `agenda`.`Contato` (`id`) 120 | ON DELETE NO ACTION 121 | ON UPDATE NO ACTION, 122 | CONSTRAINT `fk_Contato_Tag_Tag1` 123 | FOREIGN KEY (`tag_id`) 124 | REFERENCES `agenda`.`Tag` (`id`) 125 | ON DELETE NO ACTION 126 | ON UPDATE NO ACTION) 127 | ENGINE = InnoDB; 128 | 129 | 130 | SET SQL_MODE=@OLD_SQL_MODE; 131 | SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; 132 | SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; 133 | -------------------------------------------------------------------------------- /agenda/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.db import models 3 | 4 | CONTATO_TRATAMENTO = ( 5 | ('a', 'Arq.'), 6 | ('aa', 'Arqa.'), 7 | ('d', 'Dona'), 8 | ('dr', 'Dr.'), 9 | ('dra', 'Dra.'), 10 | ('e', 'Eng.'), 11 | ('p', 'Prof.'), 12 | ('pa', 'Profa.'), 13 | ('sr', 'Sr.'), 14 | ('sra', 'Sra.'), 15 | ('srta', 'Srta.'), 16 | ) 17 | 18 | TIPO_CONTATO = ( 19 | ('e', 'empresa'), 20 | ('p', 'pessoa'), 21 | ('c', 'colaborador'), 22 | ('f', u'funcionário'), 23 | ) 24 | 25 | 26 | class Contato(models.Model): 27 | confidencial = models.BooleanField(default=True) 28 | tratamento = models.CharField( 29 | max_length=4, choices=CONTATO_TRATAMENTO, blank=True) 30 | nome = models.CharField(max_length=50) 31 | sobrenome = models.CharField(max_length=50, blank=True) 32 | nome_fantasia = models.CharField(max_length=50, blank=True) 33 | razao_social = models.CharField(max_length=50, blank=True) 34 | tipo_contato = models.CharField(max_length=1, choices=TIPO_CONTATO) 35 | cargo = models.CharField(max_length=50, blank=True) 36 | email = models.EmailField() 37 | cnpj = models.CharField(max_length=13, blank=True) 38 | ie = models.CharField(max_length=15, blank=True) 39 | cpf = models.CharField(max_length=11, blank=True) 40 | rg = models.CharField(max_length=10, blank=True) 41 | criado_em = models.DateTimeField(auto_now_add=True, auto_now=False) 42 | modificado_em = models.DateTimeField(auto_now_add=False, auto_now=True) 43 | relationships = models.ManyToManyField( 44 | 'self', through='Relacionamento', symmetrical=False, related_name='related_to+') 45 | 46 | class Meta: 47 | ordering = ['criado_em'] 48 | verbose_name = (u'Contato') 49 | verbose_name_plural = (u'Contatos') 50 | 51 | def __unicode__(self): 52 | return self.nome + " " + self.sobrenome 53 | 54 | 55 | class Relacionamento(models.Model): 56 | contato = models.ForeignKey('Contato', related_name='contato_de') 57 | relaciona_com = models.ForeignKey('Contato', related_name='relaciona_com') 58 | 59 | class Meta: 60 | verbose_name = (u'Relacionamento') 61 | verbose_name_plural = (u'Relacionamentos') 62 | 63 | def __unicode__(self): 64 | return u'%s -> %s' % (self.contato.nome, self.relaciona_com.nome) 65 | 66 | def add_relationship(self, person, status, symm=True): 67 | relationship, created = Relacionamento.objects.get_or_create( 68 | contato=self, 69 | relaciona_com=person, 70 | status=status) 71 | if symm: 72 | person.add_relationship(self, status, False) 73 | return relationship 74 | 75 | def remove_relationship(self, person, status, symm=True): 76 | Relacionamento.objects.filter( 77 | contato=self, 78 | relaciona_com=person, 79 | status=status).delete() 80 | if symm: 81 | person.remove_relationship(self, status, False) 82 | 83 | def get_relationship(self, status): 84 | return self.relationships.filter( 85 | to_people__contato=self) 86 | 87 | 88 | class ContatoTag(models.Model): 89 | contato = models.ForeignKey('Contato') 90 | tag = models.ForeignKey('Tag') 91 | 92 | 93 | class Tag(models.Model): 94 | tag = models.CharField(max_length=100) 95 | 96 | class Meta: 97 | verbose_name = (u'tag') 98 | verbose_name_plural = (u'tags') 99 | 100 | def __unicode__(self): 101 | return self.tag 102 | 103 | TIPO_ENDERECO = ( 104 | ('i', 'indefinido'), 105 | ('c', 'comercial'), 106 | ('r', 'residencial'), 107 | ('o', 'outros'), 108 | ) 109 | 110 | 111 | class Endereco(models.Model): 112 | contato = models.ForeignKey('Contato') 113 | tipo_endereco = models.CharField(max_length=1, choices=TIPO_ENDERECO) 114 | logradouro = models.CharField(max_length=200) 115 | complemento = models.CharField(max_length=100, blank=True) 116 | bairro = models.CharField(max_length=100, blank=True) 117 | cidade = models.CharField(max_length=100, blank=True) 118 | uf = models.CharField(max_length=100, blank=True) 119 | pais = models.CharField(max_length=100, blank=True) 120 | cep = models.CharField(max_length=50, blank=True) 121 | 122 | class Meta: 123 | verbose_name = (u'endereço') 124 | verbose_name_plural = (u'endereços') 125 | 126 | def __unicode__(self): 127 | return self.logradouro 128 | 129 | TIPO_FONE = ( 130 | ('pri', 'principal'), 131 | ('com', 'comercial'), 132 | ('res', 'residencial'), 133 | ('cel', 'celular'), 134 | ('cl', 'Claro'), 135 | ('oi', 'Oi'), 136 | ('t', 'Tim'), 137 | ('v', 'Vivo'), 138 | ('n', 'Nextel'), 139 | ('fax', 'fax'), 140 | ('o', 'outros'), 141 | ) 142 | 143 | 144 | class Fone(models.Model): 145 | contato = models.ForeignKey('Contato') 146 | fone = models.CharField(max_length=50) 147 | tipo_fone = models.CharField(max_length=3, choices=TIPO_FONE) 148 | -------------------------------------------------------------------------------- /pedido/pedido_project/pedido2.sql: -------------------------------------------------------------------------------- 1 | -- Populando cliente 2 | INSERT INTO pedido_cliente (nome) VALUES ('Amanda'); 3 | INSERT INTO pedido_cliente (nome) VALUES ('Beatriz'); 4 | INSERT INTO pedido_cliente (nome) VALUES ('Carla'); 5 | INSERT INTO pedido_cliente (nome) VALUES ('Denise'); 6 | INSERT INTO pedido_cliente (nome) VALUES ('Eloisa'); 7 | INSERT INTO pedido_cliente (nome) VALUES ('Fernanda'); 8 | INSERT INTO pedido_cliente (nome) VALUES ('Gabriela'); 9 | INSERT INTO pedido_cliente (nome) VALUES ('Isadora'); 10 | INSERT INTO pedido_cliente (nome) VALUES ('Joana'); 11 | 12 | -- Populando categoria 13 | INSERT INTO pedido_categoria (categoria) VALUES ('Cama Mesa Banho'); 14 | INSERT INTO pedido_categoria (categoria) VALUES ('Eletrodomestico'); 15 | INSERT INTO pedido_categoria (categoria) VALUES ('Informatica'); 16 | INSERT INTO pedido_categoria (categoria) VALUES ('Movel'); 17 | INSERT INTO pedido_categoria (categoria) VALUES ('Roupa'); 18 | INSERT INTO pedido_categoria (categoria) VALUES ('Som'); 19 | INSERT INTO pedido_categoria (categoria) VALUES ('Video'); 20 | 21 | -- Populando produto 22 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (1, 'Toalha de mesa', 45); 23 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (2, 'Geladeira', 1200); 24 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (2, 'Fogao', 600); 25 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (3, 'Notebook', 1200); 26 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (3, 'Tablet', 900); 27 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (3, 'Ultrabook', 2100); 28 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (4, 'Sofa', 1500); 29 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (4, 'Cama', 800); 30 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (4, 'Cadeira', 400); 31 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (4, 'Mesa', 1450); 32 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (5, 'Calca', 59.99); 33 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (5, 'Camisa', 44.99); 34 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (5, 'Blusa', 80.90); 35 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (5, 'Short', 40.50); 36 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (5, 'Meia', 15.25); 37 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (6, 'CD Player', 180); 38 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (6, 'Microsystem', 1350.75); 39 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (7, 'TV', 1459.99); 40 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (7, 'Blue Ray', 724.99); 41 | INSERT INTO pedido_produto (categoria_id, produto, preco) VALUES (7, 'Home Teather', 1879.99); 42 | 43 | -- Populando pedido 44 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-01', 1); 45 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-02', 1); 46 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-02', 2); 47 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-03', 3); 48 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-04', 3); 49 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-08', 4); 50 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-08', 4); 51 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-09', 5); 52 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-10', 6); 53 | INSERT INTO pedido_pedido (data_pedido, cliente_id) VALUES ('2013-10-10', 6); 54 | 55 | -- Populando detPedido 56 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (1, 1, 16); 57 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (1,2, 20); 58 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (1,3, 12); 59 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (1,3, 11); 60 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (2,2, 1); 61 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (2,1, 5); 62 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (2,5, 3); 63 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (3,10, 2); 64 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (3,20, 8); 65 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (3,15, 9); 66 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (3,15, 12); 67 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (3,12, 20); 68 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (4,13, 22); 69 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (5,14, 17); 70 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (5,7, 19); 71 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (6,7, 4); 72 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (6,7, 6); 73 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (7,8, 3); 74 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (7,9, 5); 75 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (7,10, 2); 76 | INSERT INTO pedido_detPedido (pedido_id, produto_id, quantidade) VALUES (8,12, 1); -------------------------------------------------------------------------------- /pedido/pedido_project/pedido_project/settings.py: -------------------------------------------------------------------------------- 1 | # Django settings for pedido_project project. 2 | import os, sys 3 | 4 | BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 5 | 6 | DEBUG = True 7 | TEMPLATE_DEBUG = DEBUG 8 | 9 | ADMINS = ( 10 | # ('Your Name', 'your_email@example.com'), 11 | ) 12 | 13 | MANAGERS = ADMINS 14 | 15 | DATABASES = { 16 | 'default': { 17 | 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 18 | 'NAME': 'pedido.db', # Or path to database file if using sqlite3. 19 | # The following settings are not used with sqlite3: 20 | 'USER': '', 21 | 'PASSWORD': '', 22 | 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 23 | 'PORT': '', # Set to empty string for default. 24 | } 25 | } 26 | 27 | # Hosts/domain names that are valid for this site; required if DEBUG is False 28 | # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts 29 | ALLOWED_HOSTS = [] 30 | 31 | # Local time zone for this installation. Choices can be found here: 32 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 33 | # although not all choices may be available on all operating systems. 34 | # In a Windows environment this must be set to your system time zone. 35 | TIME_ZONE = 'America/Sao_Paulo' 36 | 37 | # Language code for this installation. All choices can be found here: 38 | # http://www.i18nguy.com/unicode/language-identifiers.html 39 | LANGUAGE_CODE = 'pt-br' 40 | 41 | SITE_ID = 1 42 | 43 | # If you set this to False, Django will make some optimizations so as not 44 | # to load the internationalization machinery. 45 | USE_I18N = True 46 | 47 | # If you set this to False, Django will not format dates, numbers and 48 | # calendars according to the current locale. 49 | USE_L10N = True 50 | 51 | # If you set this to False, Django will not use timezone-aware datetimes. 52 | USE_TZ = True 53 | 54 | # Absolute filesystem path to the directory that will hold user-uploaded files. 55 | # Example: "/var/www/example.com/media/" 56 | MEDIA_ROOT = '' 57 | 58 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a 59 | # trailing slash. 60 | # Examples: "http://example.com/media/", "http://media.example.com/" 61 | MEDIA_URL = '' 62 | 63 | # Absolute path to the directory static files should be collected to. 64 | # Don't put anything in this directory yourself; store your static files 65 | # in apps' "static/" subdirectories and in STATICFILES_DIRS. 66 | # Example: "/var/www/example.com/static/" 67 | STATIC_ROOT = '' 68 | 69 | # URL prefix for static files. 70 | # Example: "http://example.com/static/", "http://static.example.com/" 71 | STATIC_URL = '/static/' 72 | 73 | # Additional locations of static files 74 | STATICFILES_DIRS = ( 75 | os.path.join(BASE_DIR, 'static'), 76 | # Put strings here, like "/home/html/static" or "C:/www/django/static". 77 | # Always use forward slashes, even on Windows. 78 | # Don't forget to use absolute paths, not relative paths. 79 | ) 80 | 81 | # List of finder classes that know how to find static files in 82 | # various locations. 83 | STATICFILES_FINDERS = ( 84 | 'django.contrib.staticfiles.finders.FileSystemFinder', 85 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 86 | # 'django.contrib.staticfiles.finders.DefaultStorageFinder', 87 | ) 88 | 89 | # Make this unique, and don't share it with anybody. 90 | SECRET_KEY = '017k6(2ayr!qk4yw9x$3hg)0kh$!=8t-=v7o=f^vft8f_kheg)' 91 | 92 | # List of callables that know how to import templates from various sources. 93 | TEMPLATE_LOADERS = ( 94 | 'django.template.loaders.filesystem.Loader', 95 | 'django.template.loaders.app_directories.Loader', 96 | # 'django.template.loaders.eggs.Loader', 97 | ) 98 | 99 | MIDDLEWARE_CLASSES = ( 100 | 'django.middleware.common.CommonMiddleware', 101 | 'django.contrib.sessions.middleware.SessionMiddleware', 102 | 'django.middleware.csrf.CsrfViewMiddleware', 103 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 104 | 'django.contrib.messages.middleware.MessageMiddleware', 105 | # Uncomment the next line for simple clickjacking protection: 106 | # 'django.middleware.clickjacking.XFrameOptionsMiddleware', 107 | ) 108 | 109 | ROOT_URLCONF = 'pedido_project.urls' 110 | 111 | # Python dotted path to the WSGI application used by Django's runserver. 112 | WSGI_APPLICATION = 'pedido_project.wsgi.application' 113 | 114 | TEMPLATE_DIRS = ( 115 | os.path.join(BASE_DIR, 'templates/'), 116 | # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 117 | # Always use forward slashes, even on Windows. 118 | # Don't forget to use absolute paths, not relative paths. 119 | ) 120 | 121 | INSTALLED_APPS = ( 122 | 'django.contrib.auth', 123 | 'django.contrib.contenttypes', 124 | 'django.contrib.sessions', 125 | 'django.contrib.sites', 126 | 'django.contrib.messages', 127 | 'django.contrib.staticfiles', 128 | 'south', 129 | 'pedido', 130 | 'django.contrib.admin', 131 | 'django_extensions', 132 | # 'django.contrib.admindocs', 133 | ) 134 | 135 | SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' 136 | 137 | # A sample logging configuration. The only tangible logging 138 | # performed by this configuration is to send an email to 139 | # the site admins on every HTTP 500 error when DEBUG=False. 140 | # See http://docs.djangoproject.com/en/dev/topics/logging for 141 | # more details on how to customize your logging configuration. 142 | LOGGING = { 143 | 'version': 1, 144 | 'disable_existing_loggers': False, 145 | 'filters': { 146 | 'require_debug_false': { 147 | '()': 'django.utils.log.RequireDebugFalse' 148 | } 149 | }, 150 | 'handlers': { 151 | 'mail_admins': { 152 | 'level': 'ERROR', 153 | 'filters': ['require_debug_false'], 154 | 'class': 'django.utils.log.AdminEmailHandler' 155 | } 156 | }, 157 | 'loggers': { 158 | 'django.request': { 159 | 'handlers': ['mail_admins'], 160 | 'level': 'ERROR', 161 | 'propagate': True, 162 | }, 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /pedido/modelagem/pedido.sql: -------------------------------------------------------------------------------- 1 | -- Criando schema 2 | CREATE SCHEMA pedidos; 3 | USE pedidos; 4 | 5 | -- Criando as tabelas 6 | CREATE TABLE clientes ( 7 | idCliente INT AUTO_INCREMENT PRIMARY KEY, 8 | nome VARCHAR(50) 9 | ); 10 | CREATE TABLE categorias ( 11 | idCategoria INT AUTO_INCREMENT PRIMARY KEY, 12 | categoria VARCHAR(50) 13 | ); 14 | CREATE TABLE produtos ( 15 | idProduto INT AUTO_INCREMENT PRIMARY KEY, 16 | produto VARCHAR(50), 17 | preco DECIMAL(2), 18 | idCategoria INT, 19 | FOREIGN KEY (idCategoria) REFERENCES categorias(idCategoria) 20 | ); 21 | CREATE TABLE pedidos ( 22 | idPedido INT AUTO_INCREMENT PRIMARY KEY, 23 | dataPedido DATETIME, 24 | idCliente INT, 25 | FOREIGN KEY (idCliente) REFERENCES clientes(idCliente) 26 | ); 27 | CREATE TABLE detPedidos ( 28 | iddetPedido INT AUTO_INCREMENT PRIMARY KEY, 29 | quantidade INT, 30 | idPedido INT, 31 | idProduto INT, 32 | FOREIGN KEY (idPedido) REFERENCES pedidos(idPedido), 33 | FOREIGN KEY (idProduto) REFERENCES produtos(idProduto) 34 | ); 35 | 36 | -- Populando clientes 37 | INSERT INTO clientes (nome) VALUES ('Amanda'); 38 | INSERT INTO clientes (nome) VALUES ('Beatriz'); 39 | INSERT INTO clientes (nome) VALUES ('Carla'); 40 | INSERT INTO clientes (nome) VALUES ('Denise'); 41 | INSERT INTO clientes (nome) VALUES ('Eloisa'); 42 | INSERT INTO clientes (nome) VALUES ('Fernanda'); 43 | INSERT INTO clientes (nome) VALUES ('Gabriela'); 44 | INSERT INTO clientes (nome) VALUES ('Isadora'); 45 | INSERT INTO clientes (nome) VALUES ('Joana'); 46 | 47 | -- Populando categorias 48 | INSERT INTO categorias (categoria) VALUES ('Cama Mesa Banho'); 49 | INSERT INTO categorias (categoria) VALUES ('Eletrodomestico'); 50 | INSERT INTO categorias (categoria) VALUES ('Informatica'); 51 | INSERT INTO categorias (categoria) VALUES ('Movel'); 52 | INSERT INTO categorias (categoria) VALUES ('Roupa'); 53 | INSERT INTO categorias (categoria) VALUES ('Som'); 54 | INSERT INTO categorias (categoria) VALUES ('Video'); 55 | 56 | -- Populando produtos 57 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (1, 'Toalha de mesa', 45); 58 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (2, 'Geladeira', 1200); 59 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (2, 'Fogao', 600); 60 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (3, 'Notebook', 1200); 61 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (3, 'Tablet', 900); 62 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (3, 'Ultrabook', 2100); 63 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (4, 'Sofa', 1500); 64 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (4, 'Cama', 800); 65 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (4, 'Cadeira', 400); 66 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (4, 'Mesa', 1450); 67 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (5, 'Calca', 59.99); 68 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (5, 'Camisa', 44.99); 69 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (5, 'Blusa', 80.90); 70 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (5, 'Short', 40.50); 71 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (5, 'Meia', 15.25); 72 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (6, 'CD Player', 180); 73 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (6, 'Microsystem', 1350.75); 74 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (7, 'TV', 1459.99); 75 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (7, 'Blue Ray', 724.99); 76 | INSERT INTO produtos (idCategoria, produto, preco) VALUES (7, 'Home Teather', 1879.99); 77 | 78 | -- Populando pedidos 79 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-01', 1); 80 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-01', Null); 81 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-02', 1); 82 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-02', 2); 83 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-03', Null); 84 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-03', 3); 85 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-04', 3); 86 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-05', Null); 87 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-07', Null); 88 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-08', 4); 89 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-08', 4); 90 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-09', Null); 91 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-09', 5); 92 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-10', 6); 93 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-10', 6); 94 | INSERT INTO pedidos (dataPedido, idCliente) VALUES ('2013-10-10', Null); 95 | 96 | 97 | -- Populando detPedidos 98 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (1, 1, 16); 99 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (1,2, 20); 100 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (1,3, 12); 101 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (1,3, 11); 102 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (2,2, 1); 103 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (2,1, 5); 104 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (2,5, 3); 105 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (3,10, 2); 106 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (3,20, 8); 107 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (3,15, 9); 108 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (3,15, 12); 109 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (3,12, 20); 110 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (4,13, 22); 111 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (5,14, 17); 112 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (5,7, 19); 113 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (6,7, 4); 114 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (6,7, 6); 115 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (7,8, 3); 116 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (7,9, 5); 117 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (7,10, 2); 118 | INSERT INTO detPedidos (idPedido, idProduto, quantidade) VALUES (8,12, 1); 119 | 120 | -- Mostrando o nome dos clientes que fizeram um pedido 121 | SELECT DISTINCT nome 122 | FROM clientes C 123 | INNER JOIN pedidos P 124 | ON C.idCliente = P.idCliente; 125 | --------------------------------------------------------------------------------