4
respostas

[Dúvida] Criação das tabelas do SQLite

Olá, tudo bem? Estou tendo um problema com o desenvolvimento de um banco de dados mobile utilziando o SQLite no React Native, o banco de dados tem no total 11 tabelas, porém durante a execução as últimas duas tabelas (item_orders e order_payments) retornam erro. Quando peço para retornar o erro recebo undefined.

Info

"react": "18.2.0",
"react-native": "0.71.4",
"react-native-sqlite-storage": "^6.0.1",
"@types/react": "^18.0.24",
"@types/react-native": "^0.71.3",
"@types/react-native-sqlite-storage": "^6.0.0",
"typescript": "4.8.4"

Observação: vou adicionar os códigos aparte pois ultrapassa a quantidade de caracteres. Desde já, obrigado

4 respostas

SQLite.tsx

import SQLite from 'react-native-sqlite-storage';

const openConection = () => {
    const db = SQLite.openDatabase({name: 'db.db'})
    return db
}

export const db = openConection();

Tables.tsx

import { db } from './SQLite';

export const createTable = async () => {
    // Criação da tabela categories
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS categories (' +
            '  id INTEGER PRIMARY KEY NOT NULL,' +
            '  image BLOB NULL,' +
            '  name VARCHAR(45) NOT NULL,' +
            '  description VARCHAR(250) NULL,' +
            '  father INTEGER NULL,' +
            '  active TINYINT(1) NOT NULL DEFAULT 1,' +
            '  creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            '  modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            '  FOREIGN KEY (father) REFERENCES categories(id)' +
            ');'
            , [], () => console.log(`Tabela categories criada com sucesso`), () => console.log(`Erro ao criar a tabela categories`))
    });
    // Criação da tabela brands
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS brands (' +
            '  id INTEGER PRIMARY KEY NOT NULL,' +
            '  image BLOB NULL,' +
            '  name VARCHAR(45) NOT NULL,' +
            '  active TINYINT(1) NOT NULL DEFAULT 1,' +
            '  creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            '  modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP' +
            ');'
            , [], () => console.log(`Tabela brands criada com sucesso`), () => console.log(`Erro ao criar a tabela brands`))
    });
    // Criação da tabela products
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS products (' +
            '  id INTEGER PRIMARY KEY NOT NULL,' +
            '  id_category INTEGER NOT NULL,' +
            '  id_brand INTEGER NOT NULL,' +
            '  image BLOB NULL,' +
            '  name VARCHAR(45) NOT NULL,' +
            '  description VARCHAR(250) NULL,' +
            '  price DECIMAL(10,2) NOT NULL,' +
            '  active TINYINT(1) NOT NULL DEFAULT 1,' +
            '  creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            '  modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            '  FOREIGN KEY (id_category) REFERENCES categories(id),' +
            '  FOREIGN KEY (id_brand) REFERENCES brands(id)' +
            ');'
            , [], () => console.log(`Tabela products criada com sucesso`), () => console.log(`Erro ao criar a tabela products`))
    });
    // Criação da tabela clients
    (await db).transaction(tx => {
        tx.executeSql(
            `CREATE TABLE IF NOT EXISTS clients (
                id TEXT NOT NULL PRIMARY KEY,
                id_server INT NULL,
                id_seller INT NOT NULL,
                name VARCHAR(45) NOT NULL,
                type VARCHAR(4) NOT NULL CHECK(type IN ("CPF", "CNPJ")),
                birth_or_founding DATE NOT NULL,
                phone CHAR(13) NOT NULL,
                email VARCHAR(320) NOT NULL,
                status VARCHAR(15) NOT NULL DEFAULT 'waitingForSync',
                active INT NOT NULL DEFAULT 1,
                creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                UNIQUE(id_server),
                UNIQUE(name),
                UNIQUE(phone),
                UNIQUE(email)
              );`
            , [], () => console.log(`Tabela clients criada com sucesso`), () => console.log(`Erro ao criar a tabela clients`))
    });
    // Criação da tabela corporate_clients
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS corporate_clients (' +
            'id TEXT NOT NULL PRIMARY KEY,' +
            'fantasy_name VARCHAR(45) NOT NULL,' +
            'cnpj CHAR(14) NOT NULL,' +
            'state_registration CHAR(14) NULL,' +
            'municipal_registration CHAR(11) NULL,' +
            'legal_nature TEXT NULL,' +
            'UNIQUE (id),' +
            'UNIQUE (cnpj),' +
            'UNIQUE (municipal_registration),' +
            'UNIQUE (state_registration),' +
            'FOREIGN KEY (id) REFERENCES clients(id) ' +
            'ON DELETE NO ACTION ' +
            'ON UPDATE NO ACTION' +
            ');'
            , [], () => console.log(`Tabela corporate_clients criada com sucesso`), () => console.log(`Erro ao criar a tabela corporate_clients`))
    });
    /*Continua no próximo tópico*/
    });
}

Restante do código da função createTable 1/2

