WiseLibs / better-sqlite3

The fastest and simplest library for SQLite3 in Node.js.
MIT License
5.26k stars 391 forks source link

handling run() vs all() #1069

Closed agad closed 10 months ago

agad commented 10 months ago

I am working on an app where the type of statement sent to sqlite is not known until run time - ie: select that returns data or op that returns no data. So I don't know in advance if I should execute all or run. The way I handle it now is very naive but seems to work.

let stmt
try {
  stmt = this._db.prepare( command );
  const results = params ? stmt.all( params )  : stmt.all(  )  
  resolve( { rows: results, rowCount: results.length } )
  return
} catch ( err ) {
  if ( !err.message.toLowerCase().includes('run() instead')  ) {
    reject( new DatabaseError( err.message ) )
    return
  }
}

// dropped here because need to use run instead
try {
  const results = params ? stmt.run( params )  : stmt.run(  )  
  resolve( { rows: [], rowCount: results.changes } )
} catch ( err ) {
  reject( new DatabaseError( err.message ) )
}

})

Is this the appropriate way to address this issue? Is there an internal call I can make that would let me know in advance whether the query type returns data? I guess I could generate an AST and then go through that but was hoping there was a simpler approach.

Prinzhorn commented 10 months ago

if(stmt.reader) see https://github.com/WiseLibs/better-sqlite3/blob/master/docs/api.md#properties-1