Esempio n. 1
0
void fakturadat::del(void) {
	if (id>=0) {
		sqlite_exec_printf(dbData, "DELETE FROM faktura WHERE id = %i", 0, 0, &dbErrMsg, id);
		sqlite_exec_printf(dbData, "DELETE FROM pozycjafakt WHERE fakturaid = %i", 0, 0, &dbErrMsg, id);
	}
	clear();
}
Esempio n. 2
0
void Budget::deleteBudget ( int budgetid )
  {
    if ( getNumberOfBudgets() != 0 )
      {
        QString tablename = "table";
        tablename.append ( QString::number ( budgetid ) );
        sqlite_exec_printf ( bdb, "delete from budgets where budgetid = %i;", 0, 0, 0, budgetid );
        sqlite_exec_printf ( bdb, "drop table '%q';", 0, 0, 0, ( const char* ) tablename );
      }
  }
Esempio n. 3
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 ] );
  }
Esempio n. 4
0
void firmadat::commit(void) {
	BString sql;
	int ret;
//printf("commit\n");
	if (id>=0) {	// UPDATE
		sql = "UPDATE firma SET ";
		sql += "nazwa = %Q, symbol = %Q, adres = %Q, kod = %Q, miejscowosc = %Q, telefon = %Q, email = %Q";
		sql += ", nip = %Q, regon = %Q, bank = %Q, konto = %Q";
		sql += ", odbiorca = %i, dostawca = %i, aktywny = %i, zablokowany = %i";
		sql += " WHERE id = %i";
	} else {		// INSERT
		id = generate_id();
		sql += "INSERT INTO firma ( ";
		sql += "nazwa, symbol, adres, kod, miejscowosc, telefon, email";
		sql += ", nip, regon, bank, konto";
		sql += ", odbiorca, dostawca, aktywny, zablokowany";
		sql += ", id ) VALUES ( ";
		sql += "%Q, %Q, %Q, %Q, %Q, %Q, %Q";
		sql += ", %Q, %Q, %Q, %Q";
		sql += ", %i, %i, %i, %i";
		sql += ", %i)";
	}
//printf("sql:[%s]\n",sql.String());
	ret = sqlite_exec_printf(dbData, sql.String(), 0, 0, &dbErrMsg,
		data[0].String(), data[1].String(), data[2].String(), data[3].String(),
		data[4].String(), data[5].String(), data[6].String(), data[7].String(),
		data[8].String(), data[9].String(), data[10].String(),
		odbiorca, dostawca, aktywny, zablokowany,
		id);
//printf("result: %i, %s; id=%i\n", ret, dbErrMsg, id);
}
Esempio n. 5
0
/*
** Usage:  sqlite_exec_printf  DB  FORMAT  STRING
**
** Invoke the sqlite_exec_printf() interface using the open database
** DB.  The SQL is the string FORMAT.  The format string should contain
** one %s or %q.  STRING is the value inserted into %s or %q.
*/
static int test_exec_printf(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite *db;
  Tcl_DString str;
  int rc;
  char *zErr = 0;
  char zBuf[30];
  if( argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB FORMAT STRING", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  Tcl_DStringInit(&str);
  rc = sqlite_exec_printf(db, argv[2], exec_printf_cb, &str, &zErr, argv[3]);
  sprintf(zBuf, "%d", rc);
  Tcl_AppendElement(interp, zBuf);
  Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
  Tcl_DStringFree(&str);
  if( zErr ) free(zErr);
  return TCL_OK;
}
Esempio n. 6
0
int Budget::addLineItem ( int budgetid, QString lineitemname, float lineitemamount, int lineitemtype )
  {
    QString tablename = "table";
    tablename.append ( QString::number ( budgetid ) );
    sqlite_exec_printf ( bdb, "insert into '%q' values ( '%q', %.2f, %i, NULL );", 0, 0, 0, ( const char* ) tablename, ( const char* ) lineitemname, lineitemamount, lineitemtype );
    char **results;
    sqlite_get_table_printf ( bdb, "select last_insert_rowid() from '%q';", &results, NULL, NULL, NULL, ( const char* ) tablename );
    return atoi ( results [ 1 ] );
  }
Esempio n. 7
0
void pozfaklist::commit(int fakturaid) {
	int ret;
	/// remove all existing and insert new? convenient!
	ret = sqlite_exec_printf(dbData, "DELETE FROM pozycjafakt WHERE fakturaid = %i", 0, 0, &dbErrMsg, fakturaid);
//printf("result: %i, %s;\n", ret, dbErrMsg);

	// iterate through list, commit items
	pozfakitem *cur = start;
	while (cur!=NULL) {
		commititem(fakturaid, cur);
		cur = cur->nxt;
	}
}
Esempio n. 8
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 );
  }
