void StatementHandle::finalize()
{
    if (m_stmt) {
        sqlite3 *handle = sqlite3_db_handle((sqlite3_stmt *) m_stmt);
        int rc = sqlite3_finalize((sqlite3_stmt *) m_stmt);
        m_stmt = nullptr;
        if (rc == SQLITE_OK) {
            m_error.reset();
            return;
        }
        Error::ReportSQLite(m_handle.getTag(), m_handle.path,
                            Error::HandleOperation::Finalize, rc,
                            sqlite3_extended_errcode(handle),
                            sqlite3_errmsg(handle), &m_error);
    }
}
Beispiel #2
0
/* call-seq: stmt.close
 *
 * Closes the statement by finalizing the underlying statement
 * handle. The statement must not be used after being closed.
 */
static VALUE sqlite3_rb_close(VALUE self)
{
  sqlite3StmtRubyPtr ctx;
  sqlite3 * db;

  Data_Get_Struct(self, sqlite3StmtRuby, ctx);

  REQUIRE_OPEN_STMT(ctx);

  db = sqlite3_db_handle(ctx->st);
  CHECK(db, sqlite3_finalize(ctx->st));

  ctx->st = NULL;

  return self;
}
    bool step_next ()
    {
        const int status = sqlite3_step (stmt_);
        if (status != SQLITE_ROW && status != SQLITE_DONE)
        {
            std::ostringstream s;
            s << "SQLite Plugin: retrieving next row failed";
            std::string msg(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
            if (msg != "unknown error")
            {
                s << ": " << msg;
            }

            throw mapnik::datasource_exception(s.str());
        }
        return status == SQLITE_ROW;
    }
Beispiel #4
0
static int
bindargs(lua_State *T, sqlite3_stmt *stmt)
{
	int top = lua_gettop(T);
	int i;

	for (i = 2; i <= top; i++) {
		int ret;

		switch (lua_type(T, i)) {
		case LUA_TNIL:
			/* Should nil mean NULL..
			ret = sqlite3_bind_null(stmt, i-1);
			break;
			..or don't bind.. */
			continue;

		case LUA_TNUMBER:
			ret = sqlite3_bind_double(stmt, i-1,
					lua_tonumber(T, i));
			break;

		case LUA_TSTRING:
			{
				size_t len;
				const char *str = lua_tolstring(T, i, &len);

				ret = sqlite3_bind_text(stmt, i-1,
						str, len, SQLITE_STATIC);
			}
			break;

		default:
			(void)sqlite3_clear_bindings(stmt);
			return luaL_argerror(T, i, "expected nil, number or string");
		}

		if (ret != SQLITE_OK) {
			(void)sqlite3_clear_bindings(stmt);
			return luaL_argerror(T, i, sqlite3_errmsg(
						sqlite3_db_handle(stmt)));
		}
	}
	return 0;
}
SqlStatement &SqlStatement::execute() {
	require(mpVM);
	mBindNext = 1; // Next call to bind() should replace the first parameter (it's not zero-indexed)
	if (!mEndOfRows)
		sqlite3_reset(mpVM); // User wants to reset the query even though we haven't finished going through all rows...
	const int result = sqlite3_step(mpVM);
	if (result == SQLITE_DONE) {
		mEndOfRows = true; // No rows were returned
		mColsInResult = 0;
		return *this;
	} else if (result == SQLITE_ROW) {
		mEndOfRows = false; // At least one row was returned
		mColsInResult = sqlite3_column_count(mpVM);
		return *this;
	} else {
		throw SqlDatabaseException(sqlite3_errmsg(sqlite3_db_handle(mpVM)));
	}
}
int
lms_db_bind_double(sqlite3_stmt *stmt, int col, double value)
{
    int r;

    r = sqlite3_bind_double(stmt, col, value);
    if (r == SQLITE_OK)
        return 0;
    else {
        sqlite3 *db;
        const char *err;

        db = sqlite3_db_handle(stmt);
        err = sqlite3_errmsg(db);
        fprintf(stderr, "ERROR: could not bind SQL value %d: %s\n", col, err);
        return -col;
    }
}
Beispiel #7
0
static int fetch(lua_State* L, int mode) {
	stmt* s = (stmt*)luaL_checkudata(L, 1, MT_STMT);
	sqlite3* db = sqlite3_db_handle(s->handle);
	int ret;
	while((ret = sqlite3_step(s->handle)) == SQLITE_SCHEMA) {}
	if(ret == SQLITE_DONE) {
		lua_pushnil(L);
		return 1;
	} else if(ret == SQLITE_ROW) {
		int i;
		int col_count = sqlite3_column_count(s->handle);
		lua_createtable(L, col_count, 0);
		for(i = 0; i < col_count; i++) {

			if(mode == 0) {
				/* fetch, rows */
				lua_pushstring(L, sqlite3_column_name(s->handle, i));
			} else if(mode == 1) {
				/* ifetch, irows */
				lua_pushinteger(L, i + 1);
			}

			switch(sqlite3_column_type(s->handle, i)) {
			case SQLITE_INTEGER:
				lua_pushinteger(L, sqlite3_column_int(s->handle, i));
				break;
			case SQLITE_FLOAT:
				lua_pushnumber(L, sqlite3_column_double(s->handle, i));
				break;
			case SQLITE_TEXT:
				lua_pushstring(L, (const char*)sqlite3_column_text(s->handle, i));
				break;
			case SQLITE_BLOB:
			case SQLITE_NULL:
				lua_pushnil(L);
				break;
			}
			lua_settable(L, -3);
		}
		return 1;

	}
	return luaL_error(L, "[%d] %s", ret, sqlite3_errmsg(db));
}
int
lms_db_update_file_info(sqlite3_stmt *stmt, const struct lms_file_info *finfo, unsigned int update_id)
{
    int r, ret;

    ret = lms_db_bind_int(stmt, 1, finfo->mtime);
    if (ret != 0)
        goto done;

    ret = lms_db_bind_int(stmt, 2, finfo->dtime);
    if (ret != 0)
        goto done;

    ret = lms_db_bind_int(stmt, 3, finfo->itime);
    if (ret != 0)
        goto done;

    ret = lms_db_bind_int(stmt, 4, finfo->size);
    if (ret != 0)
        goto done;

    ret = lms_db_bind_int(stmt, 5, update_id);
    if (ret != 0)
        goto done;

    ret = lms_db_bind_int(stmt, 6, finfo->id);
    if (ret != 0)
        goto done;

    r = sqlite3_step(stmt);
    if (r != SQLITE_DONE) {
        fprintf(stderr, "ERROR: could not update file info: %s\n",
                sqlite3_errmsg(sqlite3_db_handle(stmt)));
        ret = -5;
        goto done;
    }

    ret = 0;

  done:
    lms_db_reset_stmt(stmt);

    return ret;
}
void JNICALL Java_com_baidu_javalite_PrepareStmt_sqlite3_1bind_1zeroblob(
        JNIEnv *env, jclass cls, jlong handle, jint column, jint bytes)
{
  if (handle == 0)
  {
    throwSqliteException(env, "handle is NULL");
    return;
  }

  sqlite3_stmt* stmt = (sqlite3_stmt*) handle;

  int rc = sqlite3_bind_zeroblob(stmt, column, bytes);

  if (rc != SQLITE_OK)
  {
    sqlite3* conn = sqlite3_db_handle(stmt);
    throwSqliteException2(env, sqlite3_errcode(conn), sqlite3_errmsg(conn));
  }
}
Beispiel #10
0
static int
bindargs(lua_State *T, sqlite3_stmt *stmt)
{
	int top = lua_gettop(T);
	int i;

	for (i = 2; i <= top; i++) {
		int ret;

		ret = _bind_arg(T, i, stmt, i-1);

		if (ret != SQLITE_OK) {
			(void)sqlite3_clear_bindings(stmt);
			return luaL_argerror(T, i, sqlite3_errmsg(
						sqlite3_db_handle(stmt)));
		}
	}
	return 0;
}
void JNICALL Java_com_baidu_javalite_PrepareStmt_sqlite3_1reset(JNIEnv *env,
        jclass cls, jlong handle)
{
  if (handle == 0)
  {
    throwSqliteException(env, "handle is NULL");
    return;
  }

  sqlite3_stmt* stmt = (sqlite3_stmt*) handle;

  int rc = sqlite3_reset(stmt);

  if (rc != SQLITE_OK)
  {
    sqlite3* conn = sqlite3_db_handle(stmt);
    throwSqliteException2(env, sqlite3_errcode(conn), sqlite3_errmsg(conn));
  }
}
int Java_ua_boberproduction_floristx_sqlite_SQLiteCursor_step(JNIEnv* env, jobject object, int statementHandle) {
	sqlite3_stmt* handle = (sqlite3_stmt*)statementHandle;

	int errcode = 0 ;

        errcode = sqlite3_step(handle);
		if (errcode==SQLITE_ROW) 
		{
			return 0;
		}else if(errcode == SQLITE_DONE)
		{
			return 1;
		} 
		else if(errcode == SQLITE_BUSY)
		{
			return -1;
		}


	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
}
Beispiel #13
0
 bool step_next ()
 {
     const int status = sqlite3_step(stmt_);
     if (status != SQLITE_DONE)
     {
         std::ostringstream s;
         s << "SQLite Plugin: inserting bbox into rtree index failed";
         std::string msg(sqlite3_errmsg(sqlite3_db_handle(stmt_)));
         if (msg != "unknown error")
         {
             s << ": " << msg;
         }
         throw mapnik::datasource_exception(s.str());
     }
     sqlite3_clear_bindings(stmt_);
     if (sqlite3_reset(stmt_) != SQLITE_OK)
     {
         throw mapnik::datasource_exception("sqlite3_reset failed");
     }
     return true;
 }
int
lms_db_bind_int64_or_null(sqlite3_stmt *stmt, int col, int64_t *p_value)
{
    int r;

    if (p_value)
        r = sqlite3_bind_int64(stmt, col, *p_value);
    else
        r = sqlite3_bind_null(stmt, col);
    if (r == SQLITE_OK)
        return 0;
    else {
        sqlite3 *db;
        const char *err;

        db = sqlite3_db_handle(stmt);
        err = sqlite3_errmsg(db);
        fprintf(stderr, "ERROR: could not bind SQL value %d: %s\n", col, err);
        return -col;
    }
}
Beispiel #15
0
static int
bindtable(lua_State *T, sqlite3_stmt *stmt)
{
	int parameters = sqlite3_bind_parameter_count(stmt);
	const char *name;
	const char *err;
	int i;

	for (i = 1; i <= parameters; i++) {
		int ret;

		name = sqlite3_bind_parameter_name(stmt, i);
		lua_settop(T, 2);
		if (name == NULL || name[0] == '?')
			lua_rawgeti(T, 2, i);
		else if (name[0] == '@')
			lua_getfield(T, 2, name + 1);
		else
			lua_getfield(T, 2, name);

		ret = _bind_arg(T, 3, stmt, i);

		if (ret != SQLITE_OK) {
			err = sqlite3_errmsg(sqlite3_db_handle(stmt));
			goto error;
		}
	}
	return 0;

error:
	(void)sqlite3_clear_bindings(stmt);
	luaL_where(T, 1);
	if (name == NULL || name[0] == '?')
		lua_pushfstring(T, "error binding %d: %s", i, err);
	else
		lua_pushfstring(T, "error binding '%s': %s", name, err);
	lua_concat(T, 2);
	return -1;
}
int
lms_db_bind_blob(sqlite3_stmt *stmt, int col, const void *blob, int len)
{
    int r;

    if (blob)
        r = sqlite3_bind_blob(stmt, col, blob, len, SQLITE_STATIC);
    else
        r = sqlite3_bind_null(stmt, col);

    if (r == SQLITE_OK)
        return 0;
    else {
        sqlite3 *db;
        const char *err;

        db = sqlite3_db_handle(stmt);
        err = sqlite3_errmsg(db);
        fprintf(stderr, "ERROR: could not bind SQL value %d: %s\n", col, err);
        return -col;
    }
}
int
lms_db_delete_file_info(sqlite3_stmt *stmt, const struct lms_file_info *finfo)
{
    int r, ret;

    ret = lms_db_bind_int64(stmt, 1, finfo->id);
    if (ret != 0)
        goto done;

    r = sqlite3_step(stmt);
    if (r != SQLITE_DONE) {
        fprintf(stderr, "ERROR: could not delete file info: %s\n",
                sqlite3_errmsg(sqlite3_db_handle(stmt)));
        ret = -2;
        goto done;
    }
    ret = 0;

  done:
    lms_db_reset_stmt(stmt);

    return ret;
}
Beispiel #18
0
static int
stmt_reset(lua_State *T)
{
	struct stmt *stmt;
	int ret;

	luaL_checktype(T, 1, LUA_TUSERDATA);
	stmt = lua_touserdata(T, 1);
	if (stmt->handle == NULL)
		return stmt_finalized(T);
	if (stmt->db->T != NULL)
		return db_busy(T);

	ret = sqlite3_reset(stmt->handle);
	(void)sqlite3_clear_bindings(stmt->handle);
	if (ret != SQLITE_OK) {
		lua_pushnil(T);
		lua_pushstring(T, sqlite3_errmsg(sqlite3_db_handle(stmt->handle)));
		return 2;
	}

	lua_pushboolean(T, 1);
	return 1;
}
Beispiel #19
0
/*
** Execute SQL code.  Return one of the SQLITE_ success/failure
** codes.  Also write an error message into memory obtained from
** malloc() and make *pzErrMsg point to that message.
**
** If the SQL is a query, then for each row in the query result
** the xCallback() function is called.  pArg becomes the first
** argument to xCallback().  If xCallback=NULL then no callback
** is invoked, even for queries.
*/
int sqlite3_exec_stmt(
	sqlite3_stmt *pStmt,           /* The SQL to be executed */
	sqlite3_callback xCallback, /* Invoke this callback routine */
	void *pArg,                 /* First argument to xCallback() */
	char **pzErrMsg             /* Write error messages here */
	){
		int rc = SQLITE_OK;
		sqlite3 *db = 0;
		char **azCols = 0;

		int nRetry = 0;
		int nChange = 0;
		int nCallback;

		if( pStmt ==0 ) return SQLITE_OK;
		db = sqlite3_db_handle(pStmt);
		while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2))){
			int nCol;
			char **azVals = 0;

			nCallback = 0;

			nCol = sqlite3_column_count(pStmt);
			azCols = (char **) malloc(2*nCol*sizeof(const char *) + 1);
			if( azCols==0 ){
				goto exec_out;
			} 

			while( 1 ){
				int i;
				rc = sqlite3_step(pStmt);

				/* Invoke the callback function if required */
				if( xCallback && (SQLITE_ROW==rc ||
					(SQLITE_DONE==rc && !nCallback))
					){
						if( 0==nCallback ){
							for(i=0; i<nCol; i++){
								azCols[i] = (char *)sqlite3_column_name(pStmt, i);
							}
							nCallback++;
						}
						if( rc==SQLITE_ROW ){
							azVals = &azCols[nCol];
							for(i=0; i<nCol; i++){
								azVals[i] = (char *)sqlite3_column_text(pStmt, i);
							}

							if( xCallback(pArg, nCol, azVals, azCols) ){
								rc = SQLITE_ABORT;
								goto exec_out;
							}
						}
				}

				if( rc!=SQLITE_ROW ){                   
					break;
				}
			}
		}

