Beispiel #1
0
bool PDOSqliteStatement::paramHook(PDOBoundParam *param,
                                   PDOParamEvent event_type) {
  switch (event_type) {
  case PDO_PARAM_EVT_EXEC_PRE:
    if (executed && !m_done) {
      sqlite3_reset(m_stmt);
      m_done = 1;
    }

    if (param->is_param) {
      if (param->paramno == -1) {
        param->paramno = sqlite3_bind_parameter_index(m_stmt,
                                                      param->name.c_str()) - 1;
      }

      switch (PDO_PARAM_TYPE(param->param_type)) {
      case PDO_PARAM_STMT:
        return false;

      case PDO_PARAM_NULL:
        if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
          return true;
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_INT:
      case PDO_PARAM_BOOL:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          if (SQLITE_OK == sqlite3_bind_int(m_stmt, param->paramno + 1,
                                            param->parameter.toInt64())) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_LOB:
        if (param->parameter.isResource()) {
          Variant buf = f_stream_get_contents(param->parameter);
          if (!same(buf, false)) {
            param->parameter = buf;
          } else {
            pdo_raise_impl_error(dbh, this, "HY105",
                                 "Expected a stream resource");
            return false;
          }
        } else if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
          handleError(__FILE__, __LINE__);
          return false;
        }

        {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_blob(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_STR:
      default:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_text(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;
      }
    }
    break;

  default:;
  }
  return true;
}
int SqliteStatement::bind (int position)
{
    return sqlite3_bind_null (statement, position);
}
Beispiel #3
0
static tb_bool_t tb_database_sqlite3_statement_bind(tb_database_sql_impl_t* database, tb_database_sql_statement_ref_t statement, tb_database_sql_value_t const* list, tb_size_t size)
{
    // check
    tb_database_sqlite3_t* sqlite = tb_database_sqlite3_cast(database);
    tb_assert_and_check_return_val(sqlite && sqlite->database && statement && list && size, tb_false);

    // the param count
    tb_size_t param_count = (tb_size_t)sqlite3_bind_parameter_count((sqlite3_stmt*)statement);
    tb_assert_and_check_return_val(size == param_count, tb_false);
   
    // walk
    tb_size_t i = 0;
    for (i = 0; i < size; i++)
    {
        // the value
        tb_database_sql_value_t const* value = &list[i];

        // done
        tb_int_t    ok = SQLITE_ERROR;
        tb_byte_t*  data = tb_null;
        switch (value->type)
        {
        case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
            tb_trace_i("sqlite3: test %lu %s", i, value->u.text.data);
            ok = sqlite3_bind_text((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.text.data, (tb_int_t)tb_database_sql_value_size(value), tb_null);
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
            ok = sqlite3_bind_int64((sqlite3_stmt*)statement, (tb_int_t)(i + 1), tb_database_sql_value_int64(value));
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
            ok = sqlite3_bind_int((sqlite3_stmt*)statement, (tb_int_t)(i + 1), (tb_int_t)tb_database_sql_value_int32(value));
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB16:
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB8:
            ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.blob.data, (tb_int_t)value->u.blob.size, tb_null);
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB32:
            {
                if (value->u.blob.stream)
                {
                    // done
                    do
                    {
                        // the stream size
                        tb_hong_t size = tb_stream_size(value->u.blob.stream);
                        tb_assert_and_check_break(size >= 0);

                        // make data
                        data = tb_malloc0_bytes((tb_size_t)size);
                        tb_assert_and_check_break(data);

                        // read data
                        if (!tb_stream_bread(value->u.blob.stream, data, (tb_size_t)size)) break;

                        // bind it
                        ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), data, (tb_int_t)size, tb_database_sqlite3_statement_bind_exit);

                    } while (0);
                }
                else ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.blob.data, (tb_int_t)value->u.blob.size, tb_null);
            }
            break;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
        case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
            ok = sqlite3_bind_double((sqlite3_stmt*)statement, (tb_int_t)(i + 1), (tb_double_t)tb_database_sql_value_double(value));
            break;
#endif
        case TB_DATABASE_SQL_VALUE_TYPE_NULL:
            ok = sqlite3_bind_null((sqlite3_stmt*)statement, (tb_int_t)(i + 1));
            break;
        default:
            tb_trace_e("statement: bind: unknown value type: %lu", value->type);
            break;
        }

        // failed?
        if (SQLITE_OK != ok)
        {
            // exit data
            if (data) tb_free(data);
            data = tb_null;

            // save state
            sqlite->base.state = tb_database_sqlite3_state_from_errno(sqlite3_errcode(sqlite->database));

            // trace
            tb_trace_e("statement: bind value[%lu] failed, error[%d]: %s", i, sqlite3_errcode(sqlite->database), sqlite3_errmsg(sqlite->database));
            break;
        }
    }

    // ok?
    return (i == size)? tb_true : tb_false;
}
Beispiel #4
0
static int pdo_sqlite_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
		enum pdo_param_event event_type)
{
	pdo_sqlite_stmt *S = (pdo_sqlite_stmt*)stmt->driver_data;
	zval *parameter;

	switch (event_type) {
		case PDO_PARAM_EVT_EXEC_PRE:
			if (stmt->executed && !S->done) {
				sqlite3_reset(S->stmt);
				S->done = 1;
			}

			if (param->is_param) {

				if (param->paramno == -1) {
					param->paramno = sqlite3_bind_parameter_index(S->stmt, ZSTR_VAL(param->name)) - 1;
				}

				switch (PDO_PARAM_TYPE(param->param_type)) {
					case PDO_PARAM_STMT:
						return 0;

					case PDO_PARAM_NULL:
						if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
							return 1;
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;

					case PDO_PARAM_INT:
					case PDO_PARAM_BOOL:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
						} else {
							convert_to_long(parameter);
#if ZEND_LONG_MAX > 2147483647
							if (SQLITE_OK == sqlite3_bind_int64(S->stmt, param->paramno + 1, Z_LVAL_P(parameter))) {
								return 1;
							}
#else
							if (SQLITE_OK == sqlite3_bind_int(S->stmt, param->paramno + 1, Z_LVAL_P(parameter))) {
								return 1;
							}
#endif
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;

					case PDO_PARAM_LOB:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_RESOURCE) {
							php_stream *stm = NULL;
							php_stream_from_zval_no_verify(stm, parameter);
							if (stm) {
								zend_string *mem = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0);
								zval_ptr_dtor(parameter);
								ZVAL_STR(parameter, mem ? mem : ZSTR_EMPTY_ALLOC());
							} else {
								pdo_raise_impl_error(stmt->dbh, stmt, "HY105", "Expected a stream resource");
								return 0;
							}
						} else if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
							pdo_sqlite_error_stmt(stmt);
							return 0;
						} else {
							convert_to_string(parameter);
						}

						if (SQLITE_OK == sqlite3_bind_blob(S->stmt, param->paramno + 1,
								Z_STRVAL_P(parameter),
								Z_STRLEN_P(parameter),
								SQLITE_STATIC)) {
							return 1;
						}
						return 0;