Esempio n. 9
0
static int ast_db_sqliteput(char *family, char *key, char *value)
{
	int res = 0;
	char *zErr = 0;
	ast_mutex_lock(&sqlite_lock);
	res=sqlite_exec_printf(db, "DELETE FROM astdb WHERE astfamily='%q' AND astkey='%q'", NULL, NULL, &zErr, family, key);
	if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
		usleep(200);
	if (zErr) {
		ast_log(LOG_ERROR, "sqliteput: %s\n", zErr);
		free(zErr);
	}
	res=sqlite_exec_printf(db, "INSERT INTO astdb (astfamily,astkey,astvalue) VALUES ('%q','%q','%q')", NULL, NULL, &zErr, family, key, value);
	if (res != SQLITE_BUSY && res != SQLITE_LOCKED) {
		usleep(200);
	}
	if (zErr) {
		ast_log(LOG_ERROR, "sqliteput: %s\n", zErr);
		free(zErr);
	}
	ast_mutex_unlock(&sqlite_lock);
	return res;
}
Esempio n. 10
0
static int ast_db_sqlitedeltree(char *family, char *keytree)
{
	int res = 0;
	char *zErr = 0;
	ast_mutex_lock(&sqlite_lock);
	res=sqlite_exec_printf(db, "DELETE FROM astdb WHERE astfamily='%q'", NULL, NULL, &zErr, family);
	if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
		usleep(200);
	if (zErr) {
		ast_log(LOG_ERROR, "sqlitedeltree: %s\n", zErr);
		free(zErr);
	}
	ast_mutex_unlock(&sqlite_lock);
	return res;
}
Esempio n. 11
0
static int ast_db_sqliteget(char *family, char *key, char *value, int valuelen)
{
	int res = 0;
        char *zErr = 0;
        ast_mutex_lock(&sqlite_lock);
        res=sqlite_exec_printf(db, "SELECT DISTINCT astvalue FROM astdb WHERE astfamily='%q' AND astkey='%q' LIMIT 1", NULL, NULL, &zErr, family, key);
if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
	if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
        	usleep(200);
        if (zErr) {
                ast_log(LOG_ERROR, "sqliteget: %s\n", zErr);
                free(zErr);
        }
        ast_mutex_unlock(&sqlite_lock);
        return res;
}
Esempio n. 12
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;
	}
}
Esempio n. 13
0
/*
** This is a different callback routine used for dumping the database.
** Each row received by this callback consists of a table name,
** the table type ("index" or "table") and SQL to create the table.
** This routine should print text sufficient to recreate the table.
*/
static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  struct callback_data *p = (struct callback_data *)pArg;
  if( nArg!=3 ) return 1;
  fprintf(p->out, "%s;\n", azArg[2]);
  if( strcmp(azArg[1],"table")==0 ){
    struct callback_data d2;
    d2 = *p;
    d2.mode = MODE_Insert;
    d2.zDestTable = 0;
    set_table_name(&d2, azArg[0]);
    sqlite_exec_printf(p->db,
       "SELECT * FROM '%q'",
       callback, &d2, 0, azArg[0]
    );
    set_table_name(&d2, 0);
  }
  return 0;
}
Esempio n. 14
0
const char *pozfaklist::calcSumPayment(void) {
	static BString result;
	int ret;

	execSQL("CREATE TEMPORARY TABLE sumpayment ( cbrutto )");

	pozfakitem *cur = start;

	while (cur!=NULL) {
		ret = sqlite_exec_printf(dbData,
		"INSERT INTO sumpayment (cbrutto) VALUES (%Q);",
		0, 0, &dbErrMsg, cur->data->data[10].String() );
		cur = cur->nxt;
	}
	result = execSQL("SELECT DECROUND(SUM(cbrutto)) FROM sumpayment");
	execSQL("DROP TABLE sumpayment");
	return result.String();
}
Esempio n. 15
0
void fakturadat::commit(void) {
//printf("in commit with %i\n",id);
	BString sql;
	int ret;
	if (id>=0) {	// UPDATE
		sql = "UPDATE faktura SET ";
		sql += "nazwa = %Q";
		sql += ", miejsce_wystawienia = %Q, wystawil = %Q, data_wystawienia = %Q, data_sprzedazy = %Q";
		sql += ", srodek_transportu = %Q, sposob_zaplaty = %Q, termin_zaplaty = %Q",
		sql += ", zapl_kwota = %Q, zapl_dnia = %Q, uwagi = %Q";
		sql += ", onazwa = %Q, oadres = %Q, okod = %Q, omiejscowosc = %Q, otelefon = %Q, oemail = %Q";
		sql += ", onip = %Q, oregon = %Q, obank = %Q, okonto = %Q";
		sql += " WHERE id = %i";
	} else {		// INSERT
		id = generate_id();
		sql += "INSERT INTO faktura ( ";
		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 += ", id ) VALUES ( ";
		sql += "%Q";
		sql += ", %Q, %Q, %Q, %Q";
		sql += ", %Q, %Q, %Q";
		sql += ", %Q, %Q, %Q";
		sql += ", %Q, %Q, %Q, %Q, %Q, %Q";
		sql += ", %Q, %Q, %Q, %Q";
		sql += ", %i)";
	}
//printf("sql:[%s]\n",sql.String());
	ret = sqlite_exec_printf(dbData, sql.String(), 0, 0, &dbErrMsg,
		nazwa.String(), ogol[0].String(), ogol[1].String(), ogol[2].String(), ogol[3].String(),
		ogol[4].String(), ogol[5].String(), ogol[6].String(),
		ogol[8].String(), ogol[9].String(), uwagi.String(),
		odata[0].String(), odata[2].String(), odata[3].String(), odata[4].String(), odata[5].String(), odata[6].String(),
		odata[7].String(), odata[8].String(), odata[9].String(), odata[10].String(),
		id);
//printf("result: %i, %s; id=%i\n", ret, dbErrMsg, id);
}
Esempio n. 16
0
void pozfaklist::commititem(int fakturaid, pozfakitem *item) {
	BString sql;
	pozfakdata *data = item->data;
	int ret, id;
	/// XXX really INSERT only?
	id = generate_id();
	sql = "INSERT INTO pozycjafakt ( ";
	sql += "id, lp, ilosc";
	sql += ", nazwa, pkwiu, jm, vatid, netto, rabat";
	sql += ", fakturaid ) VALUES ( ";
	sql += "%i, %i, %Q";
	sql += ", %Q, %Q, %Q, %i, %Q, %Q";
	sql += ", %i )";
//printf("commit for %i #%i\n", id, fakturaid);
//printf("sql:[%s]\n",sql.String());
	ret = sqlite_exec_printf(dbData, sql.String(), 0, 0, &dbErrMsg,
		id, item->lp, data->data[3].String(),
		data->data[1].String(), data->data[2].String(), data->data[4].String(), data->vatid, data->data[11].String(), data->data[5].String(),
		fakturaid
	);
//printf("result: %i, %s; id=%i\n", ret, dbErrMsg, id);
}
static void do_some_sql(int parent){
  char *zErr;
  int rc = SQLITE_OK;
  sqlite *db;
  int cnt = 0;
  static char zBig[] = 
    "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  if( access("./test.db-journal",0)==0 ){
    /*printf("pid %d: journal exists.  rollback will be required\n",getpid());*/    unlink("test.db-saved");
    system("cp test.db test.db-saved");
    unlink("test.db-journal-saved");
    system("cp test.db-journal test.db-journal-saved");
  }
  db = sqlite_open("./test.db", 0, &zErr);
  if( db==0 ){
    printf("ERROR: %s\n", zErr);
    if( strcmp(zErr,"database disk image is malformed")==0 ){
      kill(parent, SIGKILL);
    }
    exit(1);
  }
  srand(getpid());
  while( rc==SQLITE_OK ){
    cnt++;
    rc = sqlite_exec_printf(db, 
       "INSERT INTO t1 VALUES(%d,'%d%s')", 0, 0, &zErr,
       rand(), rand(), zBig);
  }
  if( rc!=SQLITE_OK ){
    printf("ERROR #%d: %s\n", rc, zErr);
    if( rc==SQLITE_CORRUPT ){
      kill(parent, SIGKILL);
    }
  }
  printf("pid %d: cnt=%d\n", getpid(), cnt);
}
Esempio n. 18
0
/*
** This is a callback procedure used to reconstruct a table.  The
** name of the table to be reconstructed is passed in as argv[0].
**
** This routine is used to automatically upgrade a database from
** format version 1 or 2 to version 3.  The correct operation of
** this routine relys on the fact that no indices are used when
** copying a table out to a temporary file.
**
** The change from version 2 to version 3 occurred between SQLite
** version 2.5.6 and 2.6.0 on 2002-July-18.  
*/
static
int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
  InitData *pData = (InitData*)pInit;
  int rc;
  Table *pTab;
  Trigger *pTrig;
  char *zErr = 0;

  pTab = sqliteFindTable(pData->db, argv[0], 0);
  assert( pTab!=0 );
  assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
  if( pTab ){
    pTrig = pTab->pTrigger;
    pTab->pTrigger = 0;  /* Disable all triggers before rebuilding the table */
  }
  rc = sqlite_exec_printf(pData->db,
    "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
    "DELETE FROM '%q'; "
    "INSERT INTO '%q' SELECT * FROM sqlite_x; "
    "DROP TABLE sqlite_x;",
    0, 0, &zErr, argv[0], argv[0], argv[0]);
  if( zErr ){
    if( *pData->pzErrMsg ) sqlite_freemem(*pData->pzErrMsg);
    *pData->pzErrMsg = zErr;
  }

  /* If an error occurred in the SQL above, then the transaction will
  ** rollback which will delete the internal symbol tables.  This will
  ** cause the structure that pTab points to be deleted.  In case that
  ** happened, we need to refetch pTab.
  */
  pTab = sqliteFindTable(pData->db, argv[0], 0);
  if( pTab ){
    assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
    pTab->pTrigger = pTrig;  /* Re-enable triggers */
  }
  return rc!=SQLITE_OK;
}
Esempio n. 19
0
void towardat::commit(void) {
	BString sql;
	int ret;
//printf("commit\n");
	if (id>=0) {	// UPDATE
		sql = "UPDATE towar SET ";
		sql += "nazwa = %Q, symbol = %Q, pkwiu = %Q, jm = %Q";
		sql += ", usluga = %i, dodany = date('now'), notatki = %Q, vatid = %i";
		sql += ", netto = %Q, zakupu = %Q, marza = %Q, rabat = %Q, kurs = %Q, clo = %Q";
		sql += ", magazyn = %Q, magzmiana = date('now')";
		sql += " WHERE id = %i";
	} else {		// INSERT
		id = generate_id();
		sql += "INSERT INTO towar ( ";
		sql += "nazwa, symbol, pkwiu, jm";
		sql += ", usluga, dodany, notatki, vatid";
		sql += ", netto, zakupu, marza, rabat";
		sql += ", kurs, clo";
		sql += ", magazyn, magzmiana";
		sql += ", id ) VALUES ( ";
		sql += "%Q, %Q, %Q, %Q";
		sql += ", %i, date('now'), %Q, %i";
		sql += ", %Q, %Q, %Q, %Q";
		sql += ", %Q, %Q";
		sql += ", %Q, date('now')";
		sql += ", %i)";
	}
//printf("sql:[%s]\n",sql.String());
	ret = sqlite_exec_printf(dbData, sql.String(), 0, 0, &dbErrMsg,
		data[0].String(), data[1].String(), data[2].String(), data[3].String(),
		usluga, notatki.String(), vatid,
		ceny[0].String(), ceny[1].String(), ceny[2].String(), ceny[3].String(),
		ceny[4].String(), ceny[5].String(),
		magazyn.String(),
		id);
//printf("result: %i, %s; id=%i\n", ret, dbErrMsg, id);
}
Esempio n. 20
0
void firmadat::del(void) {
	if (id>=0) {
		sqlite_exec_printf(dbData, "DELETE FROM firma WHERE id = %i", 0, 0, &dbErrMsg, id);
	}
	clear();
}
Esempio n. 21
0
void Budget::deleteLineItem ( int budgetid, int lineitemid )
  {
    QString tablename = "table";
    tablename.append ( QString::number ( budgetid ) );
   sqlite_exec_printf ( bdb, "delete from '%q' where lineitemid = %i;", 0, 0, 0, ( const char * ) tablename, lineitemid );
  }
