Пример #1
0
void Transfer::addTransfer ( int fromaccount, int fromparent, int toaccount, int toparent, int day, int month, int year, float amount, int cleared )
  {
    int nextrowid = -1;
    char **results;
    sqlite_get_table ( db, "select count() from transfers;", &results, 0, 0, 0 );
    if ( atoi ( results [ 1 ] ) != 0 )
      {
        char **results;
        sqlite_get_table ( db, "select min ( rowid ) from transfers;", &results, 0, 0, 0 );
        nextrowid = ( atoi ( results [ 1 ] ) ) - 1;
      }
    sqlite_exec_printf ( db, "insert into transfers values ( %i, %i, %i, %i, %i, %i, %i, 0, 0, %.2f, %i, 0, 0, 0, 0, 0, %i );", 0, 0, 0, fromaccount, fromparent, toaccount, toparent, day, month, year, amount, cleared, nextrowid );
  }
Пример #2
0
QueryResult* DatabaseSqlite::Query(const char *sql)
{
    char *errmsg;

    if (!mSqlite)
        return 0;

    char **tableData;
    int rowCount;
    int fieldCount;

    sqlite_get_table(mSqlite, sql, &tableData, &rowCount, &fieldCount, &errmsg);

    if (!rowCount)
        return 0;

    if (!tableData)
    {

        if (errmsg)
            sqlite_freemem(errmsg);
        return 0;
    }

    QueryResultSqlite *queryResult = new QueryResultSqlite(tableData, rowCount, fieldCount);
    if(!queryResult)
    {

        return 0;
    }

    queryResult->NextRow();

    return queryResult;
}
Пример #3
0
static int dbd_sqlite_query(apr_dbd_t * sql, int *nrows, const char *query)
{
    char **result;
    int ret;
    int tuples = 0;
    int fields = 0;

    if (sql->trans && sql->trans->errnum) {
        return sql->trans->errnum;
    }

    FREE_ERROR_MSG(sql);

    ret =
        sqlite_get_table(sql->conn, query, &result, &tuples, &fields,
                         &sql->errmsg);
    if (ret == SQLITE_OK) {
        *nrows = sqlite_changes(sql->conn);

        if (tuples > 0)
            free(result);

        ret = 0;
    }

    if (TXN_NOTICE_ERRORS(sql->trans)) {
        sql->trans->errnum = ret;
    }

    return ret;
}
Пример #4
0
void towardat::fetch(void) {
//printf("in fetchcurdata with %i\n",id);
	int i, j;
	int nRows, nCols;
	char **result;
	BString sql;	
	sql = "SELECT ";
	sql += "nazwa, symbol, pkwiu, jm";
	sql += ", usluga, dodany, notatki, vatid";
	sql += ", netto, zakupu, marza, rabat, kurs, clo";
	sql += ", magazyn, magzmiana";
	sql += " FROM towar WHERE id = ";
	sql << id;
//printf("sql:%s\n",sql.String());
	sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i, %s\n", nRows, nCols, dbErrMsg);
	// readout data
	i = nCols;
	for (j=0;j<=3;j++) {
		data[j] = result[i++];
	}
	usluga = toint(result[i++]);
	dodany = result[i++];
	notatki = result[i++];
	vatid = toint(result[i++]);
	for (j=0;j<=5;j++) {
		ceny[j] = result[i++];
	}
	magazyn = result[i++];
	magzmiana = result[i++];
	sqlite_free_table(result);
}
Пример #5
0
void fakturadat::fetch(void) {
//printf("in fetchcurdata with %i\n",id);
	int i, j;
	int nRows, nCols;
	char **result;
	BString sql;	
	sql = "SELECT ";
	sql += "nazwa";
	sql += ", miejsce_wystawienia, wystawil, data_wystawienia, data_sprzedazy";
	sql += ", srodek_transportu, sposob_zaplaty, termin_zaplaty";
	sql += ", zapl_kwota, zapl_dnia, uwagi";
	sql += ", onazwa, oadres, okod, omiejscowosc, otelefon, oemail";
	sql += ", onip, oregon, obank, okonto";
	sql += " FROM faktura WHERE id = ";
	sql << id;
//printf("sql:%s\n",sql.String());
	sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i, %s\n", nRows, nCols, dbErrMsg);
	// readout data
	i = nCols;
	nazwa = result[i++];
	for (j=0;j<=6;j++) {
		ogol[j] = result[i++];
	}
	ogol[8] = result[i++];
	ogol[9] = result[i++];
	uwagi = result[i++];
	odata[0] = result[i++];
	for (j=2;j<=10;j++) {
		odata[j] = result[i++];
	}
	sqlite_free_table(result);
}
Пример #6
0
void firmadat::fetch(void) {
//printf("in fetchcurdata with %i\n",id);
	int i, j;
	int nRows, nCols;
	char **result;
	BString sql;	
	sql = "SELECT ";
	sql += "nazwa, symbol, adres, kod, miejscowosc, telefon, email";
	sql += ", nip, regon, bank, konto";
	sql += ", odbiorca, dostawca, aktywny, zablokowany";
	sql += " FROM firma WHERE id = ";
	sql << id;
//printf("sql:%s\n",sql.String());
	sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i\n", nRows, nCols);
	// readout data
	i = nCols;
	for (j=0;j<=10;j++) {
		data[j] = result[i++];
	}
	odbiorca = toint(result[i++]);
	dostawca = toint(result[i++]);
	aktywny = toint(result[i++]);
	zablokowany = toint(result[i++]);

	sqlite_free_table(result);
}
Пример #7
0
void tabTowar::RefreshVatSymbols(void) {
	int i = vatRows;
	while (i>=0) {
		delete menuvat->RemoveItem(i--);
	}

	delete [] vatIds;

	int nRows, nCols;
	char **result;
	BMessage *msg;

	sqlite_get_table(dbData, "SELECT id, nazwa FROM stawka_vat WHERE aktywne = 1 ORDER BY id", &result, &nRows, &nCols, &dbErrMsg);
	if (nRows < 1) {
		// XXX Panic! empty vat table
	} else {
		vatMenuItems = new BMenuItem*[nRows];
		vatIds = new int[nRows];
		vatRows = nRows;
		for (int i=1;i<=nRows;i++) {
			msg = new BMessage(MENUVAT);
			msg->AddInt32("_vatid", toint(result[i*nCols+0]));
			vatIds[i-1] = toint(result[i*nCols+0]);
			vatMenuItems[i-1] = new BMenuItem(result[i*nCols+1], msg);
			menuvat->AddItem(vatMenuItems[i-1]);
		}
	}
	sqlite_free_table(result);
}
Пример #8
0
int
_ds_verify_signature (DSPAM_CTX * CTX, const char *signature)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[128];
  char *err=NULL, **row;
  int nrow, ncolumn;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_verify_signature: invalid database handle (NULL)");
    return EINVAL;
  }

  snprintf (query, sizeof (query),
        "select signature from dspam_signature_data where signature = \"%s\"",
        signature);

  if ((sqlite_get_table(s->dbh, query, &row, &nrow, &ncolumn, &err))!=SQLITE_OK)  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  sqlite_free_table(row);

  if (nrow<1) {
    return -1;
  }

  return 0;
}
Пример #9
0
void pozfaklist::fetch(int fakturaid) {
///printf("fetchpozfak id=%i\n", fakturaid);
	pozfakdata *data;
	int i, j;
	int nRows, nCols;
	char **result;
	BString sql, cbrutto;	

	// clear current list!
	clear();

	sql = "SELECT ";
	sql += "id, lp, ilosc";
	sql += ", nazwa, pkwiu, jm, vatid, netto, rabat";
	sql += " FROM pozycjafakt WHERE fakturaid = ";
	sql << fakturaid;
	sql += " ORDER BY lp";
//printf("sql:%s\n",sql.String());
	sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i, %s\n", nRows, nCols, dbErrMsg);
	if (nRows < 1)
		return;
	// readout data
	i = nCols;
	j = 1;
	while (j <= nRows) {
		data = new pozfakdata();
		i++;							// id, unused
		data->data[0] = result[i++];	// lp, unused
		data->data[3] = result[i++];	// ilosc
		data->data[1] = result[i++];	// nazwa
		data->data[2] = result[i++];	// pkwiu
		data->data[4] = result[i++];	// jm
		data->vatid = toint(result[i++]); //vatid
		data->data[11] = result[i++];	// c.netto
		data->data[5] = result[i++];	// rabat
		addlast(data);
		// 6, 7, 8, 9, 10 - cjednost, w.netto, vat, wvat, wbrutto
		int nCols;
		char **result = calcBrutto(data->data[11].String(), data->data[5].String(), data->data[3].String(), data->vatid, &nCols);
		if (nCols<1) {
			data->data[6] = data->data[7] = data->data[9] = data->data[10] = "";
		} else {
			data->data[6] = result[nCols+0];
			data->data[7] = result[nCols+3];
			data->data[9] = result[nCols+4];
			data->data[10] = result[nCols+5];
		}
		calcBruttoFin(result);
		// vat = stawka
		sql = "SELECT nazwa FROM stawka_vat WHERE id = "; sql << data->vatid;
		data->data[8] = execSQL(sql.String());
		j++;							// next row
	}
	sqlite_free_table(result);
	setlp();							// reset lp
}
Пример #10
0
QStringList* Budget::getBudgetIDs ()
  {
    QStringList *ids = new QStringList ();
    char **results;
    int rows, counter;
    sqlite_get_table ( bdb, "select budgetid from budgets;", &results, &rows, NULL, NULL );
    for ( counter = 0; counter < rows; counter++ )
      ids->append ( results [ counter+1 ] );
    return ids;
  }