exec_out:
		if( azCols ) free(azCols); 
		sqlite3_reset(pStmt);

		return rc;
}
Beispiel #20
0
/* call-seq: stmt.bind_param(key, value)
 *
 * Binds value to the named (or positional) placeholder. If +param+ is a
 * Fixnum, it is treated as an index for a positional placeholder.
 * Otherwise it is used as the name of the placeholder to bind to.
 *
 * See also #bind_params.
 */
static VALUE bind_param(VALUE self, VALUE key, VALUE value)
{
  sqlite3StmtRubyPtr ctx;
  int status;
  int index;

  Data_Get_Struct(self, sqlite3StmtRuby, ctx);
  REQUIRE_OPEN_STMT(ctx);

  switch(TYPE(key)) {
    case T_SYMBOL:
      key = rb_funcall(key, rb_intern("to_s"), 0);
    case T_STRING:
      if(RSTRING_PTR(key)[0] != ':') key = rb_str_plus(rb_str_new2(":"), key);
      index = sqlite3_bind_parameter_index(ctx->st, StringValuePtr(key));
      break;
    default:
      index = (int)NUM2INT(key);
  }

  if(index == 0)
    rb_raise(rb_path2class("SQLite3::Exception"), "no such bind parameter");

  switch(TYPE(value)) {
    case T_STRING:
      if(CLASS_OF(value) == cSqlite3Blob
              || rb_enc_get_index(value) == rb_ascii8bit_encindex()
        ) {
        status = sqlite3_bind_blob(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      } else {


        if (UTF16_LE_P(value) || UTF16_BE_P(value)) {
          status = sqlite3_bind_text16(
              ctx->st,
              index,
              (const char *)StringValuePtr(value),
              (int)RSTRING_LEN(value),
              SQLITE_TRANSIENT
              );
        } else {
          if (!UTF8_P(value) || !USASCII_P(value)) {
              value = rb_str_encode(value, rb_enc_from_encoding(rb_utf8_encoding()), 0, Qnil);
          }
        status = sqlite3_bind_text(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
        }
      }
      break;
    case T_BIGNUM: {
      sqlite3_int64 num64;
      if (bignum_to_int64(value, &num64)) {
          status = sqlite3_bind_int64(ctx->st, index, num64);
          break;
      }
    }
    case T_FLOAT:
      status = sqlite3_bind_double(ctx->st, index, NUM2DBL(value));
      break;
    case T_FIXNUM:
      status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)FIX2LONG(value));
      break;
    case T_NIL:
      status = sqlite3_bind_null(ctx->st, index);
      break;
    default:
      rb_raise(rb_eRuntimeError, "can't prepare %s",
          rb_class2name(CLASS_OF(value)));
      break;
  }

  CHECK(sqlite3_db_handle(ctx->st), status);

  return self;
}
Beispiel #21
0
static VALUE step(VALUE self)
{
  sqlite3StmtRubyPtr ctx;
  sqlite3_stmt *stmt;
  int value, length;
  VALUE list;
  rb_encoding * internal_encoding;

  Data_Get_Struct(self, sqlite3StmtRuby, ctx);

  REQUIRE_OPEN_STMT(ctx);

  if(ctx->done_p) return Qnil;

  {
      VALUE db          = rb_iv_get(self, "@connection");
      rb_funcall(db, rb_intern("encoding"), 0);
      internal_encoding = rb_default_internal_encoding();
  }

  stmt = ctx->st;

  value = sqlite3_step(stmt);
  length = sqlite3_column_count(stmt);
  list = rb_ary_new2((long)length);

  switch(value) {
    case SQLITE_ROW:
      {
        int i;
        for(i = 0; i < length; i++) {
          switch(sqlite3_column_type(stmt, i)) {
            case SQLITE_INTEGER:
              rb_ary_push(list, LL2NUM(sqlite3_column_int64(stmt, i)));
              break;
            case SQLITE_FLOAT:
              rb_ary_push(list, rb_float_new(sqlite3_column_double(stmt, i)));
              break;
            case SQLITE_TEXT:
              {
                VALUE str = rb_tainted_str_new(
                    (const char *)sqlite3_column_text(stmt, i),
                    (long)sqlite3_column_bytes(stmt, i)
                );
                rb_enc_associate_index(str, rb_utf8_encindex());
                if(internal_encoding)
                  str = rb_str_export_to_enc(str, internal_encoding);
                rb_ary_push(list, str);
              }
              break;
            case SQLITE_BLOB:
              {
                VALUE str = rb_tainted_str_new(
                    (const char *)sqlite3_column_blob(stmt, i),
                    (long)sqlite3_column_bytes(stmt, i)
                );
                rb_ary_push(list, str);
              }
              break;
            case SQLITE_NULL:
              rb_ary_push(list, Qnil);
              break;
            default:
              rb_raise(rb_eRuntimeError, "bad type");
          }
        }
      }
      break;
    case SQLITE_DONE:
      ctx->done_p = 1;
      return Qnil;
      break;
    default:
      sqlite3_reset(stmt);
      ctx->done_p = 0;
      CHECK(sqlite3_db_handle(ctx->st), value);
  }

  return list;
}
Beispiel #22
0
/* Return a data.frame containing the requested number of rows from
   the resultset.

   We try to determine the correct R type for each column in the
   result.  Currently, type detection happens only for the first fetch
   on a given resultset and the first row of the resultset is used for
   type interpolation.  If a NULL value appears in the first row of
   the resultset and the column corresponds to a DB table column, we
   guess the type based on the DB schema definition for the column.
   If the NULL value does not correspond to a table column, then we
   force character.
*/
SEXP rsqlite_query_fetch(SEXP handle, SEXP max_rec) {
  SQLiteResult* res = rsqlite_result_from_handle(handle);
  if (res->isSelect != 1) {
    warning("resultSet does not correspond to a SELECT statement");
    return R_NilValue;
  }
  if (res->completed == 1) {
    return R_NilValue;
  }

  /* We need to step once to be able to create the data mappings */
  int row_idx = 0;
  int state = do_select_step(res, row_idx);
  sqlite3_stmt* db_statement = (sqlite3_stmt*) res->drvResultSet;

  if (state != SQLITE_ROW && state != SQLITE_DONE) {
    error("rsqlite_query_fetch: failed first step: %s",
        sqlite3_errmsg(sqlite3_db_handle(db_statement)));
  }

  SQLiteFields* flds = rsqlite_result_fields(res);

  int num_fields = flds->num_fields;
  int num_rec = asInteger(max_rec);
  int expand = (num_rec < 0);   /* dyn expand output to accommodate all rows*/
  if (expand || num_rec == 0) {
    num_rec = rsqlite_driver()->fetch_default_rec;
  }

  SEXP output = PROTECT(NEW_LIST(num_fields));
  rsqlite_output_alloc(output, flds, num_rec);
  while (state != SQLITE_DONE) {
    fill_one_row(db_statement, output, row_idx, flds);
    row_idx++;
    if (row_idx == num_rec) {  /* request satisfied or exhausted allocated space */
      if (expand) {    /* do we extend or return the records fetched so far*/
        num_rec = 1.5 * num_rec;
        rsqlite_output_expand(output, flds, num_rec);
      } else {
        break;       /* okay, no more fetching for now */
      }
    }
    state = do_select_step(res, row_idx);
    if (state != SQLITE_ROW && state != SQLITE_DONE) {
      error("rsqlite_query_fetch: failed: %s",
          sqlite3_errmsg(sqlite3_db_handle(db_statement)));
    }
  } /* end row loop */

  if (state == SQLITE_DONE) {
    res->completed = 1;
  }

  /* size to actual number of records fetched */
  if (row_idx < num_rec) {
    num_rec = row_idx;
    /* adjust the length of each of the members in the output_list */
    for (int j = 0; j < num_fields; j++) {
      SEXP s_tmp = VECTOR_ELT(output, j);
      PROTECT(SET_LENGTH(s_tmp, num_rec));
      SET_VECTOR_ELT(output, j, s_tmp);
      UNPROTECT(1);
    }
  }
  res->rowCount += num_rec;
  UNPROTECT(1);
  return output;
}
Beispiel #23
0
bool DoStep(JSContext *cx, JS::HandleObject obj, JS::MutableHandleValue rval) {

	sqlite3_stmt *pStmt = (sqlite3_stmt*)JL_GetPrivate(obj);
	JL_ASSERT_THIS_OBJECT_STATE( pStmt );

	DatabasePrivate *dbpv;
	{

	JS::RootedValue dbVal(cx);
	JL_CHK( JL_GetReservedSlot(obj, SLOT_RESULT_DATABASE, &dbVal) );
	JL_ASSERT( dbVal.isObject() );


	JS::RootedObject dbValObj(cx, &dbVal.toObject());

	dbpv = (DatabasePrivate*)JL_GetPrivate(dbValObj);
	JL_ASSERT_OBJECT_STATE(dbpv, JL_GetClassName(dbValObj));

	}

	sqlite3 *db;
	db = dbpv->db;
	ASSERT( db == sqlite3_db_handle(pStmt) );

	{

	// check if bindings are up to date
	JS::RootedValue bindingUpToDate(cx);
	JL_CHK( JL_GetReservedSlot(obj, SLOT_RESULT_BINDING_UP_TO_DATE, &bindingUpToDate) );

	if ( bindingUpToDate != JSVAL_TRUE ) {

		JS::RootedValue queryArgument(cx);
		JS::RootedObject queryArgumentObj(cx);
		JL_CHK(jl::getSlot(cx, obj, SLOT_RESULT_QUERY_ARGUMENT_OBJECT, &queryArgumentObj));



		JL_CHK(SqliteSetupBindings(cx, pStmt, queryArgumentObj, obj)); // ":" use result object. "@" is the object passed to Query()
		JL_CHK( JL_SetReservedSlot(obj, SLOT_RESULT_BINDING_UP_TO_DATE, JL_TRUE) );
		// doc: The sqlite3_bind_*() routines must be called AFTER sqlite3_prepare() or sqlite3_reset() and BEFORE sqlite3_step().
		//      Bindings are not cleared by the sqlite3_reset() routine. Unbound parameters are interpreted as NULL.
	}

	}

	dbpv->tmpcx = cx;
	int status;
	status = sqlite3_step( pStmt ); // The return value will be either SQLITE_BUSY, SQLITE_DONE, SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
	dbpv->tmpcx = NULL;
	
	JL_CHK( !JL_IsExceptionPending(cx) );

	switch ( status ) {

		case SQLITE_ROW: // SQLITE_ROW is returned each time a new row of data is ready for processing by the caller
			rval.setBoolean(true);
			return true;
		case SQLITE_DONE: // means that the statement has finished executing successfully. sqlite3_step() should not be called again on this virtual machine without first calling sqlite3_reset() to reset the virtual machine back to its initial state.
			rval.setBoolean(false);
			return true;
		case SQLITE_MISUSE:
			// doc. means that the this routine was called inappropriately. Perhaps it was called on a virtual machine that had already been finalized or on one that had previously returned SQLITE_ERROR or SQLITE_DONE.
			//      Or it could be the case that a database connection is being used by a different thread than the one it was created it.
			// doc. If an interface fails with SQLITE_MISUSE, that means the interface was invoked incorrectly by the application. In that case, the error code and message may or may not be set.
			JL_CHK( SqliteThrowError(cx, db) );
//		case SQLITE_ERROR:
//		case SQLITE_SCHEMA: // (TBD) check for another error (doc. The database schema changed)
//			JL_CHK( SqliteThrowError(cx, db) );
	}
//	JL_REPORT_ERROR("invalid case (status:%d)", status );

	JL_CHK( SqliteThrowError(cx, db) );
	JL_BAD;
}
long long StatementHandle::getLastInsertedRowID()
{
    return sqlite3_last_insert_rowid(
        sqlite3_db_handle((sqlite3_stmt *) m_stmt));
}
int StatementHandle::getChanges()
{
    sqlite3 *handle = sqlite3_db_handle((sqlite3_stmt *) m_stmt);
    return sqlite3_changes((sqlite3 *) handle);
}
Beispiel #26
0
void sqlite_source::prepare_data(
	const std::string & database_name,
	const std::string & sql)