Esempio n. 22
0
void Budget::updateBudget ( QString name, QString description, QString currency, int budgetid )
  {
    sqlite_exec_printf ( bdb, "update budgets set name = '%q', description = '%q', currency = '%q' where budgetid = %i;", 0, 0, 0, ( const char * ) name, ( const char * ) description, ( const char * ) currency, budgetid );
  }
Esempio n. 23
0
void Transfer::setCleared ( int id, int cleared )
  {
    sqlite_exec_printf ( db, "update transfers set cleared = %i where transferid = %i;", 0, 0, 0, cleared, id );
  }
Esempio n. 24
0
void Transfer::updateTransfer ( int fromaccount, int fromparent, int toaccount, int toparent, int day, int month, int year, float amount, int cleared, int transferid )
  {
    sqlite_exec_printf ( db, "update transfers set fromaccount = %i, fromparent = %i, toaccount = %i, toparent = %i, day = %i, month = %i, year = %i,"
     "amount = %.2f, cleared = %i where transferid = %i;", 0, 0, 0, fromaccount, fromparent, toaccount, toparent, day, month, year, amount, cleared, transferid );
  }
Esempio n. 25
0
void Transfer::deleteTransfer ( int transferid )
  {
    sqlite_exec_printf ( db, "delete from transfers where transferid = %i;", 0, 0, 0, transferid );
  }