Пример #11
0
int Budget::addBudget ( QString name, int type, QString description, QString currency, int startday, int startmonth, int startyear, int endday, int endmonth, int endyear, int defaultview )
  {
    sqlite_exec_printf ( bdb, "insert into budgets values ( '%q', %i, '%q', '%q', %i, %i, %i, %i, %i, %i, %i, NULL );", 0, 0, 0, ( const char * ) name, type, ( const char * ) description, ( const char * ) currency, startday, startmonth, startyear, endday, endmonth, endyear, defaultview );
    char **results;
    sqlite_get_table ( bdb, "select last_insert_rowid() from budgets;", &results, NULL, NULL, NULL );
    QString tablename = "table";
    tablename.append ( results [ 1 ] );
    sqlite_exec_printf ( bdb, "create table '%q' ( name, lineitemamount, type, lineitemid integer primary key );", 0, 0, 0, ( const char* ) tablename );
    return atoi ( results [ 1 ] );
  }
Пример #12
0
QStringList* Budget::getBudgetNames ()
  {
    QStringList *names = new QStringList ();
    char **results;
    int rows, counter;
    sqlite_get_table ( bdb, "select name from budgets;", &results, &rows, NULL, NULL );
    names->append ( "None" );
    for ( counter = 0; counter < rows; counter++ )
      names->append ( results [ counter+1 ] );
    return names;
  }