throw(
	std::logic_error,
	std::invalid_argument)
{
	check_not_running();
	delete_data();

	sqlite3_stmt* data = get_stmt(database_name, sql);

	int column_count = sqlite3_column_count(data);
	if (column_count == 0) //statement is no SELECT statement
	{
		throw std::invalid_argument("Statement is no SQL SELECT statement.");
	}

	m_data = data;
	m_column_count = column_count;
	m_time_column = sqlite3_bind_parameter_index(m_data, get_duration_string().c_str());
	m_database_name = database_name;
	m_sql = sql;


	std::vector<column_info> column_infos;

	sqlite3* db_handle = sqlite3_db_handle(m_data);

	char const* data_type = NULL;
	char const* coll_seq = NULL;
	int not_null = 0;
	int primary_key = 0;
	int auto_inc = 0;
	for (int i = 0; i < m_column_count; ++i)
	{
		std::string column_name = sqlite3_column_origin_name(m_data, i);
		int result_code = sqlite3_table_column_metadata(
			db_handle,
			sqlite3_column_database_name(m_data, i),
			sqlite3_column_table_name(m_data, i),
			column_name.c_str(),
			&data_type,
			&coll_seq,
			&not_null,
			&primary_key,
			&auto_inc);

		if (result_code != SQLITE_OK)
		{
			//TODO: do something with the error...this error can only be an internal db error
		}

		if (i + 1 != m_time_column)
		{
			std::string type(data_type);
			column_info info(column_name, m_source_name, get_data_type(data_type));
			column_infos.push_back(info);
		}
	}

	m_stream_schema = stream_schema_ptr(new stream_schema(m_source_name, column_infos));
}
/******************************************************************************
 *
 *                      Find/Query helper functions
 *
 * ****************************************************************************/