					case PDO_PARAM_STR:
					default:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
						} else {
							convert_to_string(parameter);
							if (SQLITE_OK == sqlite3_bind_text(S->stmt, param->paramno + 1,
									Z_STRVAL_P(parameter),
									Z_STRLEN_P(parameter),
									SQLITE_STATIC)) {
								return 1;
							}
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;
				}
			}
			break;

		default:
			;
	}
	return 1;
}
Beispiel #5
0
// Bind a NULL value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName)
{
    const int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    const int ret = sqlite3_bind_null(mStmtPtr, index);
    check(ret);
}
Beispiel #6
0
bool LabrestAPI::LabrestDB::unlockResource(int resourceId, ::std::string username)
{
//    ::std::cout << "LabrestDB::unlockResource()  called" << ::std::endl;
        
    bool status;
    
    sqlite3_stmt *ppStmt;

    sqlite3_exec(db, "BEGIN", 0, 0, 0);
    
    if (ExistsResource(resourceId))
    {  
        if (ResourceIsLockByUser(resourceId, username))
        {
            sqlite3_prepare(db,"update using_resource set end_time = datetime(), "
                    "unlock_comment = ?"
                    " where id = (select lock_status from resource "
                    " where id = ?);",-1,&ppStmt,0);
        
            ::std::string tuser = ((dbPtr->getUser(username).group == 1)&&(dbPtr->getResource(resourceId).resLockStatus.username!= username)) ?  username + " as admin" :    username;        
            ::std::string unlock_comment = (username == "system") ? "Timeout expired" : tuser;
            
            
    ::std::cout << unlock_comment << ::std::endl;
            
            sqlite3_bind_text(ppStmt, 1, unlock_comment.c_str(),unlock_comment.length(),NULL);
            
            sqlite3_bind_int(ppStmt, 2, resourceId);
    
            if (sqlite3_step(ppStmt) == SQLITE_DONE)
            {
                status = true;
            }
            else
            {
                status = false;
            }
            sqlite3_finalize(ppStmt);
      
            sqlite3_prepare(db,"update resource set lock_status = ? "
            " where id = ?;",-1,&ppStmt,0);
    
            sqlite3_bind_null(ppStmt,  1);

            sqlite3_bind_int(ppStmt, 2, resourceId);

            if (sqlite3_step(ppStmt) == SQLITE_DONE)
            {
                status = true;
            }
            else
            {
                status = false;
            }
            sqlite3_finalize(ppStmt);
    
            if (status)
            {
               sqlite3_prepare(db,"select id from resource where parent = ?;" ,-1,&ppStmt,0);
                                
                sqlite3_bind_int(ppStmt, 1, resourceId);
                
                while (sqlite3_step(ppStmt) == SQLITE_ROW)
                {
                    unlockResource(sqlite3_column_int(ppStmt,0), username);
                }
                sqlite3_finalize(ppStmt);  
            };
        }
        else
        {
            sqlite3_exec(db, "COMMIT", 0, 0, 0);

            ::LabrestAPI::AccessDenied iv;

            iv.ice_throw();
        }
        Event ev;
    
        ev.TypeEvent = CB_UNLOCK;
        ev.id = EvQueuePtr->next_id;
        ev.resourceId = resourceId;
        ev.userDest = "";
        ev.userSrc = username;
    
        EvQueuePtr->push_back(ev);
        
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
    }                   
    else
    {
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
        
        ::LabrestAPI::InvalidValue iv;
        
        iv.ice_throw();
    }
    return status;
}
Beispiel #7
0
void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString &tableName,
    const QStringList &tagKeys,
    const QStringList &notNullTagKeys )
{
  Q_UNUSED( tagKeys );

  QString sqlInsertLine = QStringLiteral( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) );
  for ( int i = 0; i < tagKeys.count(); ++i )
    sqlInsertLine += QStringLiteral( ",?" );
  sqlInsertLine += QLatin1String( ", GeomFromWKB(?, 4326))" );
  sqlite3_stmt *stmtInsert = nullptr;
  if ( sqlite3_prepare_v2( mDatabase, sqlInsertLine.toUtf8().constData(), -1, &stmtInsert, nullptr ) != SQLITE_OK )
  {
    mError = QStringLiteral( "Prepare SELECT FROM ways failed." );
    return;
  }

  QgsOSMWayIterator ways = listWays();
  QgsOSMWay w;
  while ( ( w = ways.next() ).isValid() )
  {
    QgsOSMTags t = tags( true, w.id() );

    QgsPolyline polyline = wayPoints( w.id() );

    if ( polyline.count() < 2 )
      continue; // invalid way

    bool isArea = ( polyline.first() == polyline.last() ); // closed way?
    // filter out closed way that are not areas through tags
    if ( isArea && ( t.contains( QStringLiteral( "highway" ) ) || t.contains( QStringLiteral( "barrier" ) ) ) )
    {
      // make sure tags that indicate areas are taken into consideration when deciding on a closed way is or isn't an area
      // and allow for a closed way to be exported both as a polygon and a line in case both area and non-area tags are present
      if ( ( t.value( QStringLiteral( "area" ) ) != QLatin1String( "yes" ) && !t.contains( QStringLiteral( "amenity" ) ) && !t.contains( QStringLiteral( "landuse" ) ) && !t.contains( QStringLiteral( "building" ) ) && !t.contains( QStringLiteral( "natural" ) ) && !t.contains( QStringLiteral( "leisure" ) ) && !t.contains( QStringLiteral( "aeroway" ) ) ) || !closed )
        isArea = false;
    }

    if ( closed != isArea )
      continue; // skip if it's not what we're looking for

    //check not null tags
    bool skipNull = false;
    for ( int i = 0; i < notNullTagKeys.count() && !skipNull; ++i )
      if ( !t.contains( notNullTagKeys[i] ) )
        skipNull = true;

    if ( skipNull )
      continue;

    QgsGeometry geom = closed ? QgsGeometry::fromPolygon( QgsPolygon() << polyline ) : QgsGeometry::fromPolyline( polyline );
    int col = 0;
    sqlite3_bind_int64( stmtInsert, ++col, w.id() );

    // tags
    for ( int i = 0; i < tagKeys.count(); ++i )
    {
      if ( t.contains( tagKeys[i] ) )
        sqlite3_bind_text( stmtInsert, ++col, t.value( tagKeys[i] ).toUtf8().constData(), -1, SQLITE_TRANSIENT );
      else
        sqlite3_bind_null( stmtInsert, ++col );
    }

    if ( !geom.isNull() )
    {
      QByteArray wkb( geom.exportToWkb() );
      sqlite3_bind_blob( stmtInsert, ++col, wkb.constData(), wkb.length(), SQLITE_STATIC );
    }
    else
      sqlite3_bind_null( stmtInsert, ++col );

    int insertRes = sqlite3_step( stmtInsert );
    if ( insertRes != SQLITE_DONE )
    {
      mError = QStringLiteral( "Error inserting way %1 [%2]" ).arg( w.id() ).arg( insertRes );
      break;
    }

    sqlite3_reset( stmtInsert );
    sqlite3_clear_bindings( stmtInsert );
  }

  sqlite3_finalize( stmtInsert );
}
Beispiel #8
0
Datei: db.c Projekt: Tilka/ncdc
// Executes a single query.
// If transaction = TRUE, the query is assumed to be executed in a transaction
//   (which has already been initiated)
// The return path (if any) and lastid (0 if not requested) are stored in *res
// and *lastid. The caller of this function is responsible for sending back the
// final response. If this function returns anything other than SQLITE_DONE,
// the query has failed.
// It is assumed that the first `flags' part of the queue item has already been
// fetched.
static int db_queue_process_one(sqlite3 *db, char *q, gboolean nocache, gboolean transaction, GAsyncQueue **res, gint64 *lastid) {
  char *query = darray_get_ptr(q);
  *res = NULL;
  *lastid = 0;

  // Would be nice to have the parameters logged
  g_debug("db: Executing \"%s\"", query);

  // Get statement handler
  int r = SQLITE_ROW;
  sqlite3_stmt *s;
  if(nocache ? sqlite3_prepare_v2(db, query, -1, &s, NULL) : db_queue_process_prepare(db, query, &s)) {
    g_critical("SQLite3 error preparing `%s': %s", query, sqlite3_errmsg(db));
    r = SQLITE_ERROR;
  }

  // Bind parameters
  int t, n;
  int i = 1;
  char *a;
  while((t = darray_get_int32(q)) != DBQ_END && t != DBQ_RES) {
    if(r == SQLITE_ERROR)
      continue;
    switch(t) {
    case DBQ_NULL:
      sqlite3_bind_null(s, i);
      break;
    case DBQ_INT:
      sqlite3_bind_int(s, i, darray_get_int32(q));
      break;
    case DBQ_INT64:
      sqlite3_bind_int64(s, i, darray_get_int64(q));
      break;
    case DBQ_TEXT:
      sqlite3_bind_text(s, i, darray_get_string(q), -1, SQLITE_STATIC);
      break;
    case DBQ_BLOB:
      a = darray_get_dat(q, &n);
      sqlite3_bind_blob(s, i, a, n, SQLITE_STATIC);
      break;
    }
    i++;
  }

  // Fetch information about what results we need to send back
  gboolean wantlastid = FALSE;
  char columns[20]; // 20 should be enough for everyone
  n = 0;
  if(t == DBQ_RES) {
    *res = darray_get_ptr(q);
    while((t = darray_get_int32(q)) != DBQ_END) {
      if(t == DBQ_LASTID)
        wantlastid = TRUE;
      else
        columns[n++] = t;
    }
  }

  // Execute query
  while(r == SQLITE_ROW) {
    // do the step()
    if(transaction)
      r = sqlite3_step(s);
    else
      while((r = sqlite3_step(s)) == SQLITE_BUSY)
        ;
    if(r != SQLITE_DONE && r != SQLITE_ROW)
      g_critical("SQLite3 error on step() of `%s': %s", query, sqlite3_errmsg(db));
    // continue with the next step() if we're not going to do anything with the results
    if(r != SQLITE_ROW || !*res || !n)
      continue;
    // send back a response
    GByteArray *rc = g_byte_array_new();
    darray_init(rc);
    darray_add_int32(rc, r);
    for(i=0; i<n; i++) {
      switch(columns[i]) {
      case DBQ_INT:   darray_add_int32( rc, sqlite3_column_int(  s, i)); break;
      case DBQ_INT64: darray_add_int64( rc, sqlite3_column_int64(s, i)); break;
      case DBQ_TEXT:  darray_add_string(rc, (char *)sqlite3_column_text( s, i)); break;
      case DBQ_BLOB:  darray_add_dat(   rc, sqlite3_column_blob( s, i), sqlite3_column_bytes(s, i)); break;
      default: g_warn_if_reached();
      }
    }
    g_async_queue_push(*res, g_byte_array_free(rc, FALSE));
  }

  // Fetch last id, if requested
  if(r == SQLITE_DONE && wantlastid)
    *lastid = sqlite3_last_insert_rowid(db);
  sqlite3_reset(s);
  if(nocache)
    sqlite3_finalize(s);

  return r;
}
Beispiel #9
0
Statement &Statement::bindNull(int pos)
{
    CHECK_RESULT_CONN(sqlite3_bind_null(impl->stmt, pos + 1), impl->conn);
    return *this;
}
static void
check_end2_fid (struct gml_params *params, const char *el)
{
/* checking if the FID tag ends here */
    int ret;
    int fld = 1;
    struct gml_column *col;
    if (strcasecmp (params->fid_tag, el) == 0)
      {
	  params->is_fid = 0;
	  if (params->stmt == NULL)
	      return;

	  /* resetting the SQL prepared statement */
	  sqlite3_reset (params->stmt);
	  sqlite3_clear_bindings (params->stmt);
	  col = params->first;
	  while (col)
	    {
		/* binding ordinary column values */
		switch (col->value_type)
		  {
		  case VALUE_INT:
		      sqlite3_bind_int64 (params->stmt, fld, col->int_value);
		      break;
		  case VALUE_FLOAT:
		      sqlite3_bind_double (params->stmt, fld, col->dbl_value);
		      break;
		  case VALUE_TEXT:
		      sqlite3_bind_text (params->stmt, fld, col->txt_value,
					 strlen (col->txt_value),
					 SQLITE_STATIC);
		      break;
		  default:
		      sqlite3_bind_null (params->stmt, fld);
		      break;
		  };
		fld++;
		col = col->next;
	    }
	  /* setting up the latest Polygon (if any) */
	  polygon_set_up (params);
	  /* binding Geometry BLOB value */
	  if (params->geometry == NULL)
	      sqlite3_bind_null (params->stmt, fld);
	  else
	    {
		unsigned char *blob;
		int blob_size;
		params->geometry->Srid = params->srid;
		params->geometry->DeclaredType = params->declared_type;
		gaiaToSpatiaLiteBlobWkb (params->geometry, &blob, &blob_size);
		sqlite3_bind_blob (params->stmt, fld, blob, blob_size, free);
	    }
	  /* performing INSERT INTO */
	  ret = sqlite3_step (params->stmt);
	  clean_values (params);
	  if (ret == SQLITE_DONE || ret == SQLITE_ROW)
	      return;
	  fprintf (stderr, "sqlite3_step() error: INSERT INTO\n");
	  sqlite3_finalize (params->stmt);
	  params->stmt = NULL;
      }
}
Beispiel #11
0
int StoreENTable(sqlite3 *db, unsigned long int sid, FILE *fp, int swp)
{
    int retval = 0;
    int rc;
    sqlite3_stmt *stmt;
    
    char *sql;

    sql = "INSERT INTO levels" \
          " (sid, id, nele, name, e, g, vn, vl, p, ibase, ncomplex, sname)" \
          " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);

    sqlite3_bind_int(stmt,  1, sid);

    sqlite3_exec(db, "BEGIN", 0, 0, 0);
    
    while (retval == 0) {
        EN_HEADER h;
        int i, n;
        
        n = ReadENHeader(fp, &h, swp);
        if (n == 0) {
            break;
        }
        
        sqlite3_bind_int(stmt,  3, h.nele);

        for (i = 0; i < h.nlevels; i++) {
            EN_RECORD r;
            int p, vnl, vn, vl, g, ibase;
            
            n = ReadENRecord(fp, &r, swp);
            if (n == 0) {
                break;
            }

            if (r.p < 0) {
	      p = 1;
	      vnl = -r.p;
            } else {
	      p = 0;
	      vnl = r.p;
            }
            
            g = JFromENRecord(&r) + 1;
            vn = vnl/100;
            vl = vnl - 100*vn;
            
            ibase = IBaseFromENRecord(&r);
    
            sqlite3_bind_int   (stmt,  2, r.ilev);
            SQLITE3_BIND_STR   (stmt,  4, r.name);
            sqlite3_bind_double(stmt,  5, r.energy);
            sqlite3_bind_int   (stmt,  6, g);
            sqlite3_bind_int   (stmt,  7, vn);
            sqlite3_bind_int   (stmt,  8, vl);
            sqlite3_bind_int   (stmt,  9, p);
            if (ibase >= 0) {
                sqlite3_bind_int (stmt, 10, ibase);
            } else {
                sqlite3_bind_null(stmt, 10);
            }
            SQLITE3_BIND_STR   (stmt, 11, r.ncomplex);
            SQLITE3_BIND_STR   (stmt, 12, r.sname);

            rc = sqlite3_step(stmt);
            if (rc != SQLITE_DONE) {
                fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
                retval = -1;
                break;
            }
            sqlite3_reset(stmt);
        }
    }

    sqlite3_exec(db, "COMMIT", 0, 0, 0);
    
    sqlite3_finalize(stmt);

    return retval;
}
void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString& tableName, const QStringList& tagKeys )
{
  Q_UNUSED( tagKeys );

  QString sqlInsertLine = QString( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) );
  for ( int i = 0; i < tagKeys.count(); ++i )
    sqlInsertLine += QString( ",?" );
  sqlInsertLine += ", GeomFromWKB(?, 4326))";
  sqlite3_stmt* stmtInsert;
  if ( sqlite3_prepare_v2( mDatabase, sqlInsertLine.toUtf8().constData(), -1, &stmtInsert, 0 ) != SQLITE_OK )
  {
    mError = "Prepare SELECT FROM ways failed.";
    return;
  }

  QgsOSMWayIterator ways = listWays();
  QgsOSMWay w;
  while (( w = ways.next() ).isValid() )
  {
    QgsOSMTags t = tags( true, w.id() );

    QgsPolyline polyline = wayPoints( w.id() );

    if ( polyline.count() < 2 )
      continue; // invalid way

    bool isArea = ( polyline.first() == polyline.last() ); // closed way?
    // some closed ways are not really areas
    if ( isArea && ( t.contains( "highway" ) || t.contains( "barrier" ) ) )
    {
      if ( t.value( "area" ) != "yes" ) // even though "highway" is line by default, "area"="yes" may override that
        isArea = false;
    }

    if ( closed != isArea )
      continue; // skip if it's not what we're looking for

    QgsGeometry* geom = closed ? QgsGeometry::fromPolygon( QgsPolygon() << polyline ) : QgsGeometry::fromPolyline( polyline );
    int col = 0;
    sqlite3_bind_int64( stmtInsert, ++col, w.id() );

    // tags
    for ( int i = 0; i < tagKeys.count(); ++i )
    {
      if ( t.contains( tagKeys[i] ) )
        sqlite3_bind_text( stmtInsert, ++col, t.value( tagKeys[i] ).toUtf8().constData(), -1, SQLITE_TRANSIENT );
      else
        sqlite3_bind_null( stmtInsert, ++col );
    }

    sqlite3_bind_blob( stmtInsert, ++col, geom->asWkb(), geom->wkbSize(), SQLITE_STATIC );

    int insertRes = sqlite3_step( stmtInsert );
    if ( insertRes != SQLITE_DONE )
    {
      mError = QString( "Error inserting way %1 [%2]" ).arg( w.id() ).arg( insertRes );
      break;
    }

    sqlite3_reset( stmtInsert );
    sqlite3_clear_bindings( stmtInsert );
    delete geom;
  }

  sqlite3_finalize( stmtInsert );
}
Beispiel #13
0
	typename std::enable_if<std::is_same<nullptr_t, T>::value, int>::type
		BindValue(sqlite3_stmt *statement, int current, const T& t)
	{
			return sqlite3_bind_null(statement, current);
		}