Пример #13
0
int pozfaklist::generate_id(void) {
	int newid = 1;
	int nRows, nCols;
	char **result;
	sqlite_get_table(dbData, "SELECT MAX(id) FROM pozycjafakt", &result, &nRows, &nCols, &dbErrMsg);
	if (nRows > 0) {
		// there is something in db
		newid = toint(result[1]) + 1;
	}
	sqlite_free_table(result);
	return newid;
}
Пример #14
0
int
_sqlite_drv_get_spamtotals (DSPAM_CTX * CTX)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[1024];
  char *err=NULL, **row;
  int nrow, ncolumn;
  int rc;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_sqlite_drv_get_spamtotals: invalid database handle (NULL)");
    return EINVAL;
  }

  memset(&s->control_totals, 0, sizeof(struct _ds_spam_totals));
  memset(&CTX->totals, 0, sizeof(struct _ds_spam_totals));

  snprintf (query, sizeof (query),
            "select spam_learned, innocent_learned, "
            "spam_misclassified, innocent_misclassified, "
            "spam_corpusfed, innocent_corpusfed, "
            "spam_classified, innocent_classified "
            " from dspam_stats");

  if ((sqlite_get_table(s->dbh, query, &row, &nrow, &ncolumn, &err))!=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  if (nrow>0 && row != NULL) {
    CTX->totals.spam_learned		= strtol (row[ncolumn], NULL, 0);
    CTX->totals.innocent_learned	= strtol (row[ncolumn+1], NULL, 0);
    CTX->totals.spam_misclassified	= strtol (row[ncolumn+2], NULL, 0);
    CTX->totals.innocent_misclassified 	= strtol (row[ncolumn+3], NULL, 0);
    CTX->totals.spam_corpusfed		= strtol (row[ncolumn+4], NULL, 0);
    CTX->totals.innocent_corpusfed	= strtol (row[ncolumn+5], NULL, 0);
    CTX->totals.spam_classified		= strtol (row[ncolumn+6], NULL, 0);
    CTX->totals.innocent_classified	= strtol (row[ncolumn+7], NULL, 0);
    rc = 0;
  } else {
    rc = EFAILURE;
  }

  sqlite_free_table(row);
  if ( !rc )
    memcpy(&s->control_totals, &CTX->totals, sizeof(struct _ds_spam_totals));

  return rc;
}
Пример #15
0
// XXX this is duplicated in befaktab!
const char *pozfaklist::execSQL(const char *input) {
	int nRows, nCols;
	char **result;
	static BString res;
//printf("sql=[%s]\n",sql.String());
	sqlite_get_table(dbData, input, &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i, %s\n", nRows, nCols, dbErrMsg);
	if (nRows < 1)
		res = "";
	else
		res = result[1];
	sqlite_free_table(result);
	return res.String();
}
Пример #16
0
void pozfaklist::updateStorage(int fakturaid = -1) {
	BString sql, nazwa, magazyn, stare;
	pozfakitem *cur = start;
	int ret;
	int nRows, nCols;
	char **result;
	bool usluga;

	while (cur!=NULL) {
		// get state
		nazwa = cur->data->data[1]; nazwa.ReplaceAll("'","''"); nazwa.Prepend("'"); nazwa.Append("'");
		sql = "SELECT usluga,magazyn FROM towar WHERE nazwa = "; sql += nazwa;
		sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
		if (nRows<1) {
			// nie ma takiego w bazie, nic nie robic
		} else {
			// usluga?
			usluga = toint(result[nCols+0]);
//			printf("usluga:%i\n", usluga);
			if (!usluga) {
				// calc new magazyn state
				magazyn = result[nCols+1];
//				printf("[%s]:mag:%s, nowe:%s\n",nazwa.String(),magazyn.String(),cur->data->data[3].String());
				if (fakturaid > 0) {
					// get old state
					sql = "SELECT ilosc FROM pozycjafakt WHERE fakturaid = "; sql << fakturaid;
					sql += " AND nazwa = "; sql += nazwa;
					stare = execSQL(sql.String());
				} else {
					stare = "0";
				}
				sql = "SELECT 0"; sql += stare; sql += "+0"; sql += magazyn; sql += "-0"; sql += cur->data->data[3];
//printf("sql=[%s],magazyn=[%s]\n",sql.String(),execSQL(sql.String()));
				magazyn = execSQL(sql.String());
//				printf("nowy mag[%s]: [%s]\n",nazwa.String(), magazyn.String());
				// update magazyn state (note that nazwa() is already quoted)
				ret = sqlite_exec_printf(dbData,
					"UPDATE towar SET magazyn = %Q, magzmiana = DATE('now') WHERE nazwa = %s",
					0, 0, &dbErrMsg, magazyn.String(), nazwa.String());
//				printf("got:%i,%s\n",ret,dbErrMsg);
			}
		}
		sqlite_free_table(result);
		cur = cur->nxt;
	}
}
Пример #17
0
static int dbd_sqlite_select(apr_pool_t * pool, apr_dbd_t * sql,
                             apr_dbd_results_t ** results, const char *query,
                             int seek)
{
    char **result;
    int ret = 0;
    int tuples = 0;
    int fields = 0;

    if (sql->trans && sql->trans->errnum) {
        return sql->trans->errnum;
    }

    FREE_ERROR_MSG(sql);

    ret = sqlite_get_table(sql->conn, query, &result, &tuples, &fields,
                           &sql->errmsg);

    if (ret == SQLITE_OK) {
        if (!*results) {
            *results = apr_pcalloc(pool, sizeof(apr_dbd_results_t));
        }

        (*results)->res = result;
        (*results)->ntuples = tuples;
        (*results)->sz = fields;
        (*results)->random = seek;
        (*results)->pool = pool;

        if (tuples > 0)
            apr_pool_cleanup_register(pool, result, free_table,
                                      apr_pool_cleanup_null);

        ret = 0;
    }
    else {
        if (TXN_NOTICE_ERRORS(sql->trans)) {
            sql->trans->errnum = ret;
        }
    }

    return ret;
}
Пример #18
0
int
_ds_get_spamrecord (DSPAM_CTX * CTX, unsigned long long token,
                    struct _ds_spam_stat *stat)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[1024];
  char *err=NULL, **row;
  int nrow, ncolumn;


  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_get_spamrecord: invalid database handle (NULL)");
    return EINVAL;
  }

  snprintf (query, sizeof (query),
            "select spam_hits, innocent_hits from dspam_token_data "
            "where token = '%" LLU_FMT_SPEC "' ", token);

  stat->probability = 0.0;
  stat->spam_hits = 0;
  stat->innocent_hits = 0;
  stat->status &= ~TST_DISK;

  if ((sqlite_get_table(s->dbh, query, &row, &nrow, &ncolumn, &err))!=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  if (nrow < 1)
    sqlite_free_table(row);

  if (nrow < 1 || row == NULL)
    return 0;

  stat->spam_hits = strtol (row[0], NULL, 0);
  stat->innocent_hits = strtol (row[1], NULL, 0);
  stat->status |= TST_DISK;
  sqlite_free_table(row);
  return 0;
}
Пример #19
0
void tabTowar::RefreshIndexList(void) {
	// clear current list
	if (list->CountItems()>0) {
		tab2ListItem *anItem;
		for (int i=0; (anItem=(tab2ListItem*)list->ItemAt(i)); i++)
			delete anItem;
		if (!list->IsEmpty())
			list->MakeEmpty();
	}
	// select list from db
	int nRows, nCols;
	char **result;
	sqlite_get_table(dbData, "SELECT id, symbol, nazwa FROM towar ORDER BY id", &result, &nRows, &nCols, &dbErrMsg);
	if (nRows < 1) {
		// no entries
	} else {
		for (int i=1;i<=nRows;i++)
			list->AddItem(new tab2ListItem(toint(result[i*nCols+0]), result[i*nCols+1], result[i*nCols+2]));
	}
	sqlite_free_table(result);
}
Пример #20
0
static int SQLite2_execute (dbconn_t * c, const char * s)
{
	char **result;
	const char *tail;
	int ret;

	/* Oddly enough a sqlite_get_table will execute sql that inserts and updates! */
	if (sqlite_get_table(c->SQLite2.handle, s, &result, &c->SQLite2.nrows, &c->SQLite2.ncolumns, NULL) != SQLITE_OK) {
		sqlite_free_table(result);
		return 0;
	}
	else {
		sqlite_free_table(result);
		c->SQLite2.sql = string_copy(s, "SQLite2_execute");
		c->SQLite2.last_row = 0;
		c->SQLite2.step_res = 0;

		return c->SQLite2.nrows;
	}

	return -1;
}
Пример #21
0
static int sqlite_odbx_result( odbx_t* handle, odbx_result_t** result, struct timeval* timeout, unsigned long chunk )
{
	char** res;
	long ms = 0;
	int err, nrow, ncolumn;
	struct sres* sres;
	struct sconn* aux = (struct sconn*) handle->aux;


	if( handle->generic == NULL || aux == NULL )
	{
		return -ODBX_ERR_PARAM;
	}

	aux->errmsg = NULL;
	if( aux->stmt == NULL )
	{
		return ODBX_RES_DONE;   /* no more results */
	}

	if( timeout != NULL )
	{
		ms = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
	}

	while( ( err = sqlite_get_table( (sqlite*) handle->generic, aux->stmt, &res, &nrow, &ncolumn, NULL ) ) == SQLITE_BUSY )
	{
		if( ms <= 0 ) { return ODBX_RES_TIMEOUT; }   /* Timeout */

		sqlite_busy_timeout( (sqlite*) handle->generic, 100 );
		ms -= 100;
	}

	free( aux->stmt );
	aux->stmt = NULL;

	if( err != SQLITE_OK )
	{
		aux->errno = err;
		aux->errmsg = (char*) sqlite_error_string( err );
		return -ODBX_ERR_BACKEND;
	}

	if( ( *result = (odbx_result_t*) malloc( sizeof( struct odbx_result_t ) ) ) == NULL )
	{
		return -ODBX_ERR_NOMEM;
	}

	if( ( sres = (struct sres*) malloc( sizeof( struct sres ) ) ) == NULL )
	{
		free( *result );
		*result = NULL;

		return -ODBX_ERR_NOMEM;
	}

	(*result)->generic = (void*) res;
	(*result)->aux = (void*) sres;
	sres->ncolumn = ncolumn;
	sres->nrow = nrow;
	sres->cur = -1;

	if( !ncolumn ) { return ODBX_RES_NOROWS; }   /* empty or not SELECT like query */

	return ODBX_RES_ROWS;   /* result is available */
}
Пример #22
0
int Budget::getLastAdded ()
  {
    char **results;
    sqlite_get_table ( bdb, "select last_insert_rowid() from budgets;", &results, NULL, NULL, NULL );
    return atoi ( results [ 1 ] );
  }