int
gf_sql_query_function (sqlite3_stmt              *prep_stmt,
                      gf_query_callback_t       query_callback,
                      void                      *_query_cbk_args)
{
        int ret = -1;
        gfdb_query_record_t *gfdb_query_record = NULL;
        char *text_column = NULL;
        sqlite3 *db_conn = NULL;

        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, prep_stmt, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, query_callback, out);

        db_conn = sqlite3_db_handle(prep_stmt);

        gfdb_query_record = gfdb_query_record_init ();
        if (!gfdb_query_record) {
                        gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                                LG_MSG_CREATE_FAILED, "Failed to create "
                                "gfdb_query_record");
                                goto out;
        }

        /*Loop to access queried rows*/
        while ((ret = sqlite3_step (prep_stmt)) == SQLITE_ROW) {

                /*Clear the query record*/
                memset (gfdb_query_record, 0, sizeof(*gfdb_query_record));

                if (sqlite3_column_count(prep_stmt) > 0) {

                        /*Retriving GFID - column index is 0*/
                        text_column = (char *)sqlite3_column_text
                                                        (prep_stmt, 0);
                        if (!text_column) {
                                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                                        LG_MSG_GET_ID_FAILED, "Failed "
                                        "retriving GF_ID");
                                goto out;
                        }
                        ret = gf_uuid_parse (text_column, gfdb_query_record->gfid);
                        if (ret) {
                                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                                        LG_MSG_PARSE_FAILED, "Failed parsing "
                                        "GF_ID");
                                goto out;
                        }

                        /*Retrive Link Buffer - column index 1*/
                        text_column = (char *)sqlite3_column_text
                                                (prep_stmt, 1);
                        /* Get link string. Do shallow copy here
                         * query_callback function should do a
                         * deep copy and then do operations on this field*/
                        gfdb_query_record->_link_info_str = text_column;
                        gfdb_query_record->link_info_size = strlen
                                                                (text_column);

                        /* Call the call back function provided*/
                        ret = query_callback (gfdb_query_record,
                                                        _query_cbk_args);
                        if (ret) {
                                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                                        LG_MSG_QUERY_CALL_BACK_FAILED,
                                        "Query Call back failed!");
                                goto out;
                        }

                }

        }

        if (ret != SQLITE_DONE) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_GET_RECORD_FAILED, "Failed retriving records "
                        "from db : %s", sqlite3_errmsg (db_conn));
                ret = -1;
                goto out;
        }

        ret = 0;