Beispiel #14
0
		bool exec(const std::string& sql, 
			const bindings_type& bindings, 
			rows_type* rows)
		{
			boost::mutex::scoped_lock lock(guard_);
			auto it = stmt_ptr_map_.find(sql);
			sqlite3_stmt* stmt;
			if(it == stmt_ptr_map_.end()) {
				sqlite3_stmt* new_stmt;
				int ret = sqlite3_prepare_v2(db_ptr_.get(), sql.c_str(), sql.size(), &new_stmt, NULL);
				if(new_stmt == NULL ) {
					std::cerr << "Failed to execute statement: " << sql << std::endl;
					return false;
				}
				if(ret != SQLITE_OK) {
					std::cerr << "Failed to execute statement: " << sql << ", " << ret << std::endl;
					sqlite3_finalize(new_stmt);
					return false;
				}
				stmt_ptr_map_[sql] = boost::shared_ptr<sqlite3_stmt>(new_stmt, statement_finalise());
				stmt = new_stmt;
			} else {
				stmt = it->second.get();
				// Reset the prepared statement, which is more efficient than re-creating
				// as preparing a statement is expensive.
				sqlite3_reset(stmt);
				sqlite3_clear_bindings(stmt);
			}
#ifdef BOOST_NO_CXX11_RANGE_BASED_FOR
			BOOST_FOREACH(auto bit, bindings) {
#else
			for(auto bit : bindings) {
#endif
				int ndx = 0;
				if(bit.first.type() == json_spirit::int_type) {
					ndx = bit.first.get_int();
				} else if(bit.first.type() == json_spirit::str_type) {
					ndx = sqlite3_bind_parameter_index(stmt, bit.first.get_str().c_str());
				} else {
					ASSERT_LOG(false, "parameter for binding index must be int or string: " << bit.first.type());
				}
				ASSERT_LOG(ndx != 0, "Bad index value: 0");
				switch(bit.second.type()) {
					case json_spirit::obj_type: {
						json_spirit::mObject& obj = bit.second.get_obj();
						std::string s = json_spirit::write(obj);
						sqlite3_bind_blob(stmt, ndx, static_cast<const void*>(s.c_str()), s.size(), SQLITE_TRANSIENT);
						break;
					}
					case json_spirit::array_type: {
						json_spirit::mArray& ary = bit.second.get_array();
						std::string s = json_spirit::write(ary);
						sqlite3_bind_blob(stmt, ndx, static_cast<const void*>(s.c_str()), s.size(), SQLITE_TRANSIENT);
						break;
					}
					case json_spirit::str_type: {
						std::string s = bit.second.get_str();
						sqlite3_bind_text(stmt, ndx, s.c_str(), s.size(), SQLITE_TRANSIENT);
						break;
					}
					case json_spirit::bool_type: {
						sqlite3_bind_int(stmt, ndx, bit.second.get_bool());
						break;
					}
					case json_spirit::int_type: {
						sqlite3_bind_int(stmt, ndx, bit.second.get_int());
						break;
					}
					case json_spirit::real_type: {
						sqlite3_bind_double(stmt, ndx, bit.second.get_real());
						break;
					}
					case json_spirit::null_type: {
						sqlite3_bind_null(stmt, ndx);
						break;
					}
				}
			}
			
			std::vector<json_spirit::mValue> ret_rows;
			// Step through the statement
			bool stepping = true;
			while(stepping) {
				int ret = sqlite3_step(stmt);
				if(ret == SQLITE_ROW) {
					int col_count = sqlite3_column_count(stmt);
					for(int n = 0; n != col_count; ++n) {
						int type = sqlite3_column_type(stmt, n);
						switch(type) {
							case SQLITE_INTEGER: {
								int val = sqlite3_column_int(stmt, n);
								ret_rows.push_back(json_spirit::mValue(val));
								break;
							}
							case SQLITE_FLOAT: {
								double val = sqlite3_column_double(stmt, n);
								ret_rows.push_back(json_spirit::mValue(val));
								break;
							}
							case SQLITE_BLOB: {
								const char* blob = reinterpret_cast<const char *>(sqlite3_column_blob(stmt, n));
								int len = sqlite3_column_bytes(stmt, n);
								json_spirit::mValue value;
								json_spirit::read(std::string(blob, blob + len), value);
								ret_rows.push_back(value);
								break;
							}
							case SQLITE_NULL: {
								ret_rows.push_back(json_spirit::mValue());
								break;
							}
							case SQLITE_TEXT: {
								const uint8_t* us = sqlite3_column_text(stmt, n);
								int len = sqlite3_column_bytes(stmt, n);
								std::string s(us, us + len);
								ret_rows.push_back(json_spirit::mValue(s));
								break;
							}
						}						
					}
				} else if(ret == SQLITE_DONE) {
					stepping = false;
				} else {
					std::cerr << "Error stepping through statement: " << sql << ", " << ret << " : " << sqlite3_errmsg(db_ptr_.get()) << std::endl;
					return false;
				}
			}

			ASSERT_LOG(rows != NULL || ret_rows.empty() != false, "There was data to return but no place to put it.");
			rows->swap(ret_rows);
			return true;
		}
	private:
Beispiel #15
0
bool LabrestAPI::LabrestDB::deleteResourceType(int id)
{
//    ::std::cout << "LabrestDB::deleteResourceType()  called" << ::std::endl;
    
    bool status;
    
    sqlite3_exec(db, "BEGIN", 0, 0, 0);
    
    sqlite3_stmt *ppStmt;
    
    sqlite3_prepare(db,"update resource set type_id = ? where type_id = ?;",-1,&ppStmt,0);

    sqlite3_bind_null(ppStmt,1);
    
    sqlite3_bind_int(ppStmt, 2, id);
    
//    sqlite3_prepare(db,"delete from resource where type_id = ?;",-1,&ppStmt,0);
//    
//    sqlite3_bind_int(ppStmt, 1, id);

    if (sqlite3_step(ppStmt) == SQLITE_DONE)
    {
	status = true;
    }
    else
    {
	status = false;
    }
    sqlite3_finalize(ppStmt);
    
    sqlite3_prepare(db,"update resource_type set parent = ? where parent = ?;",-1,&ppStmt,0);

    sqlite3_bind_null(ppStmt,1);
    
    sqlite3_bind_int(ppStmt, 2, id);

    if (sqlite3_step(ppStmt) == SQLITE_DONE)
    {
	status = true;
    }
    else
    {
	status = false;
    }
    sqlite3_finalize(ppStmt);

    if (status)
    {
        sqlite3_prepare(db,"delete from resource_type "
            "where id = ?;",-1,&ppStmt,0);
        
        sqlite3_bind_int(ppStmt, 1, id);

        if (sqlite3_step(ppStmt) == SQLITE_DONE)
        {
            status = true;
        }
        else
        {
            status = false;
        }
        sqlite3_finalize(ppStmt);
    }
    sqlite3_exec(db, "COMMIT", 0, 0, 0);
    
    return status;

}
Beispiel #16
0
 void Statement::BindNull(int col)
 {
   CheckOk(sqlite3_bind_null(GetStatement(), col + 1));
 }
Beispiel #17
0
bool LabrestAPI::LabrestDB::lockResource(int resourceId, ::std::string username, int duration)
{
//    ::std::cout << "LabrestDB::lockResource()  called" << ::std::endl;
    
    bool status;
    
    int lock_st_id; 

    sqlite3_stmt *ppStmt;
    
    sqlite3_exec(db, "BEGIN", 0, 0, 0);
    
    if (ExistsResource(resourceId))
    {    
    if (ResourceIsNotLock(resourceId))
    {
        sqlite3_prepare(db,"insert into using_resource(username,resource_id, "
                "start_time, duration, end_time) "
               "values(?,?,datetime(), ?, ?);" ,-1,&ppStmt,0);
       
        sqlite3_bind_text(ppStmt,1,username.c_str(),username.length(),NULL);

        sqlite3_bind_int(ppStmt, 2, resourceId);
        
        if (duration == -1) sqlite3_bind_null(ppStmt,3);
            else sqlite3_bind_int(ppStmt, 3, duration);
        
        sqlite3_bind_null(ppStmt,4);
        
        if (sqlite3_step(ppStmt) == SQLITE_DONE)
        {
            status = true;
        }
        else
        {
            status = false;
        }
        sqlite3_finalize(ppStmt);
    
        if (status)
         
            {
                sqlite3_prepare(db,"update resource set lock_status = "
                        "(select id from using_resource where "
                     "resource_id = ? and end_time isnull)"
                        " where id = ?;" ,-1,&ppStmt,0);
                
                sqlite3_bind_int(ppStmt, 1, resourceId);
                
                sqlite3_bind_int(ppStmt, 2, resourceId);
                
                if (sqlite3_step(ppStmt) == SQLITE_DONE)
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                sqlite3_finalize(ppStmt);
                
                sqlite3_prepare(db,"select id from resource where parent = ?;" ,-1,&ppStmt,0);
                                
                sqlite3_bind_int(ppStmt, 1, resourceId);
                
                while (sqlite3_step(ppStmt) == SQLITE_ROW)
                {
                    lockResource(sqlite3_column_int(ppStmt,0), username, duration);
                }
                sqlite3_finalize(ppStmt);          
        }
        
        Event ev;
    
        ev.TypeEvent = CB_LOCK;
        ev.id = EvQueuePtr->next_id;
        ev.resourceId = resourceId;
        ev.userDest = "";
        ev.userSrc = username;
    
        EvQueuePtr->push_back(ev);
        
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
    }
    else
    {
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
        
        ::LabrestAPI::ResourceIsLock rl;
        
        rl.ice_throw();
    }
    }
    else
    {
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
        
        ::LabrestAPI::InvalidValue iv;
        
        iv.ice_throw();
    }
    
    return status;
}
Beispiel #18
0
	int Statement::Bind(int index)
	{
		return IsValid()
			? sqlite3_bind_null(m_st, index+1)
			: SQLITE_ERROR;
	}
Beispiel #19
0
void QgsOSMDatabase::exportSpatiaLiteNodes( const QString &tableName, const QStringList &tagKeys, const QStringList &notNullTagKeys )
{
  QString sqlInsertPoint = QStringLiteral( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) );
  for ( int i = 0; i < tagKeys.count(); ++i )
    sqlInsertPoint += QStringLiteral( ",?" );
  sqlInsertPoint += QLatin1String( ", GeomFromWKB(?, 4326))" );
  sqlite3_stmt *stmtInsert = nullptr;
  if ( sqlite3_prepare_v2( mDatabase, sqlInsertPoint.toUtf8().constData(), -1, &stmtInsert, nullptr ) != SQLITE_OK )
  {
    mError = QStringLiteral( "Prepare SELECT FROM nodes failed." );
    return;
  }

  QgsOSMNodeIterator nodes = listNodes();
  QgsOSMNode n;
  while ( ( n = nodes.next() ).isValid() )
  {
    QgsOSMTags t = tags( false, n.id() );

    // skip untagged nodes: probably they form a part of ways
    if ( t.count() == 0 )
      continue;

    //check not null tags
    bool skipNull = false;
    for ( int i = 0; i < notNullTagKeys.count() && !skipNull; ++i )
      if ( !t.contains( notNullTagKeys[i] ) )
        skipNull = true;

    if ( skipNull )
      continue;

    QgsGeometry geom = QgsGeometry::fromPoint( n.point() );
    int col = 0;
    sqlite3_bind_int64( stmtInsert, ++col, n.id() );

    // tags
    for ( int i = 0; i < tagKeys.count(); ++i )
    {
      if ( t.contains( tagKeys[i] ) )
        sqlite3_bind_text( stmtInsert, ++col, t.value( tagKeys[i] ).toUtf8().constData(), -1, SQLITE_TRANSIENT );
      else
        sqlite3_bind_null( stmtInsert, ++col );
    }

    QByteArray wkb( geom.exportToWkb() );
    sqlite3_bind_blob( stmtInsert, ++col, wkb.constData(), wkb.length(), SQLITE_STATIC );

    int insertRes = sqlite3_step( stmtInsert );
    if ( insertRes != SQLITE_DONE )
    {
      mError = QStringLiteral( "Error inserting node %1 [%2]" ).arg( n.id() ).arg( insertRes );
      break;
    }

    sqlite3_reset( stmtInsert );
    sqlite3_clear_bindings( stmtInsert );
  }

  sqlite3_finalize( stmtInsert );
}
Beispiel #20
0
/*
 * success,err = statement:execute(...)
 */