Пример #23
0
int Budget::getNumberOfBudgets ()
  {
    char **results;
    sqlite_get_table ( bdb, "select count() from budgets;", &results, NULL, NULL, NULL );
    return atoi ( results [ 1 ] );
  }
Пример #24
0
int Transfer::getNumberOfTransfers ()
  {
    char **results;
    sqlite_get_table ( db, "select count() from transfers;", &results, 0, 0, 0 );
    return atoi ( results [ 1 ] );
  }
Пример #25
0
int
_ds_getall_spamrecords (DSPAM_CTX * CTX, ds_diction_t diction)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  buffer *query;
  ds_term_t ds_term;
  ds_cursor_t ds_c;
  char scratch[1024];
  struct _ds_spam_stat stat;
  unsigned long long token = 0;
  char *err=NULL, **row;
  int nrow, ncolumn, get_one = 0, i;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_getall_spamrecords: invalid database handle (NULL)");
    return EINVAL;
  }

  stat.spam_hits = 0;
  stat.innocent_hits = 0;

  query = buffer_create (NULL);
  if (query == NULL)
  {
    LOG (LOG_CRIT, ERR_MEM_ALLOC);
    return EUNKNOWN;
  }

  snprintf (scratch, sizeof (scratch),
            "select token, spam_hits, innocent_hits "
            "from dspam_token_data where token in(");

  buffer_cat (query, scratch);
  ds_c = ds_diction_cursor(diction);
  ds_term = ds_diction_next(ds_c);
  while(ds_term)
  {
    snprintf (scratch, sizeof (scratch), "'%" LLU_FMT_SPEC "'", ds_term->key);
    buffer_cat (query, scratch);
    ds_term->s.innocent_hits = 0;
    ds_term->s.spam_hits = 0;
    ds_term->s.probability = 0;
    ds_term->s.status &= ~TST_DISK;
    ds_term = ds_diction_next(ds_c);
    if (ds_term != NULL)
      buffer_cat (query, ",");
    get_one = 1;
  }
  ds_diction_close(ds_c);
  buffer_cat (query, ")");