out:
        gfdb_query_record_fini (&gfdb_query_record);
        return ret;
}
Beispiel #28
0
SqlException::SqlException(sqlite3_stmt* statement, const std::string& message)
    : SqlException(sqlite3_db_handle(statement), sqlite3_sql(statement), message) {
}
void
publish_services (void)
{
  struct gen_ssid_arg arg = {
    .ssid = "##",
    .ssid_len = 2,
    .last_pos = -1,
    .rc = ERR_SUCCESS,
  };
  char *err_msg;
  int rc;
  sqlite3 *db;

  if (sqlite3_open_v2 (SERVICE_LIST_DB, &db, SQLITE_OPEN_READONLY, NULL))
    {
      SQLITE3_ERR (db,
		   "Cannot open DB in read-only mode for publishing services");
      goto error;
    }

  if ((rc = sqlite3_exec (db,
			  "select "
			  COLUMN_CAT_ID ", " COLUMN_DESC ", " COLUMN_POSITION
			  " from " TABLE_SERVICE_LIST
			  " order by " COLUMN_POSITION " asc",
			  gen_ssid, &arg, &err_msg)) != SQLITE_ABORT
      && rc != SQLITE_OK)
    {
      SQLITE3_ERR_STR (err_msg, "Cannot select services to publish");
      goto error;
    }
  if (rc == SQLITE_ABORT)
    {
      sqlite3_free (err_msg);
      l->APP_ERR (arg.rc, "Cannot publish services");
      goto error;
    }

  if ((rc = set_ssid (arg.ssid, arg.ssid_len)))
    {
      l->APP_ERR (rc, "Cannot set SSID");
    }

 error:
  if (sqlite3_close (db))
    {
      SQLITE3_ERR (db,
		   "Cannot close read-only DB for reading published services");
    }
}