static int statement_execute(lua_State *L) {
    int n = lua_gettop(L);
    statement_t *statement = (statement_t *)luaL_checkudata(L, 1, DBD_SQLITE_STATEMENT);
    int p;
    int errflag = 0;
    const char *errstr = NULL;
    int expected_params;
    int num_bind_params = n - 1;

    if (!statement->stmt) {
	lua_pushboolean(L, 0);
	lua_pushstring(L, DBI_ERR_EXECUTE_INVALID);
	return 2;
    }

    /*
     * reset the handle before binding params
     * this will be a NOP if the handle has not
     * been executed
     */
    if (sqlite3_reset(statement->stmt) != SQLITE_OK) {
	lua_pushboolean(L, 0);
	lua_pushfstring(L, DBI_ERR_EXECUTE_FAILED, sqlite3_errmsg(statement->conn->sqlite));
	return 2;
    }

    sqlite3_clear_bindings(statement->stmt);

    expected_params = sqlite3_bind_parameter_count(statement->stmt);
    if (expected_params != num_bind_params) {
	/*
         * sqlite3_reset does not handle this condition,
         * and the client library will fill unset params
         * with NULLs
         */ 
	lua_pushboolean(L, 0);
	lua_pushfstring(L, DBI_ERR_PARAM_MISCOUNT, expected_params, num_bind_params); 
	return 2;
    }

    for (p = 2; p <= n; p++) {
	int i = p - 1;
	int type = lua_type(L, p);
	char err[64];

	switch(type) {
	case LUA_TNIL:
	    errflag = sqlite3_bind_null(statement->stmt, i) != SQLITE_OK;
	    break;
	case LUA_TNUMBER:
	    errflag = sqlite3_bind_double(statement->stmt, i, lua_tonumber(L, p)) != SQLITE_OK;
	    break;
	case LUA_TSTRING:
	    errflag = sqlite3_bind_text(statement->stmt, i, lua_tostring(L, p), -1, SQLITE_STATIC) != SQLITE_OK;
	    break;
	case LUA_TBOOLEAN:
	    errflag = sqlite3_bind_int(statement->stmt, i, lua_toboolean(L, p)) != SQLITE_OK;
	    break;
	default:
	    /*
	     * Unknown/unsupported value type
	     */
	    errflag = 1;
            snprintf(err, sizeof(err)-1, DBI_ERR_BINDING_TYPE_ERR, lua_typename(L, type));
            errstr = err;
	}

	if (errflag)
	    break;
    }   

    if (errflag) {
	lua_pushboolean(L, 0);
	if (errstr)
	    lua_pushfstring(L, DBI_ERR_BINDING_PARAMS, errstr);
	else
	    lua_pushfstring(L, DBI_ERR_BINDING_PARAMS, sqlite3_errmsg(statement->conn->sqlite));
    
	return 2;
    }
    
    try_begin_transaction(statement->conn);

    if (!step(statement)) {
	lua_pushboolean(L, 0);
	lua_pushfstring(L, DBI_ERR_EXECUTE_FAILED, sqlite3_errmsg(statement->conn->sqlite));
	return 2;
    }

    statement->affected = sqlite3_changes(statement->conn->sqlite);

    lua_pushboolean(L, 1);
    return 1;
}
Beispiel #21
0
DLL_FUNCTION(int32_t) BU_SQLite_Bind_Null(sqlite3_stmt* pStmt, int32_t index) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Bind_Null=_BU_SQLite_Bind_Null@8")
	return sqlite3_bind_null(pStmt, index);
}
void sqlite3_command::bind(int index) {
	if(sqlite3_bind_null(this->stmt, index)!=SQLITE_OK)
		throw database_error(&m_con);
}
Beispiel #23
0
// Bind a NULL value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex)
{
    const int ret = sqlite3_bind_null(mStmtPtr, aIndex);
    check(ret);
}
Beispiel #24
0
/* --------------------------------------------------------------- */
void R_sqlbind( const int func )
{
	int col, i;
	double d;
	char type;

	if (!sqldb)   Lerror(ERR_DATABASE,1);
	if (!sqlstmt) Lerror(ERR_DATABASE,0);

	if (ARGN==0) {
		Licpy(ARGR, sqlite3_bind_parameter_count(sqlstmt));
		return;
	}

	if (ARGN!=3) Lerror(ERR_INCORRECT_CALL,0);

	if (Ldatatype(ARG1,'N'))
		col = Lrdint(ARG1);
	else {
		LASCIIZ(*ARG1);
		col = sqlite3_bind_parameter_index(sqlstmt, LSTR(*ARG1));
	}
	get_pad(2, type);

	switch (type) {
		case 'b': case 'B':	/* blob */
			Licpy(ARGR, sqlite3_bind_blob(sqlstmt, col,
				LSTR(*ARG3), LLEN(*ARG3), SQLITE_TRANSIENT));
			break;

		case 'i': case 'I':	/* integer */
			get_i(3, i);
			Licpy(ARGR, sqlite3_bind_int(sqlstmt, col, i));
			break;

		case 'd': case 'D':	/* double */
		case 'f': case 'F':
			L2REAL(ARG3);
			Licpy(ARGR, sqlite3_bind_double(sqlstmt, col, LREAL(*ARG3)));
			break;

		case 's': case 'S':	/* double */
		case 't': case 'T':
			L2STR(ARG3);
			Licpy(ARGR, sqlite3_bind_text(sqlstmt, col,
				LSTR(*ARG3), LLEN(*ARG3), SQLITE_TRANSIENT));
			break;

		case 'n': case 'N':	/* null */
			Licpy(ARGR, sqlite3_bind_null(sqlstmt, col));
			break;

		case 'z': case 'Z':	/* zero blob */
			get_i(3, i);
			Licpy(ARGR, sqlite3_bind_zeroblob(sqlstmt, col, i));
			break;

		default:
			Lerror(ERR_INCORRECT_CALL,0);
	}
} /* R_sqlbind */
Beispiel #25
0
int proxy_db_bind_stmt(pool *p, const char *stmt, int idx, int type,
    void *data) {
  sqlite3_stmt *pstmt;
  int res;
 
  if (p == NULL ||
      stmt == NULL) {
    errno = EINVAL;
    return -1;
  }

  /* SQLite3 bind parameters start at index 1. */
  if (idx < 1) {
    errno = EINVAL;
    return -1;
  }

  if (prepared_stmts == NULL) {
    errno = ENOENT;
    return -1;
  }

  pstmt = pr_table_get(prepared_stmts, stmt, NULL);
  if (pstmt == NULL) {
    pr_trace_msg(trace_channel, 19,
      "unable to find prepared statement for '%s'", stmt);
    errno = ENOENT;
    return -1;
  }

  switch (type) {
    case PROXY_DB_BIND_TYPE_INT: {
      int i;

      if (data == NULL) {
        errno = EINVAL;
        return -1;
      }

      i = *((int *) data);
      res = sqlite3_bind_int(pstmt, idx, i);
      if (res != SQLITE_OK) {
        pr_trace_msg(trace_channel, 4,
          "error binding parameter %d of '%s' to INT %d: %s", idx, stmt, i,
          sqlite3_errmsg(proxy_dbh));
      }
      break;
    }

    case PROXY_DB_BIND_TYPE_LONG: {
      long l;

      if (data == NULL) {
        errno = EINVAL;
        return -1;
      }

      l = *((long *) data);
      res = sqlite3_bind_int(pstmt, idx, l);
      if (res != SQLITE_OK) {
        pr_trace_msg(trace_channel, 4,
          "error binding parameter %d of '%s' to LONG %ld: %s", idx, stmt, l,
          sqlite3_errmsg(proxy_dbh));
      }
      break;
    }

    case PROXY_DB_BIND_TYPE_TEXT: {
      const char *text;

      if (data == NULL) {
        errno = EINVAL;
        return -1;
      }

      text = (const char *) data;
      res = sqlite3_bind_text(pstmt, idx, text, -1, NULL);
      if (res != SQLITE_OK) {
        pr_trace_msg(trace_channel, 4,
          "error binding parameter %d of '%s' to TEXT '%s': %s", idx, stmt,
          text, sqlite3_errmsg(proxy_dbh));
      }
      break;
    }

    case PROXY_DB_BIND_TYPE_NULL:
      res = sqlite3_bind_null(pstmt, idx);
      if (res != SQLITE_OK) {
        pr_trace_msg(trace_channel, 4,
          "error binding parameter %d of '%s' to NULL: %s", idx, stmt,
          sqlite3_errmsg(proxy_dbh));
      }
      break;

    default:
      pr_trace_msg(trace_channel, 2,
        "unknown/unsupported bind data type %d", type);
      errno = EINVAL;
      return -1;
  }

  return 0;
}
Beispiel #26
0
unsigned long rb_c_impl_SQLite3_execute(int argc, VALUE *argv, void* pDB)
{
    sqlite3 * db = NULL;
	void **ppDB = &pDB;		
	sqlite3_stmt *statement = NULL;
	const char* sql = NULL;
	VALUE arRes = rb_ary_new();
    VALUE* colNames = NULL;
	int nRes = 0;
    char * szErrMsg = 0;
    int is_batch = 0;

	if ((argc < 2) || (argc > 3))
		rb_raise(rb_eArgError, "wrong # of arguments(%d for 3)",argc);
	
	db = (sqlite3 *)rho_db_get_handle(*ppDB);
	sql = RSTRING_PTR(argv[0]);
    is_batch = argv[1] == Qtrue ? 1 : 0;

    RAWTRACE1("db_execute: %s", sql);

    PROF_START_CREATED("SQLITE");
    if ( is_batch )
    {
        PROF_START_CREATED("SQLITE_EXEC");

        rho_db_lock(*ppDB);
        nRes = sqlite3_exec(db, sql,  NULL, NULL, &szErrMsg);
        rho_db_unlock(*ppDB);

        PROF_STOP("SQLITE_EXEC");
    }
    else
    {
        rho_db_lock(*ppDB);
        PROF_START_CREATED("SQLITE_PREPARE");
        nRes = rho_db_prepare_statement(*ppDB, sql, -1, &statement);
        PROF_STOP("SQLITE_PREPARE");
        //nRes = sqlite3_prepare_v2(db, sql, -1, &statement, NULL);
        if ( nRes != SQLITE_OK)
        {
            szErrMsg = (char *)sqlite3_errmsg(db);
            rho_db_unlock(*ppDB);

            rb_raise(rb_eArgError, "could not prepare statement: %d; Message: %s",nRes, (szErrMsg?szErrMsg:""));
        }

        if ( (argc > 2) && (TYPE(argv[2]) == T_ARRAY) )
        {
            int i = 0;
            VALUE args = argv[2];
            if ( RARRAY_LEN(args) > 0 && TYPE(RARRAY_PTR(args)[0]) == T_ARRAY )
                args = RARRAY_PTR(args)[0];

            for( ; i < RARRAY_LEN(args); i++ )
            {
                VALUE arg = RARRAY_PTR(args)[i];
                if (NIL_P(arg))
                {
                    sqlite3_bind_null(statement, i+1);
                    continue;
                }

                switch( TYPE(arg) )
                {
                case T_STRING:
                    sqlite3_bind_text(statement, i+1, RSTRING_PTR(arg), RSTRING_LEN(arg), SQLITE_TRANSIENT);
                    break;
                case T_FLOAT:
                    sqlite3_bind_double(statement, i+1, NUM2DBL(arg));
                    break;
                case T_FIXNUM:
                case T_BIGNUM:
                    sqlite3_bind_int64(statement, i+1, NUM2LL(arg));
                    break;
                case T_DATA:
                    if (CLASS_OF(arg) == rb_cTime)
                    {
                        VALUE intVal = rb_funcall(arg, rb_intern("to_i"), 0);	
                        sqlite3_bind_int64(statement, i+1, NUM2LL(intVal));
                        break;
                    }

                default:
					{
						VALUE strVal = rb_funcall(arg, rb_intern("to_s"), 0);	
	                    sqlite3_bind_text(statement, i+1, RSTRING_PTR(strVal), -1, SQLITE_TRANSIENT);	
					}
					break;
                }
            }
        }

        PROF_START_CREATED("SQLITE_EXEC");
        nRes = sqlite3_step(statement);
        PROF_STOP("SQLITE_EXEC");

	    while( nRes== SQLITE_ROW ) {
		    int nCount = sqlite3_data_count(statement);
		    int nCol = 0;
		    VALUE hashRec = rb_hash_new();

            //if ( !colNames )
            //    colNames = getColNames(statement, nCount);

		    for(;nCol<nCount;nCol++){
			    int nColType = sqlite3_column_type(statement,nCol);
			    const char* szColName = sqlite3_column_name(statement,nCol);
                
			    //VALUE colName = rb_str_new2(szColName);
                VALUE colName = rb_utf8_str_new_cstr(szColName);

                VALUE colValue = Qnil;
    			
			    switch(nColType){
				    case SQLITE_NULL:
					    break;
                    case SQLITE_FLOAT:
                    {
                        double dVal = sqlite3_column_double(statement, nCol);
                        colValue = DBL2NUM(dVal);
                        break;
                    }
                    case SQLITE_INTEGER:
                    {
                        sqlite_int64 nVal = sqlite3_column_int64(statement, nCol);
                        colValue = LL2NUM(nVal);
                        break;
                    }
				    default:{
                        sqlite3_value * sqlValue = sqlite3_column_value(statement, nCol);
                        int nLen = sqlite3_value_bytes(sqlValue);
                        const char*  szValue = (const char *)sqlite3_value_text(sqlValue);
					    //char *text = (char *)sqlite3_column_text(statement, nCol);
					    
                        //colValue = rb_str_new(szValue, nLen);
                        colValue = rb_utf8_str_new(szValue, nLen);
					    break;
				    }
			    }
    			
			    rb_hash_aset(hashRec, colName/*colNames[nCol]*/, colValue);
		    }
    		
		    rb_ary_push(arRes, hashRec);

            PROF_START_CREATED("SQLITE_EXEC");
            nRes = sqlite3_step(statement);
            PROF_STOP("SQLITE_EXEC");

	    }

        rho_db_unlock(*ppDB);

    }

    if ( statement )
        //sqlite3_finalize(statement);
        sqlite3_reset(statement);

    if ( colNames )
        free(colNames);

    if ( nRes != SQLITE_OK && nRes != SQLITE_ROW && nRes != SQLITE_DONE )
    {
        if ( !szErrMsg )
            szErrMsg = (char*)sqlite3_errmsg(db);

        rb_raise(rb_eArgError, "could not execute statement: %d; Message: %s",nRes, (szErrMsg?szErrMsg:""));
    }

    PROF_STOP("SQLITE");

	return arRes;
}
Beispiel #27
0
 bool operator()(const sql_null_type &value) const
 {
     return sqlite3_bind_null(stmt_.get(), index_);
 }