#ifdef VERBOSE
  LOGDEBUG ("sqlite query length: %ld\n", query->used);
  _sqlite_drv_query_error (strdup("VERBOSE DEBUG (INFO ONLY - NOT AN ERROR)"), query->data);
#endif

  if (!get_one) 
    return 0;

  if ((sqlite_get_table(s->dbh, query->data, &row, &nrow, &ncolumn, &err))
      !=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query->data);
    buffer_destroy(query);
    return EFAILURE;
  }

  if (nrow < 1) {
    sqlite_free_table(row);
    buffer_destroy(query);
    return 0;
  }

  if (row == NULL)
    return 0;

  stat.probability = 0;
  stat.status |= TST_DISK;
  for(i=1;i<=nrow;i++) {
    token = strtoull (row[(i*ncolumn)], NULL, 0);
    stat.spam_hits = strtol (row[1+(i*ncolumn)], NULL, 0);
    stat.innocent_hits = strtol (row[2+(i*ncolumn)], NULL, 0);

    if (stat.spam_hits < 0)
      stat.spam_hits = 0;
    if (stat.innocent_hits < 0)
      stat.innocent_hits = 0;

    ds_diction_addstat(diction, token, &stat);
  }

  sqlite_free_table(row);

  ds_c = ds_diction_cursor(diction);
  ds_term = ds_diction_next(ds_c);
  while(ds_term && !s->control_token) {
    if (ds_term->s.spam_hits && ds_term->s.innocent_hits) {
      s->control_token = ds_term->key;
      s->control_sh = ds_term->s.spam_hits;
      s->control_ih = ds_term->s.innocent_hits;
    }
    ds_term = ds_diction_next(ds_c);
  }
  ds_diction_close(ds_c);

  if (!s->control_token)
  {
     ds_c = ds_diction_cursor(diction);
     ds_term = ds_diction_next(ds_c);
     s->control_token = ds_term->key;
     s->control_sh = ds_term->s.spam_hits;
     s->control_ih = ds_term->s.innocent_hits;
     ds_diction_close(ds_c);
  }

  buffer_destroy (query);
  return 0;
}
Пример #26
0
static boolean_t
smb_nic_dbvalidate(void)
{
	sqlite *db;
	char *errmsg = NULL;
	char *sql;
	char **result;
	int nrow, ncol;
	boolean_t check = B_TRUE;
	int rc;

	sql = sqlite_mprintf("SELECT * FROM db_info");
	if (sql == NULL)
		return (B_FALSE);

	db = smb_nic_dbopen(SMB_NIC_DB_ORW);
	if (db == NULL) {
		sqlite_freemem(sql);
		return (B_FALSE);
	}

	rc = sqlite_get_table(db, sql, &result, &nrow, &ncol, &errmsg);
	sqlite_freemem(sql);

	if (rc != SQLITE_OK) {
		syslog(LOG_ERR, "Failed to validate host database.  Unable " \
		    "to get database information (%s).", NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		smb_nic_dbclose(db);
		return (B_FALSE);
	}

	if (nrow != 1 || ncol != 3) {
		syslog(LOG_ERR, "Failed to validate host database:  bad " \
		    "db_info table.");
		sqlite_free_table(result);
		smb_nic_dbclose(db);
		return (B_FALSE);
	}

	if ((atoi(result[3]) != SMB_NIC_DB_VERMAJOR) ||
	    (atoi(result[4]) != SMB_NIC_DB_VERMINOR) ||
	    (atoi(result[5]) != SMB_NIC_DB_MAGIC)) {
		syslog(LOG_ERR, "Failed to validate host database: bad " \
		    "db_info content.");
		sqlite_free_table(result);
		smb_nic_dbclose(db);
		return (B_FALSE);
	}
	sqlite_free_table(result);

	sql = sqlite_mprintf("SELECT hostname FROM hosts");
	if (sql == NULL) {
		smb_nic_dbclose(db);
		return (B_FALSE);
	}

	rc = sqlite_get_table(db, sql, &result, &nrow, &ncol, &errmsg);
	sqlite_freemem(sql);

	if (rc != SQLITE_OK) {
		syslog(LOG_ERR, "Failed to validate host database.  Unable " \
		"to query for host (%s).", NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		smb_nic_dbclose(db);
		return (B_FALSE);
	}

	sqlite_free_table(result);

	if (nrow == 0)
		/* No hosts in the database */
		check = B_FALSE;

	smb_nic_dbclose(db);
	return (check);
}
Пример #27
0
int
_ds_get_signature (DSPAM_CTX * CTX, struct _ds_spam_signature *SIG,
                   const char *signature)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  unsigned long length;
  unsigned char *mem;
  char query[128];
  char *err=NULL, **row;
  int nrow, ncolumn;
  void *ptr;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_get_signature: invalid database handle (NULL)");
    return EINVAL;
  }

  snprintf (query, sizeof (query),
            "select data, length(data) "
            " from dspam_signature_data where signature = \"%s\"",
            signature);

  if ((sqlite_get_table(s->dbh, query, &row, &nrow, &ncolumn, &err))!=SQLITE_OK)  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  if (nrow<1)
    sqlite_free_table(row);
  if (nrow<1 || row == NULL)
    return EFAILURE;

  length = strlen(row[ncolumn]);
  if (length == 0)
  {
    sqlite_free_table(row);
    return EFAILURE;
  }

  mem = malloc(length+1);
  if (mem == NULL) {
   LOG(LOG_CRIT, ERR_MEM_ALLOC);
   sqlite_free_table(row);
   return EUNKNOWN;
  }

  length = sqlite_decode_binary((unsigned char *) row[ncolumn], mem);
  if (length<=0) {
    LOG(LOG_ERR, "sqlite_decode_binary() failed with error %d", length);
    return EFAILURE;
  }

  ptr = realloc(mem, length);
  if (ptr)
    SIG->data = ptr;
  else {
    LOG(LOG_CRIT, ERR_MEM_ALLOC);
    SIG->data = mem;
  }
  SIG->length = length;

  sqlite_free_table(row);
  return 0;
}
Пример #28
0
/*
** If an input line begins with "." then invoke this routine to
** process that line.
**
** Return 1 to exit and 0 to continue.
*/
static int do_meta_command(char *zLine, struct callback_data *p){
  int i = 1;
  int nArg = 0;
  int n, c;
  int rc = 0;
  char *azArg[50];

  /* Parse the input line into tokens.
  */
  while( zLine[i] && nArg<ArraySize(azArg) ){
    while( isspace(zLine[i]) ){ i++; }
    if( zLine[i]==0 ) break;
    if( zLine[i]=='\'' || zLine[i]=='"' ){
      int delim = zLine[i++];
      azArg[nArg++] = &zLine[i];
      while( zLine[i] && zLine[i]!=delim ){ i++; }
      if( zLine[i]==delim ){
        zLine[i++] = 0;
      }
    }else{
      azArg[nArg++] = &zLine[i];
      while( zLine[i] && !isspace(zLine[i]) ){ i++; }
      if( zLine[i] ) zLine[i++] = 0;
    }
  }

  /* Process the input line.
  */
  if( nArg==0 ) return rc;
  n = strlen(azArg[0]);
  c = azArg[0][0];
  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
    struct callback_data data;
    char *zErrMsg = 0;
    open_db(p);
    memcpy(&data, p, sizeof(data));
    data.showHeader = 1;
    data.mode = MODE_Column;
    data.colWidth[0] = 3;
    data.colWidth[1] = 15;
    data.colWidth[2] = 58;
    sqlite_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite_freemem(zErrMsg);
    }
  }else

  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
    char *zErrMsg = 0;
    open_db(p);
    fprintf(p->out, "BEGIN TRANSACTION;\n");
    if( nArg==1 ){
      sqlite_exec(p->db,
        "SELECT name, type, sql FROM sqlite_master "
        "WHERE type!='meta' AND sql NOT NULL "
        "ORDER BY substr(type,2,1), name",
        dump_callback, p, &zErrMsg
      );
    }else{
      int i;
      for(i=1; i<nArg && zErrMsg==0; i++){
        sqlite_exec_printf(p->db,
          "SELECT name, type, sql FROM sqlite_master "
          "WHERE tbl_name LIKE '%q' AND type!='meta' AND sql NOT NULL "
          "ORDER BY substr(type,2,1), name",
          dump_callback, p, &zErrMsg, azArg[i]
        );
      }
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite_freemem(zErrMsg);
    }else{
      fprintf(p->out, "COMMIT;\n");
    }
  }else

  if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){
    int j;
    char *z = azArg[1];
    int val = atoi(azArg[1]);
    for(j=0; z[j]; j++){
      if( isupper(z[j]) ) z[j] = tolower(z[j]);
    }
    if( strcmp(z,"on")==0 ){
      val = 1;
    }else if( strcmp(z,"yes")==0 ){
      val = 1;
    }
    p->echoOn = val;
  }else

  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
    rc = 1;
  }else

  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
    int j;
    char *z = nArg>=2 ? azArg[1] : "1";
    int val = atoi(z);
    for(j=0; z[j]; j++){
      if( isupper(z[j]) ) z[j] = tolower(z[j]);
    }
    if( strcmp(z,"on")==0 ){
      val = 1;
    }else if( strcmp(z,"yes")==0 ){
      val = 1;
    }
    if(val == 1) {
      if(!p->explainPrev.valid) {
        p->explainPrev.valid = 1;
        p->explainPrev.mode = p->mode;
        p->explainPrev.showHeader = p->showHeader;
        memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
      }
      /* We could put this code under the !p->explainValid
      ** condition so that it does not execute if we are already in
      ** explain mode. However, always executing it allows us an easy
      ** was to reset to explain mode in case the user previously
      ** did an .explain followed by a .width, .mode or .header
      ** command.
      */
      p->mode = MODE_Column;
      p->showHeader = 1;
      memset(p->colWidth,0,ArraySize(p->colWidth));
      p->colWidth[0] = 4;
      p->colWidth[1] = 12;
      p->colWidth[2] = 10;
      p->colWidth[3] = 10;
      p->colWidth[4] = 35;
    }else if (p->explainPrev.valid) {
      p->explainPrev.valid = 0;
      p->mode = p->explainPrev.mode;
      p->showHeader = p->explainPrev.showHeader;
      memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
    }
  }else

  if( c=='h' && (strncmp(azArg[0], "header", n)==0
                 ||
                 strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){
    int j;
    char *z = azArg[1];
    int val = atoi(azArg[1]);
    for(j=0; z[j]; j++){
      if( isupper(z[j]) ) z[j] = tolower(z[j]);
    }
    if( strcmp(z,"on")==0 ){
      val = 1;
    }else if( strcmp(z,"yes")==0 ){
      val = 1;
    }
    p->showHeader = val;
  }else

  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
    fprintf(stderr,zHelp);
  }else

  if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){
    struct callback_data data;
    char *zErrMsg = 0;
    open_db(p);
    memcpy(&data, p, sizeof(data));
    data.showHeader = 0;
    data.mode = MODE_List;
    sqlite_exec_printf(p->db,
      "SELECT name FROM sqlite_master "
      "WHERE type='index' AND tbl_name LIKE '%q' "
      "UNION ALL "
      "SELECT name FROM sqlite_temp_master "
      "WHERE type='index' AND tbl_name LIKE '%q' "
      "ORDER BY 1",
      callback, &data, &zErrMsg, azArg[1], azArg[1]
    );
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite_freemem(zErrMsg);
    }
  }else

  if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){
    int n2 = strlen(azArg[1]);
    if( strncmp(azArg[1],"line",n2)==0
        ||
        strncmp(azArg[1],"lines",n2)==0 ){
      p->mode = MODE_Line;
    }else if( strncmp(azArg[1],"column",n2)==0
              ||
              strncmp(azArg[1],"columns",n2)==0 ){
      p->mode = MODE_Column;
    }else if( strncmp(azArg[1],"list",n2)==0 ){
      p->mode = MODE_List;
    }else if( strncmp(azArg[1],"html",n2)==0 ){
      p->mode = MODE_Html;
    }else if( strncmp(azArg[1],"insert",n2)==0 ){
      p->mode = MODE_Insert;
      if( nArg>=3 ){
        set_table_name(p, azArg[2]);
      }else{
        set_table_name(p, "table");
      }
    }else {
      fprintf(stderr,"mode should be on of: column html insert line list\n");
    }
  }else

  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
    sprintf(p->nullvalue, "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  }else

  if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
    if( p->out!=stdout ){
      fclose(p->out);
    }
    if( strcmp(azArg[1],"stdout")==0 ){
      p->out = stdout;
      strcpy(p->outfile,"stdout");
    }else{
      p->out = fopen(azArg[1], "wb");
      if( p->out==0 ){
        fprintf(stderr,"can't write to \"%s\"\n", azArg[1]);
        p->out = stdout;
      } else {
         strcpy(p->outfile,azArg[1]);
      }
    }
  }else

  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
    if( nArg >= 2) {
      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
    }
    if( nArg >= 3) {
      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
    }
  }else

  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
    rc = 1;
  }else

  if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
    FILE *alt = fopen(azArg[1], "rb");
    if( alt==0 ){
      fprintf(stderr,"can't open \"%s\"\n", azArg[1]);
    }else{
      process_input(p, alt);
      fclose(alt);
    }
  }else

