· 8 years ago · Jun 06, 2018, 07:16 PM
1import { Injectable } from '@angular/core';
2import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
3
4@Injectable()
5export class DatabaseProvider {
6
7 public MensagemDeErro : String = "";
8 public bancoCriado : boolean = false;
9
10 constructor(private sqlite: SQLite) {
11
12 }
13
14 public getDB() {
15 this.MensagemDeErro = "Provider getBD";
16 let db = this.sqlite.create({
17 name: 'produto.db',
18 location: 'default'
19 });
20 this.MensagemDeErro = "Banco antes return";
21 return db;
22 }
23
24 public createDatabase() {
25 return this.getDB()
26 .then((db: SQLiteObject) => {
27
28 // Criando as tabelas
29 this.bancoCriado = true;
30 this.createTables(db);
31
32 })
33 .catch(e => console.log(e));
34
35
36 }
37
38 private createTables(db: SQLiteObject) {
39 // Criando as tabelas
40 db.sqlBatch([
41 ['CREATE TABLE IF NOT EXISTS categoria ' +
42 ' (idCategoria integer primary key AUTOINCREMENT NOT NULL, ' +
43 ' descricao VARCHAR (100))'],
44 ['CREATE TABLE IF NOT EXISTS enderecos (idendereco integer primary key AUTOINCREMENT NOT NULL, cep TEXT, rua TEXT, bairro TEXT, numero TEXT)'],
45 ['CREATE TABLE IF NOT EXISTS usuarios (idusuario integer primary key AUTOINCREMENT NOT NULL, nome TEXT, email TEXT, usuario TEXT, senha TEXT, idendereco integer, FOREIGN KEY(idendereco) references usuarios(idendereco))'],
46 ['CREATE TABLE IF NOT EXISTS ' +
47 ' produto (idProduto INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,' +
48 ' nomeProduto VARCHAR (100) NOT NULL COLLATE NOCASE,' +
49 ' valorProduto DECIMAL (10, 2) NOT NULL, ' +
50 ' quantidadeEstoque INTEGER NOT NULL,' +
51 ' ativo BOOLEAN not null,' +
52 ' dataValidadeProduto date not null, ' +
53 ' fotoProduto text not null, ' +
54 ' idCategoria INTEGER NOT NULL REFERENCES categoria (IdCategoria) );']
55 ])
56 .then(() => console.log('Tabelas criadas'))
57 .catch(e => console.error('Erro ao criar as tabelas', e));
58 }
59
60}