Beispiel #28
0
int  LabrestAPI::LabrestDB::addResourse(::std::string name, ::std::string description, int typeId, int parentId)
{
 //   ::std::cout << "LabrestDB::addResourse()  called" << ::std::endl;
    
    bool status, stat2;
    
    int id;

    sqlite3_stmt *ppStmt;
    
    sqlite3_exec(db, "BEGIN", 0, 0, 0);
    
    if (parentId != -1) 
    {
        status = ExistsResource(parentId);
    }
    stat2 = ExistsResourceType(typeId);
    
    if (status && stat2)
    { 
        sqlite3_prepare(db,"insert into resource(name, description, type_id, "
            "lock_status, parent) values(?, ?, ?, ?, ?);",-1,&ppStmt,0);

        sqlite3_bind_text(ppStmt, 1, name.c_str(), name.length(),NULL);

        sqlite3_bind_text(ppStmt, 2, description.c_str(), description.length(),NULL);

        sqlite3_bind_int(ppStmt, 3, typeId);
    
        sqlite3_bind_null(ppStmt, 4);
    
        if (parentId == -1) sqlite3_bind_null(ppStmt, 5);
        else  sqlite3_bind_int(ppStmt, 5, parentId);

        if (sqlite3_step(ppStmt) == SQLITE_DONE)
        {
            status = true;
        }
        else
        {
            status = false;
        }
        sqlite3_finalize(ppStmt);
        
        if (status)
        {
             sqlite3_prepare(db,"select max(id) from resource;",-1,&ppStmt,0);

        if (sqlite3_step(ppStmt) == SQLITE_ROW)
        {       
            id = sqlite3_column_int(ppStmt,0);
            
            status = true;
        }
        else
        {
            status = false;
        }
        sqlite3_finalize(ppStmt);
        }
      
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
    }
    else 
    {
        sqlite3_exec(db, "COMMIT", 0, 0, 0);
        
        ::LabrestAPI::InvalidValue iv;
        
        iv.ice_throw();
    }
    return id;
}
Beispiel #29
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
#ifdef HAVE_RUBY_ENCODING_H
              || rb_enc_get_index(value) == rb_ascii8bit_encindex()
#endif
        ) {
        status = sqlite3_bind_blob(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      } else {
#ifdef HAVE_RUBY_ENCODING_H
        if(!UTF8_P(value)) {
              VALUE db          = rb_iv_get(self, "@connection");
              VALUE encoding    = rb_funcall(db, rb_intern("encoding"), 0);
              rb_encoding * enc = rb_to_encoding(encoding);
              value = rb_str_export_to_enc(value, enc);
          }
#endif

        status = sqlite3_bind_text(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      }
      break;
    case T_BIGNUM:
#if SIZEOF_LONG < 8
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)NUM2LL(value));
          break;
      }
#endif
    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 #30
0
bool SQLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("SQLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("SQLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("SQLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}