#ifdef SQLITE_HAS_CODEC
  if( c=='r' && strncmp(azArg[0],"rekey", n)==0 && nArg==4 ){
    char *zOld = p->zKey;
    if( zOld==0 ) zOld = "";
    if( strcmp(azArg[1],zOld) ){
      fprintf(stderr,"old key is incorrect\n");
    }else if( strcmp(azArg[2], azArg[3]) ){
      fprintf(stderr,"2nd copy of new key does not match the 1st\n");
    }else{
      sqlite_freemem(p->zKey);
      p->zKey = sqlite_mprintf("%s", azArg[2]);
      sqlite_rekey(p->db, p->zKey, strlen(p->zKey));
    }
  }else
#endif

  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
    struct callback_data data;
    char *zErrMsg = 0;
    open_db(p);
    memcpy(&data, p, sizeof(data));
    data.showHeader = 0;
    data.mode = MODE_Semi;
    if( nArg>1 ){
      extern int sqliteStrICmp(const char*,const char*);
      if( sqliteStrICmp(azArg[1],"sqlite_master")==0 ){
        char *new_argv[2], *new_colv[2];
        new_argv[0] = "CREATE TABLE sqlite_master (\n"
                      "  type text,\n"
                      "  name text,\n"
                      "  tbl_name text,\n"
                      "  rootpage integer,\n"
                      "  sql text\n"
                      ")";
        new_argv[1] = 0;
        new_colv[0] = "sql";
        new_colv[1] = 0;
        callback(&data, 1, new_argv, new_colv);
      }else if( sqliteStrICmp(azArg[1],"sqlite_temp_master")==0 ){
        char *new_argv[2], *new_colv[2];
        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
                      "  type text,\n"
                      "  name text,\n"
                      "  tbl_name text,\n"
                      "  rootpage integer,\n"
                      "  sql text\n"
                      ")";
        new_argv[1] = 0;
        new_colv[0] = "sql";
        new_colv[1] = 0;
        callback(&data, 1, new_argv, new_colv);
      }else{
        sqlite_exec_printf(p->db,
          "SELECT sql FROM "
          "  (SELECT * FROM sqlite_master UNION ALL"
          "   SELECT * FROM sqlite_temp_master) "
          "WHERE tbl_name LIKE '%q' AND type!='meta' AND sql NOTNULL "
          "ORDER BY substr(type,2,1), name",
          callback, &data, &zErrMsg, azArg[1]);
      }
    }else{
      sqlite_exec(p->db,
         "SELECT sql FROM "
         "  (SELECT * FROM sqlite_master UNION ALL"
         "   SELECT * FROM sqlite_temp_master) "
         "WHERE type!='meta' AND sql NOTNULL "
         "ORDER BY substr(type,2,1), name",
         callback, &data, &zErrMsg
      );
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite_freemem(zErrMsg);
    }
  }else

  if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
    sprintf(p->separator, "%.*s", (int)ArraySize(p->separator)-1, azArg[1]);
  }else

  if( c=='s' && strncmp(azArg[0], "show", n)==0){
    int i;
    fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
    fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
    fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
    fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
    fprintf(p->out,"%9.9s: %s\n","nullvalue", p->nullvalue);
    fprintf(p->out,"%9.9s: %s\n","output",
                                 strlen(p->outfile) ? p->outfile : "stdout");
    fprintf(p->out,"%9.9s: %s\n","separator", p->separator);
    fprintf(p->out,"%9.9s: ","width");
    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
        fprintf(p->out,"%d ",p->colWidth[i]);
    }
    fprintf(p->out,"\n\n");
  }else

  if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
    char **azResult;
    int nRow, rc;
    char *zErrMsg;
    open_db(p);
    if( nArg==1 ){
      rc = sqlite_get_table(p->db,
        "SELECT name FROM sqlite_master "
        "WHERE type IN ('table','view') "
        "UNION ALL "
        "SELECT name FROM sqlite_temp_master "
        "WHERE type IN ('table','view') "
        "ORDER BY 1",
        &azResult, &nRow, 0, &zErrMsg
      );
    }else{
      rc = sqlite_get_table_printf(p->db,
        "SELECT name FROM sqlite_master "
        "WHERE type IN ('table','view') AND name LIKE '%%%q%%' "
        "UNION ALL "
        "SELECT name FROM sqlite_temp_master "
        "WHERE type IN ('table','view') AND name LIKE '%%%q%%' "
        "ORDER BY 1",
        &azResult, &nRow, 0, &zErrMsg, azArg[1], azArg[1]
      );
    }
    if( zErrMsg ){
      fprintf(stderr,"Error: %s\n", zErrMsg);
      sqlite_freemem(zErrMsg);
    }
    if( rc==SQLITE_OK ){
      int len, maxlen = 0;
      int i, j;
      int nPrintCol, nPrintRow;
      for(i=1; i<=nRow; i++){
        if( azResult[i]==0 ) continue;
        len = strlen(azResult[i]);
        if( len>maxlen ) maxlen = len;
      }
      nPrintCol = 80/(maxlen+2);
      if( nPrintCol<1 ) nPrintCol = 1;
      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
      for(i=0; i<nPrintRow; i++){
        for(j=i+1; j<=nRow; j+=nPrintRow){
          char *zSp = j<=nPrintRow ? "" : "  ";
          printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
        }
        printf("\n");
      }
    }
    sqlite_free_table(azResult);
  }else

  if( c=='t' && n>1 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){
    open_db(p);
    sqlite_busy_timeout(p->db, atoi(azArg[1]));
  }else

  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
    int j;
    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
      p->colWidth[j-1] = atoi(azArg[j]);
    }
  }else

  {
    fprintf(stderr, "unknown command or invalid arguments: "
      " \"%s\". Enter \".help\" for help\n", azArg[0]);
  }

  return rc;
}