/**
 * The callback function used with sqlite3_exec() to not change the modification
 * time of unmodified record. The SQL select in sqlite3_exec()
 * <strong>MUST</strong> select all columns with '*'.
 *
 * @param [in] stmt the prepared statement to adjust the modification time.
 * @param [in] col_count the number of columns in this record.
 * @param [in] cols the columns of this record.
 * @param [in] col_names the column names of this record.
 *
 * @return 0 if there is no error or non-zero if there is one.
 */
static int
adjust_mod_time (void *stmt, int col_count, char **cols, char **col_names)
{
  sqlite3_stmt *updt_stmt = stmt;
  sqlite3 *db = sqlite3_db_handle (updt_stmt);

  if (sqlite3_bind_text (stmt, 1, cols[COLPOS_MOD_TIME], -1, SQLITE_STATIC))
    {
      SQLITE3_ERR (db, "Cannot bind mod_time to updt stmt");
      return -1;
    }
  if (sqlite3_bind_text (stmt, 2, cols[COLPOS_POSITION], -1, SQLITE_STATIC))
    {
      SQLITE3_ERR (db, "Cannot bind position to updt stmt");
      return -1;
    }
  if (sqlite3_bind_text (stmt, 3, cols[COLPOS_CAT_ID], -1, SQLITE_STATIC))
    {
      SQLITE3_ERR (db, "Cannot bind cat_id to updt stmt");
      return -1;
    }
  if (sqlite3_bind_text (stmt, 4, cols[COLPOS_DESC], -1, SQLITE_STATIC))
    {
      SQLITE3_ERR (db, "Cannot bind desc to updt stmt");
      return -1;
    }
  if (sqlite3_bind_text (stmt, 5, cols[COLPOS_LONG_DESC], -1, SQLITE_STATIC))
    {
      SQLITE3_ERR (db, "Cannot bind long_desc to updt stmt");
      return -1;
    }
  if (sqlite3_bind_text (stmt, 6, cols[COLPOS_URI], -1, SQLITE_STATIC))
    {
      SQLITE3_ERR (db, "Cannot bind uri to updt stmt");
      return -1;
    }

  if (sqlite3_step (stmt) != SQLITE_DONE)
    {
      SQLITE3_ERR (db, "Cannot execute updt stmt");
      return -1;
    }

  if (sqlite3_reset (stmt))
    {
      SQLITE3_ERR (db, "Cannot reset updt stmt");
      return -1;
    }
  if (sqlite3_clear_bindings (stmt))
    {
      SQLITE3_ERR (db, "Cannot clear updt stmt bindings");
      return -1;
    }

  return 0;
}
Beispiel #30
0
 Execerror::Execerror(const char* function, sqlite3_stmt* stmt, int _errcode)
   : SqliteError(function, sqlite3_errmsg(sqlite3_db_handle(stmt))),
     errcode(_errcode)
 { }