Esempio n. 26
0
void Transfer::deleteAllTransfers ( int accountid )
  {
    sqlite_exec_printf ( db, "delete from transfers where fromaccount = %i;", 0, 0, 0, accountid );
    sqlite_exec_printf ( db, "delete from transfers where toaccount = %i;", 0, 0, 0, accountid );
  }
Esempio n. 27
0
static int sqlite_log(struct ast_cdr *cdr)
{
	int res = 0;
	char *zErr = 0;
	struct tm tm;
	time_t t;
	char startstr[80], answerstr[80], endstr[80];
	int count;

	ast_mutex_lock(&sqlite_lock);

	t = cdr->start.tv_sec;
	localtime_r(&t, &tm);
	strftime(startstr, sizeof(startstr), DATE_FORMAT, &tm);

	t = cdr->answer.tv_sec;
	localtime_r(&t, &tm);
	strftime(answerstr, sizeof(answerstr), DATE_FORMAT, &tm);

	t = cdr->end.tv_sec;
	localtime_r(&t, &tm);
	strftime(endstr, sizeof(endstr), DATE_FORMAT, &tm);

	for(count=0; count<5; count++) {
		res = sqlite_exec_printf(db,
			"INSERT INTO cdr ("
				"clid,src,dst,dcontext,"
				"channel,dstchannel,lastapp,lastdata, "
				"start,answer,end,"
				"duration,billsec,disposition,amaflags, "
				"accountcode"
#				if LOG_UNIQUEID
				",uniqueid"
#				endif
#				if LOG_USERFIELD
				",userfield"
#				endif
			") VALUES ("
				"'%q', '%q', '%q', '%q', "
				"'%q', '%q', '%q', '%q', "
				"'%q', '%q', '%q', "
				"%d, %d, %d, %d, "
				"'%q'"
#				if LOG_UNIQUEID
				",'%q'"
#				endif
#				if LOG_USERFIELD
				",'%q'"
#				endif
			")", NULL, NULL, &zErr,
				cdr->clid, cdr->src, cdr->dst, cdr->dcontext,
				cdr->channel, cdr->dstchannel, cdr->lastapp, cdr->lastdata,
				startstr, answerstr, endstr,
				cdr->duration, cdr->billsec, cdr->disposition, cdr->amaflags,
				cdr->accountcode
#				if LOG_UNIQUEID
				,cdr->uniqueid
#				endif
#				if LOG_USERFIELD
				,cdr->userfield
#				endif
			);
		if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
			break;
		usleep(200);
	}
	
	if (zErr) {
		ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
		free(zErr);
	}

	ast_mutex_unlock(&sqlite_lock);
	return res;
}
Esempio n. 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;
}
Esempio n. 29
0
void Budget::updateLineItem ( QString lineitemname, float lineitemamount, int lineitemtype, int budgetid, int lineitemid )
  {
    QString tablename = "table";
    tablename.append ( QString::number ( budgetid ) );
    sqlite_exec_printf ( bdb, "update '%q' set name = '%q', lineitemamount = %f, type = %i where lineitemid = %i;", 0, 0, 0, ( const char* ) tablename, ( const char * ) lineitemname, lineitemamount, lineitemtype, lineitemid );
  }
