-1
I was developing an application using the React-Native-sqlite-Storage but I came across a very strange problem, time my code works and time does not, I can not understand, to try to investigate I came to the following code:
/* Conexão */
const db = SQLite.openDatabase(
'candy.db',
'1.0',
'candy',
20000,
() => console.log('banco de dados aberto'),
(error) => console.log('error', error),
);
/* Objeto estático para teste */
const order = {
items: [{
nome: "Snickers",
quantidade: 1,
preco: 3,
codigo_de_barras: 123
},
{
nome: "Bala de goma",
quantidade: 1,
preco: 1,
codigo_de_barras: 1234
},
],
cliente: {
id: 1
},
status: "NAO PROCESSADO"
};
/* Transação */
db.transaction(tx => {
tx.executeSql(
"INSERT INTO pedidos (id_usuario,status) VALUES (?,?)", [order.cliente.id, order.status],
() => {},
(e) => console.log(e)
)
/* Parte que ocorre o erro */
order.items.forEach(produto => {
db.executeSql(
`INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade, preco)
VALUES((SELECT last_insert_rowid()+1 from pedidos), ?,?,?)`, [produto.codigo_de_barras, produto.quantidade, produto.preco],
() => console.log(produto, "inserido com sucesso no banco de dados"),
(e) => console.log(e)
)
})
})
The strange thing is that I have two items in order.items both items are displayed on the console but are not always entered in the database, this part does not make sense to me because then going through the same function together. If it were still the case that they will be inserted as different times would make sense to me because this library offers support for precedents that I am not using at the moment, but even this strange behavior I was able to develop normal. Can someone give me a direction of what to do?? I no longer have ideas.
I discovered the problem was in this SQL :
INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade, preco) VALUES((SELECT last_insert_rowid()+1 from pedidos)
, I switched to :INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade,preco) VALUES ((SELECT id FROM pedidos ORDER BY id DESC LIMIT 1),?,?,?)
and everything worked, I will choose your question and as soon as you free up the time of Bounty I make you beautiful, it was well worth it were not your answer and I do not know if I would ever touch this project again.– Rodrigo Gabriel