// Criação da tabela natural_person_clients
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS natural_person_clients (' +
            'id TEXT NOT NULL PRIMARY KEY,' +
            'cpf CHAR(11) NOT NULL UNIQUE,' +
            'rg CHAR(9) NULL UNIQUE,' +
            'FOREIGN KEY (id) REFERENCES clients(id) ON DELETE NO ACTION ON UPDATE NO ACTION' +
            ');'
            , [], () => console.log(`Tabela natural_person_clients criada com sucesso`), () => console.log(`Erro ao criar a tabela natural_person_clients`))
    });
    // Criação da tabela address_clients
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS addresses_clients (' +
            'id TEXT PRIMARY KEY NOT NULL UNIQUE,' +
            'road VARCHAR(100) NOT NULL,' +
            'number VARCHAR(10) NOT NULL,' +
            'neighborhood VARCHAR(100) NOT NULL,' +
            'complement VARCHAR(50) NULL,' +
            'city VARCHAR(100) NOT NULL,' +
            'state CHAR(2) NOT NULL,' +
            'zip_code CHAR(8) NOT NULL,' +
            'FOREIGN KEY (id) REFERENCES clients(id) ON DELETE NO ACTION ON UPDATE NO ACTION' +
            ');'
            , [], () => console.log(`Tabela addresses_clients criada com sucesso`), () => console.log(`Erro ao criar a tabela addresses_clients`))
    });
    // Criação da tabela payment_methods
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS payment_methods (' +
            'id INTEGER NOT NULL PRIMARY KEY,' +
            'name VARCHAR(45) NOT NULL UNIQUE,' +
            'description VARCHAR(250) NULL,' +
            'charge DECIMAL(10,2) NOT NULL DEFAULT 0,' +
            'deadline INTEGER NOT NULL DEFAULT 1,' +
            'maximum_installments INTEGER NOT NULL DEFAULT 1,' +
            'active INTEGER NOT NULL DEFAULT 1,' +
            'creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            'modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            'UNIQUE (name)' +
            ');'
            , [], () => console.log(`Tabela payment_methods criada com sucesso`), () => console.log(`Erro ao criar a tabela payment_methods`))
    });
    // Criação da tabela orders
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS orders (' +
            'id TEXT NOT NULL PRIMARY KEY,' +
            'id_server INT NULL,' +
            'id_client TEXT NOT NULL,' +
            'id_payment INT NOT NULL,' +
            'id_seller INT NOT NULL,' +
            'amount DECIMAL(20,2) NOT NULL,' +
            'date DATETIME NOT NULL,' +
            'status TEXT NOT NULL DEFAULT "waitingForSync" CHECK(status IN ("waitingForSync", "synced", "inSeparation", "waitingToBeSent", "sent", "delivered", "returned", "canceled", "concluded", "underObservation", "latePayment", "awaitingPayment")),' +
            'active TINYINT(1) NOT NULL DEFAULT 1,' +
            'creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            'modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
            'UNIQUE (id_server),' +
            'UNIQUE (id),' +
            'FOREIGN KEY (id_client) REFERENCES clients(id) ON DELETE NO ACTION ON UPDATE NO ACTION,' +
            'FOREIGN KEY (id_payment) REFERENCES payment_methods(id) ON DELETE NO ACTION ON UPDATE NO ACTION' +
            ');'
            , [], () => console.log(`Tabela orders criada com sucesso`), () => console.log(`Erro ao criar a tabela orders`)
        );
    });
    // Criação da tabela item_orders
    (await db).transaction(tx => {
        tx.executeSql(
            'CREATE TABLE IF NOT EXISTS item_orders (' +
            'id_order TEXT NOT NULL,' +
            'id_product INT NOT NULL,' +
            'amount DECIMAL(10,2) NOT NULL,' +
            'unitary_value DECIMAL(20,2) NOT NULL,' +
            'description VARCHAR(250) NULL,' +
            'PRIMARY KEY (id_order, id_product),' +
            'FOREIGN KEY (id_order) REFERENCES orders(id) ON DELETE NO ACTION ON UPDATE NO ACTION,' +
            'FOREIGN KEY (id_product) REFERENCES products(id) ON DELETE NO ACTION ON UPDATE NO ACTION,' +
            'INDEX id_product_idx (id_product ASC)' +
            ');'
            , [], () => console.log('Tabela item_orders criada com sucesso'), () => console.log('Erro ao criar a tabela item_orders')
        );
    });

Restante do código da função createTable 2/2

// Criação da tabela order_payments
(await db).transaction(tx => {
    tx.executeSql(
        'CREATE TABLE IF NOT EXISTS order_payments (' +
        'id_order TEXT NOT NULL,' +
        'id_payment INT NOT NULL,' +
        'description VARCHAR(250) NULL,' +
        'date DATETIME NOT NULL,' +
        'PRIMARY KEY (id_order, id_payment),' +
        'FOREIGN KEY (id_order) REFERENCES orders(id) ON DELETE NO ACTION ON UPDATE NO ACTION,' +
        'FOREIGN KEY (id_payment) REFERENCES payment_methods(id) ON DELETE NO ACTION ON UPDATE NO ACTION,' +
        'INDEX id_payment_idx (id_payment ASC)' +
        ');'
        , [], () => console.log(`Tabela order_payments criada com sucesso`), (tx, e) => console.log(`Erro ao criar a tabela order_payments`, e)
    )

Olá Gustavo, tudo bem?

Entendo que você esteja enfrentando problemas na criação das últimas duas tabelas do seu banco de dados utilizando SQLite no React Native. É importante analisar o código para identificar o que pode estar causando o erro.

Uma possível causa para o retorno de undefined ao solicitar o erro é que pode haver algum problema na execução do código responsável pela criação dessas tabelas. Verifique se você está utilizando as consultas corretas para criar as tabelas item_orders e order_payments, e se os nomes das tabelas estão corretamente escritos no código.

Além disso, verifique se você está utilizando a versão correta do pacote react-native-sqlite-storage em seu projeto. Certifique-se de que a versão 6.0.1 é compatível com as versões do React Native e das dependências que você está utilizando.

Caso você possa fornecer os trechos de código relacionados à criação das tabelas item_orders e order_payments, posso tentar ajudar de forma mais específica.

Espero ter ajudado e bons estudos!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software