Esempio n. 30
0
static int sqlite_log(struct ast_cdr *cdr)
{
	int res = 0;
	char *zErr = 0;
	char startstr[80], answerstr[80], endstr[80];
	int count;
#if LOG_HRTIME
	double hrbillsec = 0.0;
	double hrduration;
#endif

	ast_mutex_lock(&sqlite_lock);

	format_date(startstr, sizeof(startstr), &cdr->start);
	format_date(answerstr, sizeof(answerstr), &cdr->answer);
	format_date(endstr, sizeof(endstr), &cdr->end);

#if LOG_HRTIME
	if (!ast_tvzero(cdr->answer)) {
		hrbillsec = (double) ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0;
	}
	hrduration = (double) ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0;
#endif

	for(count=0; count<5; count++) {
		res = sqlite_exec_printf(db,
			"INSERT INTO cdr ("
				"clid,src,dst,dcontext,"
				"channel,dstchannel,lastapp,lastdata, "
				"start,answer,end,"
				"duration,billsec,disposition,amaflags, "
				"accountcode"
#				if LOG_UNIQUEID
				",uniqueid"
#				endif
#				if LOG_USERFIELD
				",userfield"
#				endif
			") VALUES ("
				"'%q', '%q', '%q', '%q', "
				"'%q', '%q', '%q', '%q', "
				"'%q', '%q', '%q', "
#if LOG_HRTIME
				"%f, %f, %d, %d, "
#else
				"%d, %d, %d, %d, "
#endif
				"'%q'"
#				if LOG_UNIQUEID
				",'%q'"
#				endif
#				if LOG_USERFIELD
				",'%q'"
#				endif
			")", NULL, NULL, &zErr,
				cdr->clid, cdr->src, cdr->dst, cdr->dcontext,
				cdr->channel, cdr->dstchannel, cdr->lastapp, cdr->lastdata,
				startstr, answerstr, endstr,
#if LOG_HRTIME
				hrduration, hrbillsec, cdr->disposition, cdr->amaflags,
#else
				cdr->duration, cdr->billsec, cdr->disposition, cdr->amaflags,
#endif
				cdr->accountcode
#				if LOG_UNIQUEID
				,cdr->uniqueid
#				endif
#				if LOG_USERFIELD
				,cdr->userfield
#				endif
			);
		if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
			break;
		usleep(200);
	}

	if (zErr) {
		ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
		ast_free(zErr);
	}

	ast_mutex_unlock(&sqlite_lock);
	return res;
}