Sqlite SELECT last_insert_rowid() 因为lastId 返回0

问题描述 投票:0回答:1

现在我正在开发一个 Ionic 7/Angular 18 项目,我需要在 sqlite db 中保存 Ventas(销售)和属于该销售的产品,所以我首先保存 venta,然后保存产品,如下所示我需要 idventa 在我使用“SELECT last_insert_rowid() as lastId”的产品中引用,但我总是得到 0 而不是我应该得到的整数。 ventas和productos_ventas记录在数据库中只是productos_venta表中的idventa为0的问题。

{
    "name": "ventas",
    "schema": [
        { "column": "idventa", "value": "INTEGER PRIMARY KEY AUTOINCREMENT" },
        { "column": "idcliente", "value": "INTEGER NOT NULL" },
        { "column": "idusuario", "value": "INTEGER" },
        { "column": "monto_total", "value": "REAL" },
        { "column": "fecha", "value": "TEXT NOT NULL" }
    ]
},  
{
    "name": "productos_ventas",
    "schema": [
        { "column": "idproducto_venta", "value": "INTEGER PRIMARY KEY AUTOINCREMENT" },
        { "column": "idproducto", "value": "INTEGER NOT NULL" },
        { "column": "idventa", "value": "INTEGER NOT NULL" },
        { "column": "cantidad", "value": "INTEGER NOT NULL" },
        { "column": "precio", "value": "REAL NOT NULL" },          
        { "column": "monto", "value": "REAL" }
    ]
}

这是代码:

async saveVentaL(
    venta: { idcliente: number, idusuario: number, monto_total: number, fecha: string },
    productos_ventas: { idproducto: number, cantidad: number, precio: number, monto: number }[]
): Promise<{ ventaId: number; changes: capSQLiteChanges }> {
    console.log("Starting to save venta locally: ", venta, productos_ventas);
  
    const ventaSql = 'INSERT INTO ventas (idcliente, idusuario, monto_total, fecha) VALUES (?, ?, ?, ?)';
    const productosVentasSql = 'INSERT INTO productos_ventas (idventa, idproducto, cantidad, precio, monto) VALUES (?, ?, ?, ?, ?)';
    const dbName = await this.getDbName();
  
    // Insert venta
    const ventaChanges: capSQLiteChanges = await CapacitorSQLite.run({      
        database: dbName,
        statement: ventaSql,
        values: [venta.idcliente, venta.idusuario, venta.monto_total, venta.fecha]
    });

    if (this.isWeb) {
        await CapacitorSQLite.saveToStore({ database: dbName });
    }

    const ventaId = await this.queryLastInsertRowId();
    console.log("Venta ID: ", ventaId);

    // Prepare statements for productos_ventas
    const statements: any[] = productos_ventas.map(pv => ({
        statement: productosVentasSql,
        values: [ventaId, pv.idproducto, pv.cantidad, pv.precio, pv.monto]
    }));

// Insert productos_ventas
const productosVentasChanges: capSQLiteChanges = await CapacitorSQLite.executeSet({
    database: dbName,
    set: statements
});

if (this.isWeb) {
    await CapacitorSQLite.saveToStore({ database: dbName });
}

console.log("Changes after saving productos_ventas locally: ", productosVentasChanges);
return { ventaId, changes: productosVentasChanges };
}

private async queryLastInsertRowId(): Promise<number> {
    const dbName = await this.getDbName();
    const sql = 'SELECT last_insert_rowid() as lastId';
    return CapacitorSQLite.query({
        database: dbName,
        statement: sql,
        values: [],
    }).then((response: capSQLiteValues) => {
        const lastId = response.values?.[0]?.lastId;
        if (lastId !== undefined) {
            return lastId;
        } else {
          throw new Error('Failed to retrieve last insert row ID.');
        }
    });
}

`

我只是尝试调试,但我一无所知。我期待得到正确的身份

Starting to save venta locally:  
{idcliente: 1, idusuario: 2, monto_total: 240, fecha: '2024-07-09T07:32:15.541Z'} [{…}]
sqlite.service.ts:279 
Venta ID:  0
sqlite.service.ts:297 
Changes after saving productos_ventas locally:  {changes: {…}}
venta.page.ts:96 
Venta saved locally successfully: {ventaId: 0, changes: {…}}
venta.page.ts:102 
idventa is undefined. Full response: {ventaId: 0, changes: {…}}changes: {changes:    {…}}ventaId: 0[[Prototype]]: Object
(anonymous) @ venta.page.ts:102
venta.page.ts:107 
Venta save operation completed.
angular sqlite capacitor-plugin ionic7
1个回答
0
投票

Promise 不会等待返回,因此 then 块内的代码(异步)将在 then 块下面的代码(同步)之后执行。因此,您应该使用

await
等待响应然后返回,而不使用
then
块。

private async queryLastInsertRowId(): Promise<number> {
    const dbName = await this.getDbName();
    const sql = 'SELECT last_insert_rowid() as lastId';
    const response: capSQLiteValues = await CapacitorSQLite.query({
        database: dbName,
        statement: sql,
        values: [],
    });
    const lastId = response.values?.[0]?.lastId;
    if (lastId !== undefined) {
        return lastId;
    } else {
      throw new Error('Failed to retrieve last insert row ID.');
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.