Example #1
0
int
main(int argc, char *argv[])
{
    char *sql;
    int res;
    char *errmsg = NULL;
    char *porigin, *zonefile;
    dns_fixedname_t forigin, fname;
    dns_name_t *origin, *name;
    dns_db_t *db = NULL;
    dns_dbiterator_t *dbiter;
    dns_dbnode_t *node;
    dns_rdatasetiter_t *rdsiter;
    dns_rdataset_t rdataset;
    dns_rdata_t rdata = DNS_RDATA_INIT;
    isc_mem_t *mctx = NULL;
    isc_entropy_t *ectx = NULL;
    isc_buffer_t b;
    isc_result_t result;

    if (argc != 5) {
	printf("usage: %s <zone> <zonefile> <dbfile> <dbtable>\n", argv[0]);
	exit(1);
    }
    
    porigin  = argv[1];
    zonefile = argv[2];

    dbi.filename = argv[3];
    dbi.table    = argv[4];
    
    dns_result_register();
    
    result = isc_mem_create(0, 0, &mctx);
    check_result(result, "isc_mem_create");
    result = isc_entropy_create(mctx, &ectx);
    check_result(result, "isc_entropy_create");
    result = isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE);
    check_result(result, "isc_hash_create");
    
    isc_buffer_init(&b, porigin, strlen(porigin));
    isc_buffer_add(&b, strlen(porigin));
    dns_fixedname_init(&forigin);
    origin = dns_fixedname_name(&forigin);
    result = dns_name_fromtext(origin, &b, dns_rootname, 0, NULL);
    check_result(result, "dns_name_fromtext");
    
    db = NULL;
    result = dns_db_create(mctx, "rbt", origin, dns_dbtype_zone,
			   dns_rdataclass_in, 0, NULL, &db);
    check_result(result, "dns_db_create");
    
    result = dns_db_load(db, zonefile);
    if (result == DNS_R_SEENINCLUDE)
	result = ISC_R_SUCCESS;
    check_result(result, "dns_db_load");

    printf("Connecting to '%s'\n", dbi.filename);
    
    if ((result = db_connect(&dbi)) != ISC_R_SUCCESS) {
	fprintf(stderr, "Connection to database '%s' failed\n",
		dbi.filename);
	closeandexit(1);
    }
    
    sql = sqlite3_mprintf("DROP TABLE %q ", dbi.table);
    printf("%s\n", sql);
    res = sqlite3_exec(dbi.db, sql, NULL, NULL, &errmsg);
    sqlite3_free(sql);
#if 0
    if (res != SQLITE_OK) {
	fprintf(stderr, "DROP TABLE %s failed: %s\n",
		dbi.table, errmsg);
    }
#endif

#if 0    
    sql = sqlite3_mprintf(sql, "BEGIN TRANSACTION");
    printf("%s\n", sql);
    res = sqlite3_exec(dbi.db, sql, NULL, NULL, &errmsg);
    sqlite3_free(sql);
    if (res != SQLITE_OK) {
	fprintf(stderr, "BEGIN TRANSACTION failed: %s\n", errmsg);
	closeandexit(1);
    }
#endif
    
    sql = sqlite3_mprintf(
	"CREATE TABLE %q "
	"(NAME TEXT, TTL INTEGER, RDTYPE TEXT, RDATA TEXT) ",
	dbi.table);
    printf("%s\n", sql);
    res = sqlite3_exec(dbi.db, sql, NULL, NULL, &errmsg);
    sqlite3_free(sql);
    if (res != SQLITE_OK) {
	fprintf(stderr, "CREATE TABLE %s failed: %s\n",
		dbi.table, errmsg);
	closeandexit(1);
    }
    
    dbiter = NULL;
    result = dns_db_createiterator(db, 0, &dbiter);
    check_result(result, "dns_db_createiterator()");
    
    result = dns_dbiterator_first(dbiter);
    check_result(result, "dns_dbiterator_first");
    
    dns_fixedname_init(&fname);
    name = dns_fixedname_name(&fname);
    dns_rdataset_init(&rdataset);
    dns_rdata_init(&rdata);
    
    while (result == ISC_R_SUCCESS) {
	node = NULL;
	result = dns_dbiterator_current(dbiter, &node, name);
	if (result == ISC_R_NOMORE)
	    break;
	check_result(result, "dns_dbiterator_current");
	
	rdsiter = NULL;
	result = dns_db_allrdatasets(db, node, NULL, 0, &rdsiter);
	check_result(result, "dns_db_allrdatasets");

	result = dns_rdatasetiter_first(rdsiter);

	while (result == ISC_R_SUCCESS) {
	    dns_rdatasetiter_current(rdsiter, &rdataset);
	    result = dns_rdataset_first(&rdataset);
	    check_result(result, "dns_rdataset_first");
	    while (result == ISC_R_SUCCESS) {
		dns_rdataset_current(&rdataset, &rdata);
		addrdata(name, rdataset.ttl, &rdata);
		dns_rdata_reset(&rdata);
		result = dns_rdataset_next(&rdataset);
	    }
	    dns_rdataset_disassociate(&rdataset);
	    result = dns_rdatasetiter_next(rdsiter);
	}
	dns_rdatasetiter_destroy(&rdsiter);
	dns_db_detachnode(db, &node);
	result = dns_dbiterator_next(dbiter);
    }

#if 0
    sql = sqlite3_mprintf(sql, "COMMIT TRANSACTION ");
    printf("%s\n", sql);
    res = sqlite3_exec(dbi.db, sql, NULL, NULL, &errmsg);
    sqlite3_free(sql);
    if (res != SQLITE_OK) {
	fprintf(stderr, "COMMIT TRANSACTION failed: %s\n", errmsg);
	closeandexit(1);
    }
#endif
    
    dns_dbiterator_destroy(&dbiter);
    dns_db_detach(&db);
    isc_hash_destroy();
    isc_entropy_detach(&ectx);
    isc_mem_destroy(&mctx);

    closeandexit(0);

    exit(0);
}
static
void OGR2SQLITE_ogr_datasource_load_layers(sqlite3_context* pContext,
                                           int argc, sqlite3_value** argv)
{
    sqlite3* hDB = (sqlite3*) sqlite3_user_data(pContext);

    if( (argc < 1 || argc > 3) || sqlite3_value_type (argv[0]) != SQLITE_TEXT )
    {
        sqlite3_result_int (pContext, 0);
        return;
    }
    const char* pszDataSource = (const char*) sqlite3_value_text(argv[0]);

    int bUpdate = FALSE;
    if( argc >= 2 )
    {
        if( sqlite3_value_type(argv[1]) != SQLITE_INTEGER )
        {
            sqlite3_result_int (pContext, 0);
            return;
        }
        bUpdate = sqlite3_value_int(argv[1]);
    }

    const char* pszPrefix = NULL;
    if( argc >= 3 )
    {
        if( sqlite3_value_type(argv[2]) != SQLITE_TEXT )
        {
            sqlite3_result_int (pContext, 0);
            return;
        }
        pszPrefix = (const char*) sqlite3_value_text(argv[2]);
    }

    OGRDataSource* poDS = (OGRDataSource*)OGROpenShared(pszDataSource, bUpdate, NULL);
    if( poDS == NULL )
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s", pszDataSource);
        sqlite3_result_int (pContext, 0);
        return;
    }

    CPLString osEscapedDataSource = OGRSQLiteEscape(pszDataSource);
    for(int i=0;i<poDS->GetLayerCount();i++)
    {
        const char* pszLayerName = poDS->GetLayer(i)->GetName();
        CPLString osEscapedLayerName = OGRSQLiteEscape(pszLayerName);
        CPLString osTableName;
        if( pszPrefix != NULL )
        {
            osTableName = pszPrefix;
            osTableName += "_";
            osTableName += OGRSQLiteEscapeName(pszLayerName);
        }
        else
        {
            osTableName = OGRSQLiteEscapeName(pszLayerName);
        }

        char* pszErrMsg = NULL;
        if( sqlite3_exec(hDB, CPLSPrintf(
            "CREATE VIRTUAL TABLE \"%s\" USING VirtualOGR('%s', %d, '%s')",
                osTableName.c_str(),
                osEscapedDataSource.c_str(),
                bUpdate,
                osEscapedLayerName.c_str()),
            NULL, NULL, &pszErrMsg) != SQLITE_OK )
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Cannot create table \"%s\" : %s",
                     osTableName.c_str(), pszErrMsg);
            sqlite3_free(pszErrMsg);
        }
    }

    poDS->Release();
    sqlite3_result_int (pContext, 1);
}
/*
** Finished with one layer of the tree
*/
static void sqlite3TreeViewPop(TreeView *p){
  if( p==0 ) return;
  p->iLevel--;
  if( p->iLevel<0 ) sqlite3_free(p);
}
Example #4
0
/*
** Prepare to begin tokenizing a particular string.  The input
** string to be tokenized is pInput[0..nBytes-1].  A cursor
** used to incrementally tokenize this string is returned in 
** *ppCursor.
*/
static int icuOpen(
  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
  const char *zInput,                    /* Input string */
  int nInput,                            /* Length of zInput in bytes */
  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
){
  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  IcuCursor *pCsr;

  const int32_t opt = U_FOLD_CASE_DEFAULT;
  UErrorCode status = U_ZERO_ERROR;
  int nChar;

  UChar32 c;
  int iInput = 0;
  int iOut = 0;

  *ppCursor = 0;

  if( nInput<0 ){
    nInput = strlen(zInput);
  }
  nChar = nInput+1;
  pCsr = (IcuCursor *)sqlite3_malloc(
      sizeof(IcuCursor) +                /* IcuCursor */
      (nChar+1) * sizeof(int) +          /* IcuCursor.aOffset[] */
      nChar * sizeof(UChar)              /* IcuCursor.aChar[] */
  );
  if( !pCsr ){
    return SQLITE_NOMEM;
  }
  memset(pCsr, 0, sizeof(IcuCursor));
  pCsr->aOffset = (int *)&pCsr[1];
  pCsr->aChar = (UChar *)&pCsr->aOffset[nChar+1];

  pCsr->aOffset[iOut] = iInput;
  U8_NEXT(zInput, iInput, nInput, c); 
  while( c>0 ){
    int isError = 0;
    c = u_foldCase(c, opt);
    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
    if( isError ){
      sqlite3_free(pCsr);
      return SQLITE_ERROR;
    }
    pCsr->aOffset[iOut] = iInput;

    if( iInput<nInput ){
      U8_NEXT(zInput, iInput, nInput, c);
    }else{
      c = 0;
    }
  }

  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  if( !U_SUCCESS(status) ){
    sqlite3_free(pCsr);
    return SQLITE_ERROR;
  }
  pCsr->nChar = iOut;

  ubrk_first(pCsr->pIter);
  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  return SQLITE_OK;
}
Example #5
0
/**
 * This function is invoked as:
 *
 *  _TOKENIZE('<token_table>', <data_row_id>, <data>, <delimiter>,
 *             <use_token_index>, <data_tag>)
 *
 * If <use_token_index> is omitted, it is treated as 0.
 * If <data_tag> is omitted, it is treated as NULL.
 *
 * It will split <data> on each instance of <delimiter> and insert each token
 * into <token_table>. The following columns in <token_table> are used:
 * token TEXT, source INTEGER, token_index INTEGER, tag (any type)
 * The token_index column is not required if <use_token_index> is 0.
 * The tag column is not required if <data_tag> is NULL.
 *
 * One row is inserted for each token in <data>.
 * In each inserted row, 'source' is <data_row_id>.
 * In the first inserted row, 'token' is the hex collation key of
 * the entire <data> string, and 'token_index' is 0.
 * In each row I (where 1 <= I < N, and N is the number of tokens in <data>)
 * 'token' will be set to the hex collation key of the I:th token (0-based).
 * If <use_token_index> != 0, 'token_index' is set to I.
 * If <data_tag> is not NULL, 'tag' is set to <data_tag>.
 *
 * In other words, there will be one row for the entire string,
 * and one row for each token except the first one.
 *
 * The function returns the number of tokens generated.
 */
static void tokenize(sqlite3_context * context, int argc, sqlite3_value ** argv)
{
    //ALOGD("enter tokenize");
    int err;
    int useTokenIndex = 0;
    int useDataTag = 0;

    if (!(argc >= 4 || argc <= 6)) {
        ALOGE("Tokenize requires 4 to 6 arguments");
        sqlite3_result_null(context);
        return;
    }

    if (argc > 4) {
        useTokenIndex = sqlite3_value_int(argv[4]);
    }

    if (argc > 5) {
        useDataTag = (sqlite3_value_type(argv[5]) != SQLITE_NULL);
    }

    sqlite3 * handle = sqlite3_context_db_handle(context);
    UCollator* collator = (UCollator*)sqlite3_user_data(context);
    char const * tokenTable = (char const *)sqlite3_value_text(argv[0]);
    if (tokenTable == NULL) {
        ALOGE("tokenTable null");
        sqlite3_result_null(context);
        return;
    }

    // Get or create the prepared statement for the insertions
    sqlite3_stmt * statement = (sqlite3_stmt *)sqlite3_get_auxdata(context, 0);
    if (!statement) {
        char const * tokenIndexCol = useTokenIndex ? ", token_index" : "";
        char const * tokenIndexParam = useTokenIndex ? ", ?" : "";
        char const * dataTagCol = useDataTag ? ", tag" : "";
        char const * dataTagParam = useDataTag ? ", ?" : "";
        char * sql = sqlite3_mprintf("INSERT INTO %s (token, source%s%s) VALUES (?, ?%s%s);",
                tokenTable, tokenIndexCol, dataTagCol, tokenIndexParam, dataTagParam);
        err = sqlite3_prepare_v2(handle, sql, -1, &statement, NULL);
        sqlite3_free(sql);
        if (err) {
            ALOGE("prepare failed");
            sqlite3_result_null(context);
            return;
        }
        // This binds the statement to the table it was compiled against, which is argv[0].
        // If this function is ever called with a different table the finalizer will be called
        // and sqlite3_get_auxdata() will return null above, forcing a recompile for the new table.
        sqlite3_set_auxdata(context, 0, statement, tokenize_auxdata_delete);
    } else {
        // Reset the cached statement so that binding the row ID will work properly
        sqlite3_reset(statement);
    }

    // Bind the row ID of the source row
    int64_t rowID = sqlite3_value_int64(argv[1]);
    err = sqlite3_bind_int64(statement, 2, rowID);
    if (err != SQLITE_OK) {
        ALOGE("bind failed");
        sqlite3_result_null(context);
        return;
    }

    // Bind <data_tag> to the tag column
    if (useDataTag) {
        int dataTagParamIndex = useTokenIndex ? 4 : 3;
        err = sqlite3_bind_value(statement, dataTagParamIndex, argv[5]);
        if (err != SQLITE_OK) {
            ALOGE("bind failed");
            sqlite3_result_null(context);
            return;
        }
    }

    // Get the raw bytes for the string to tokenize
    // the string will be modified by following code
    // however, sqlite did not reuse the string, so it is safe to not dup it
    UChar * origData = (UChar *)sqlite3_value_text16(argv[2]);
    if (origData == NULL) {
        sqlite3_result_null(context);
        return;
    }

    // Get the raw bytes for the delimiter
    const UChar * delim = (const UChar *)sqlite3_value_text16(argv[3]);
    if (delim == NULL) {
        ALOGE("can't get delimiter");
        sqlite3_result_null(context);
        return;
    }

    UChar * token = NULL;
    UChar *state;
    int numTokens = 0;

    do {
        if (numTokens == 0) {
            token = origData;
        }

        // Reset the program so we can use it to perform the insert
        sqlite3_reset(statement);
        UErrorCode status = U_ZERO_ERROR;
        char keybuf[1024];
        uint32_t result = ucol_getSortKey(collator, token, -1, (uint8_t*)keybuf, sizeof(keybuf)-1);
        if (result > sizeof(keybuf)) {
            // TODO allocate memory for this super big string
            ALOGE("ucol_getSortKey needs bigger buffer %d", result);
            break;
        }
        uint32_t keysize = result-1;
        uint32_t base16Size = keysize*2;
        char *base16buf = (char*)malloc(base16Size);
        base16Encode(base16buf, keybuf, keysize);
        err = sqlite3_bind_text(statement, 1, base16buf, base16Size, SQLITE_STATIC);

        if (err != SQLITE_OK) {
            ALOGE(" sqlite3_bind_text16 error %d", err);
            free(base16buf);
            break;
        }

        if (useTokenIndex) {
            err = sqlite3_bind_int(statement, 3, numTokens);
            if (err != SQLITE_OK) {
                ALOGE(" sqlite3_bind_int error %d", err);
                free(base16buf);
                break;
            }
        }

        err = sqlite3_step(statement);
        free(base16buf);

        if (err != SQLITE_DONE) {
            ALOGE(" sqlite3_step error %d", err);
            break;
        }
        numTokens++;
        if (numTokens == 1) {
            // first call
            u_strtok_r(origData, delim, &state);
        }
    } while ((token = u_strtok_r(NULL, delim, &state)) != NULL);
    sqlite3_result_int(context, numTokens);
}
Example #6
0
/*
** Create an sqlite3_backup process to copy the contents of zSrcDb from
** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
** a pointer to the new sqlite3_backup object.
**
** If an error occurs, NULL is returned and an error code and error message
** stored in database handle pDestDb.
** pDestDb  Database to write to
** zDestDb  Name of database within pDestDb
** pSrcDb   Database connection to read from
** zSrcDb   Name of database within pSrcDb
*/
sqlite3_backup *sqlite3_backup_init(sqlite3* pDestDb, const char *zDestDb,
    sqlite3* pSrcDb, const char *zSrcDb)
{
	sqlite3_backup *p;                    /* Value to return */
	Parse parse;
	DB_ENV *dbenv;
	int ret;

	p = NULL;
	ret = 0;

	if (!pDestDb || !pSrcDb)
		return 0;

	sqlite3_mutex_enter(pSrcDb->mutex);
	sqlite3_mutex_enter(pDestDb->mutex);
	if (pSrcDb == pDestDb) {
		sqlite3Error(pDestDb, SQLITE_ERROR,
		    "source and destination must be distinct");
		goto err;
	}

	/* Allocate space for a new sqlite3_backup object */
	p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
	if (!p) {
		sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
		goto err;
	}

	memset(p, 0, sizeof(sqlite3_backup));
	p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
	p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
	p->pDestDb = pDestDb;
	p->pSrcDb = pSrcDb;

	if (0 == p->pSrc) {
		p->rc = p->pSrcDb->errCode;
		goto err;
	}
	if (0 == p->pDest) {
		p->rc = p->pDestDb->errCode;
		goto err;
	}

	p->iDb = sqlite3FindDbName(pDestDb, zDestDb);

	p->srcName = sqlite3_malloc((int)strlen(zSrcDb) + 1);
	p->destName = sqlite3_malloc((int)strlen(zDestDb) + 1);
	if (0 == p->srcName || 0 == p->destName) {
		p->rc = SQLITE_NOMEM;
		goto err;
	}
	strncpy(p->srcName, zSrcDb, strlen(zSrcDb) + 1);
	strncpy(p->destName, zDestDb, strlen(zDestDb) + 1);

	if (p->pDest->pBt->full_name) {
		const char *fullName = p->pDest->pBt->full_name;
		p->fullName = sqlite3_malloc((int)strlen(fullName) + 1);
		if (!p->fullName) {
			p->rc = SQLITE_NOMEM;
			goto err;
		}
		strncpy(p->fullName, fullName, strlen(fullName) + 1);
	}

	/*
	 * Make sure the schema has been read in, so the keyInfo
	 * can be retrieved for the indexes.  No-op if already read.
	 */
	memset(&parse, 0, sizeof(parse));
	parse.db = p->pSrcDb;
	p->rc = sqlite3ReadSchema(&parse);
	if (p->rc != SQLITE_OK) {
		if (parse.zErrMsg != NULL)
			sqlite3DbFree(p->pSrcDb, parse.zErrMsg);
		goto err;
	}

	/* Begin a transaction on the source. */
	if (!p->pSrc->connected) {
		if ((p->rc = btreeOpenEnvironment(p->pSrc, 1)) != SQLITE_OK)
			goto err;
	}
	dbenv = p->pSrc->pBt->dbenv;
	p->rc = dberr2sqlite(dbenv->txn_begin(dbenv, p->pSrc->family_txn,
	    &p->srcTxn, 0), NULL);
	if (p->rc != SQLITE_OK) {
		sqlite3Error(pSrcDb, p->rc, 0);
		goto err;
	}

	/*
	 * Get the page count and list of tables to copy. This will
	 * result in a read lock on the schema table, held in the
	 * read transaction.
	 */
	if ((p->rc = btreeGetPageCount(p->pSrc,
	    &p->tables, &p->nPagecount, p->srcTxn)) != SQLITE_OK) {
		sqlite3Error(pSrcDb, p->rc, 0);
		goto err;
	}

	p->nRemaining = p->nPagecount;
	p->pSrc->nBackup++;
	p->pDest->nBackup++;
	p->lastUpdate = p->pSrc->updateDuringBackup;

	goto done;

err:	if (p != 0) {
		if (pDestDb->errCode == SQLITE_OK)
			sqlite3Error(pDestDb, p->rc, 0);
		if (p->srcTxn)
			p->srcTxn->abort(p->srcTxn);
		if (p->srcName != 0)
			sqlite3_free(p->srcName);
		if (p->destName != 0)
			sqlite3_free(p->destName);
		if (p->fullName != 0)
			sqlite3_free(p->fullName);
		if (p->tables != 0)
			sqlite3_free(p->tables);
		sqlite3_free(p);
		p = NULL;
	}
done:	sqlite3_mutex_leave(pDestDb->mutex);
	sqlite3_mutex_leave(pSrcDb->mutex);
	return p;
}
Example #7
0
static gchar *get_query_string(const dt_collection_properties_t property, const gchar *text)
{
  char *escaped_text = sqlite3_mprintf("%q", text);
  gchar *query = NULL;

  switch(property)
  {
    case DT_COLLECTION_PROP_FILMROLL: // film roll
      if(!(escaped_text && *escaped_text))
        query = dt_util_dstrcat(query, "(film_id in (select id from film_rolls where folder like '%s%%'))",
                                escaped_text);
      else
        query = dt_util_dstrcat(query, "(film_id in (select id from film_rolls where folder like '%s'))",
                                escaped_text);
      break;

    case DT_COLLECTION_PROP_FOLDERS: // folders
      query = dt_util_dstrcat(query, "(film_id in (select id from film_rolls where folder like '%s%%'))",
                              escaped_text);
      break;

    case DT_COLLECTION_PROP_COLORLABEL: // colorlabel
    {
      int color = 0;
      if(!(escaped_text && *escaped_text) || strcmp(escaped_text, "%") == 0)
        query = dt_util_dstrcat(query, "(id in (select imgid from color_labels where color IS NOT NULL))");
      else
      {
        if(strcmp(escaped_text, _("red")) == 0)
          color = 0;
        else if(strcmp(escaped_text, _("yellow")) == 0)
          color = 1;
        else if(strcmp(escaped_text, _("green")) == 0)
          color = 2;
        else if(strcmp(escaped_text, _("blue")) == 0)
          color = 3;
        else if(strcmp(escaped_text, _("purple")) == 0)
          color = 4;
        query = dt_util_dstrcat(query, "(id in (select imgid from color_labels where color=%d))", color);
      }
    }
    break;

    case DT_COLLECTION_PROP_HISTORY: // history
      query = dt_util_dstrcat(query, "(id %s in (select imgid from history where imgid=images.id)) ",
                              (strcmp(escaped_text, _("altered")) == 0) ? "" : "not");
      break;

    case DT_COLLECTION_PROP_GEOTAGGING: // geotagging
      query = dt_util_dstrcat(query, "(id %s in (select id AS imgid from images where (longitude IS NOT NULL AND "
                                 "latitude IS NOT NULL))) ",
                              (strcmp(escaped_text, _("tagged")) == 0) ? "" : "not");
      break;

    case DT_COLLECTION_PROP_CAMERA: // camera
      if (!text || text[0] == '\0') // Optimize away the empty case
        query = dt_util_dstrcat(query, "(1=1)");
      else
      {
        // Start query with a false statement to avoid special casing the first condition
        query = dt_util_dstrcat(query, "((1=0)");
        GList *lists = NULL;
        dt_collection_get_makermodel(text, NULL, &lists);
        GList *element = lists;
        while (element)
        {
          GList *tuple = element->data;
          char *mk = sqlite3_mprintf("%q", tuple->data);
          char *md = sqlite3_mprintf("%q", tuple->next->data);
          query = dt_util_dstrcat(query, " or (maker = '%s' and model = '%s')", mk, md);
          sqlite3_free(mk);
          sqlite3_free(md);
          g_free(tuple->data);
          g_free(tuple->next->data);
          g_list_free(tuple);
          element = element->next;
        }
        g_list_free(lists);
        query = dt_util_dstrcat(query, ")");
      }
      break;
    case DT_COLLECTION_PROP_TAG: // tag
      query = dt_util_dstrcat(query, "(id in (select imgid from tagged_images as a join "
                                 "tags as b on a.tagid = b.id where name like '%s'))",
                              escaped_text);
      break;

    // TODO: How to handle images without metadata? In the moment they are not shown.
    // TODO: Autogenerate this code?
    case DT_COLLECTION_PROP_TITLE: // title
      query = dt_util_dstrcat(query, "(id in (select id from meta_data where key = %d and value like '%%%s%%'))",
                      DT_METADATA_XMP_DC_TITLE, escaped_text);
      break;
    case DT_COLLECTION_PROP_DESCRIPTION: // description
      query = dt_util_dstrcat(query, "(id in (select id from meta_data where key = %d and value like '%%%s%%'))",
                      DT_METADATA_XMP_DC_DESCRIPTION, escaped_text);
      break;
    case DT_COLLECTION_PROP_CREATOR: // creator
      query = dt_util_dstrcat(query, "(id in (select id from meta_data where key = %d and value like '%%%s%%'))",
                      DT_METADATA_XMP_DC_CREATOR, escaped_text);
      break;
    case DT_COLLECTION_PROP_PUBLISHER: // publisher
      query = dt_util_dstrcat(query, "(id in (select id from meta_data where key = %d and value like '%%%s%%'))",
                      DT_METADATA_XMP_DC_PUBLISHER, escaped_text);
      break;
    case DT_COLLECTION_PROP_RIGHTS: // rights
      query = dt_util_dstrcat(query, "(id in (select id from meta_data where key = %d and value like '%%%s%%'))",
                      DT_METADATA_XMP_DC_RIGHTS, escaped_text);
      break;
    case DT_COLLECTION_PROP_LENS: // lens
      query = dt_util_dstrcat(query, "(lens like '%%%s%%')", escaped_text);
      break;

    case DT_COLLECTION_PROP_FOCAL_LENGTH: // focal length
    {
      gchar *operator, *number1, *number2;
      dt_collection_split_operator_number(escaped_text, &number1, &number2, &operator);

      if(operator&& strcmp(operator, "[]") == 0)
      {
        if(number1 && number2)
          query = dt_util_dstrcat(query, "((focal_length >= %s) AND (focal_length <= %s))", number1, number2);
      }
      else if(operator&& number1)
        query = dt_util_dstrcat(query, "(focal_length %s %s)", operator, number1);
      else if(number1)
        query = dt_util_dstrcat(query, "(focal_length = %s)", number1);
      else
        query = dt_util_dstrcat(query, "(focal_length like '%%%s%%')", escaped_text);

      g_free(operator);
      g_free(number1);
      g_free(number2);
    }
    break;

    case DT_COLLECTION_PROP_ISO: // iso
    {
      gchar *operator, *number1, *number2;
      dt_collection_split_operator_number(escaped_text, &number1, &number2, &operator);

      if(operator&& strcmp(operator, "[]") == 0)
      {
        if(number1 && number2)
          query = dt_util_dstrcat(query, "((iso >= %s) AND (iso <= %s))", number1, number2);
      }
      else if(operator&& number1)
        query = dt_util_dstrcat(query, "(iso %s %s)", operator, number1);
      else if(number1)
        query = dt_util_dstrcat(query, "(iso = %s)", number1);
      else
        query = dt_util_dstrcat(query, "(iso like '%%%s%%')", escaped_text);

      g_free(operator);
      g_free(number1);
      g_free(number2);
    }
    break;

    case DT_COLLECTION_PROP_APERTURE: // aperture
    {
      gchar *operator, *number1, *number2;
      dt_collection_split_operator_number(escaped_text, &number1, &number2, &operator);

      if(operator&& strcmp(operator, "[]") == 0)
      {
        if(number1 && number2)
          query = dt_util_dstrcat(query, "((round(aperture,1) >= %s) AND (round(aperture,1) <= %s))", number1,
                                  number2);
      }
      else if(operator&& number1)
        query = dt_util_dstrcat(query, "(round(aperture,1) %s %s)", operator, number1);
      else if(number1)
        query = dt_util_dstrcat(query, "(round(aperture,1) = %s)", number1);
      else
        query = dt_util_dstrcat(query, "(round(aperture,1) like '%%%s%%')", escaped_text);

      g_free(operator);
      g_free(number1);
      g_free(number2);
    }
    break;

    case DT_COLLECTION_PROP_FILENAME: // filename
      query = dt_util_dstrcat(query, "(filename like '%%%s%%')", escaped_text);
      break;

    case DT_COLLECTION_PROP_DAY:
    // query = dt_util_dstrcat(query, "(datetime_taken like '%%%s%%')", escaped_text);
    // break;

    case DT_COLLECTION_PROP_TIME:
    {
      gchar *operator, *number1, *number2;
      dt_collection_split_operator_datetime(escaped_text, &number1, &number2, &operator);

      if(strcmp(operator, "[]") == 0)
      {
        if(number1 && number2)
          query = dt_util_dstrcat(query, "((datetime_taken >= '%s') AND (datetime_taken <= '%s'))", number1,
                                  number2);
      }
      else if((strcmp(operator, "=") == 0 || strcmp(operator, "") == 0) && number1)
        query = dt_util_dstrcat(query, "(datetime_taken like '%s')", number1);
      else if(strcmp(operator, "<>") == 0 && number1)
        query = dt_util_dstrcat(query, "(datetime_taken not like '%s')", number1);
      else if(number1)
        query = dt_util_dstrcat(query, "(datetime_taken %s '%s')", operator, number1);
      else
        query = dt_util_dstrcat(query, "(datetime_taken like '%%%s%%')", escaped_text);

      g_free(operator);
      g_free(number1);
      g_free(number2);
    }
    break;

    default:
      // we shouldn't be here
      break;
  }
  sqlite3_free(escaped_text);

  if(!query) // We've screwed up and not done a query string, send a placeholder
    query = dt_util_dstrcat(query, "(1=1)");

  return query;
}
Example #8
0
/*
** Invoke a virtual table constructor (either xCreate or xConnect). The
** pointer to the function to invoke is passed as the fourth parameter
** to this procedure.
*/
static int vtabCallConstructor(
  sqlite3 *db, 
  Table *pTab,
  Module *pMod,
  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  char **pzErr
){
  VtabCtx sCtx, *pPriorCtx;
  VTable *pVTable;
  int rc;
  const char *const*azArg = (const char *const*)pTab->azModuleArg;
  int nArg = pTab->nModuleArg;
  char *zErr = 0;
  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);

  if( !zModuleName ){
    return SQLITE_NOMEM;
  }

  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  if( !pVTable ){
    sqlite3DbFree(db, zModuleName);
    return SQLITE_NOMEM;
  }
  pVTable->db = db;
  pVTable->pMod = pMod;

  /* Invoke the virtual table constructor */
  assert( &db->pVtabCtx );
  assert( xConstruct );
  sCtx.pTab = pTab;
  sCtx.pVTable = pVTable;
  pPriorCtx = db->pVtabCtx;
  db->pVtabCtx = &sCtx;
  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  db->pVtabCtx = pPriorCtx;
  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;

  if( SQLITE_OK!=rc ){
    if( zErr==0 ){
      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
    }else {
      *pzErr = sqlite3MPrintf(db, "%s", zErr);
      sqlite3_free(zErr);
    }
    sqlite3DbFree(db, pVTable);
  }else if( ALWAYS(pVTable->pVtab) ){
    /* Justification of ALWAYS():  A correct vtab constructor must allocate
    ** the sqlite3_vtab object if successful.  */
    pVTable->pVtab->pModule = pMod->pModule;
    pVTable->nRef = 1;
    if( sCtx.pTab ){
      const char *zFormat = "vtable constructor did not declare schema: %s";
      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
      sqlite3VtabUnlock(pVTable);
      rc = SQLITE_ERROR;
    }else{
      int iCol;
      /* If everything went according to plan, link the new VTable structure
      ** into the linked list headed by pTab->pVTable. Then loop through the 
      ** columns of the table to see if any of them contain the token "hidden".
      ** If so, set the Column.isHidden flag and remove the token from
      ** the type string.  */
      pVTable->pNext = pTab->pVTable;
      pTab->pVTable = pVTable;

      for(iCol=0; iCol<pTab->nCol; iCol++){
        char *zType = pTab->aCol[iCol].zType;
        int nType;
        int i = 0;
        if( !zType ) continue;
        nType = sqlite3Strlen30(zType);
        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
          for(i=0; i<nType; i++){
            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
             && (zType[i+7]=='\0' || zType[i+7]==' ')
            ){
              i++;
              break;
            }
          }
        }
        if( i<nType ){
          int j;
          int nDel = 6 + (zType[i+6] ? 1 : 0);
          for(j=i; (j+nDel)<=nType; j++){
            zType[j] = zType[j+nDel];
          }
          if( zType[i]=='\0' && i>0 ){
            assert(zType[i-1]==' ');
            zType[i-1] = '\0';
          }
          pTab->aCol[iCol].isHidden = 1;
        }
      }
    }
  }

  sqlite3DbFree(db, zModuleName);
  return rc;
}
Example #9
0
static int sqlite_log(struct cw_cdr *cdr)
{
	int res = 0;
	char *zErr = 0;
	struct tm tm;
	time_t t;
	char startstr[80], answerstr[80], endstr[80];
	int count;
	char fn[PATH_MAX];
	char *sql;

	cw_mutex_lock(&sqlite3_lock);

	/* is the database there? */
	snprintf(fn, sizeof(fn), "%s/cdr.db", cw_config_CW_LOG_DIR);
	sqlite3_open(fn, &db);
	if (!db) {
		cw_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
		free(zErr);
		return -1;
	}


	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++) {
		sql = sqlite3_mprintf(
			"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
			")",
				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
			);
		cw_log(LOG_DEBUG, "CDR SQLITE3 SQL [%s]\n", sql);
		res = sqlite3_exec(db,
						   sql,
						   NULL,
						   NULL,
						   &zErr
						   );

		if (sql) {
		    sqlite3_free(sql);
		    sql = NULL;
		}
		if (res != SQLITE_BUSY && res != SQLITE_LOCKED)
			break;
		usleep(200);
	}

	if (sql) {
		sqlite3_free(sql);
		sql = NULL;
	}
	
	if (zErr) {
		cw_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
		free(zErr);
	}

	if (db) sqlite3_close(db);

	cw_mutex_unlock(&sqlite3_lock);
	return res;
}
Example #10
0
/*
** Destroy a tokenizer
*/
static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  sqlite3_free(pTokenizer);
  return SQLITE_OK;
}
Example #11
0
/**
 * Attaches a registry database to the registry object. Prior to calling this,
 * the registry object is not actually connected to the registry. This function
 * attaches it so it can be queried and manipulated.
 *
 * @param [in] reg     the registry to attach to
 * @param [in] path    path to the registry db on disk
 * @param [out] errPtr on error, a description of the error that occurred
 * @return             true if success; false if failure
 */
int reg_attach(reg_registry* reg, const char* path, reg_error* errPtr) {
    struct stat sb;
    int initialized = 1; /* registry already exists */
    int can_write = 1; /* can write to this location */
    int result = 0;
    if (reg->status & reg_attached) {
        reg_throw(errPtr, REG_MISUSE, "a database is already attached to this "
                "registry");
        return 0;
    }
    if (stat(path, &sb) != 0) {
        initialized = 0;
        if (errno == ENOENT) {
            char *dirc, *dname;
            dirc = strdup(path);
            dname = dirname(dirc);
            if (stat(dname, &sb) != 0) {
                can_write = 0;
            }
            free(dirc);
        } else {
            can_write = 0;
        }
    }
    /* can_write is still true if one of the stat calls succeeded */
    if (can_write) {
        if (sb.st_uid == getuid()) {
            if (!(sb.st_mode & S_IWUSR)) {
                can_write = 0;
            }
        } else if (sb.st_gid == getgid()) {
            if (!(sb.st_mode & S_IWGRP)) {
                can_write = 0;
            }
        } else {
            if (!(sb.st_mode & S_IWOTH)) {
                can_write = 0;
            }
        }
    }
    if (initialized || can_write) {
        sqlite3_stmt* stmt = NULL;
        char* query = sqlite3_mprintf("ATTACH DATABASE '%q' AS registry", path);
        int r;
        do {
            r = sqlite3_prepare(reg->db, query, -1, &stmt, NULL);
        } while (r == SQLITE_BUSY);
        if (r == SQLITE_OK) {
            /* XXX: Busy waiting, consider using sqlite3_busy_handler/timeout */
            do {
                sqlite3_step(stmt);
                r = sqlite3_reset(stmt);
                switch (r) {
                    case SQLITE_OK:
                        if (initialized || (create_tables(reg->db, errPtr))) {
                            Tcl_InitHashTable(&reg->open_entries,
                                    sizeof(sqlite_int64)/sizeof(int));
                            reg->status |= reg_attached;
                            result = 1;
                        }
                        break;
                    case SQLITE_BUSY:
                        break;
                    default:
                        reg_sqlite_error(reg->db, errPtr, query);
                }
            } while (r == SQLITE_BUSY);
        } else {
            reg_sqlite_error(reg->db, errPtr, query);
        }
        if (stmt) {
            sqlite3_finalize(stmt);
        }
        sqlite3_free(query);
    } else {
        reg_throw(errPtr, REG_CANNOT_INIT, "port registry doesn't exist at "
                "\"%q\" and couldn't write to this location", path);
    }
    return result;
}
Example #12
0
/*
** Close a tokenization cursor previously opened by a call to
** porterOpen() above.
*/
static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  sqlite3_free(c->zToken);
  sqlite3_free(c);
  return SQLITE_OK;
}
Example #13
0
int db_create(void)
{
    static const char query[] =
            "PRAGMA synchronous = 0;"
                    "PRAGMA journal_mode = OFF;"

                    "CREATE TABLE IF NOT EXISTS files ("
                    "   fid INTEGER PRIMARY KEY,"
                    "	hash BLOB NOT NULL,"
                    "	name TEXT NOT NULL,"
                    "   ext TEXT,"
                    "   size INTEGER NOT NULL,"
                    "   type INTEGER NOT NULL,"
                    "   srcavail INTEGER DEFAULT 0,"
                    "   srccomplete INTEGER DEFAULT 0,"
                    "   rating INTEGER DEFAULT 0,"
                    "   rated_count INTEGER DEFAULT 0,"
                    "   mlength INTEGER,"
                    "   mbitrate INTEGER,"
                    "   mcodec TEXT"
                    ");"

                    "CREATE VIRTUAL TABLE IF NOT EXISTS fnames USING fts4 ("
                    "   content=\"files\", tokenize=unicode61, name"
                    ");"

                    "CREATE TABLE IF NOT EXISTS sources ("
                    "   fid INTEGER NOT NULL,"
                    "   sid INTEGER NOT NULL,"
                    "   complete INTEGER,"
                    "   rating INTEGER"
                    ");"
                    "CREATE INDEX IF NOT EXISTS sources_fid_i"
                    "   ON sources(fid);"
                    "CREATE INDEX IF NOT EXISTS sources_sid_i"
                    "   ON sources(sid);"

                    "CREATE TRIGGER IF NOT EXISTS sources_ai AFTER INSERT ON sources BEGIN"
                    "   UPDATE files SET srcavail=srcavail+1,srccomplete=srccomplete+new.complete,"
                    "       rating=rating+new.rating, rated_count = CASE WHEN new.rating<>0 THEN rated_count+1 ELSE 0 END"
                    "   WHERE fid=new.fid;"
                    "END;"
                    "CREATE TRIGGER IF NOT EXISTS sources_bd BEFORE DELETE ON sources BEGIN"
                    "   UPDATE files SET srcavail=srcavail-1,srccomplete=srccomplete-old.complete,"
                    "       rating=rating-old.rating, rated_count = CASE WHEN old.rating<>0 THEN rated_count-1 ELSE rated_count END"
                    "   WHERE fid=old.fid;"
                    "END;"

                    // delete when no sources available
                    " CREATE TRIGGER IF NOT EXISTS files_au AFTER UPDATE ON files WHEN new.srcavail=0 BEGIN"
                    "   DELETE FROM files WHERE fid=new.fid;"
                    "END;"

                    // update on file name change
                    "CREATE TRIGGER IF NOT EXISTS files_fts1 BEFORE UPDATE ON files WHEN new.name<>old.name BEGIN"
                    "   DELETE FROM fnames WHERE docid=old.rowid;"
                    "END;"
                    "CREATE TRIGGER IF NOT EXISTS files_fts2 AFTER UPDATE ON files WHEN new.name<>old.name BEGIN"
                    "   INSERT INTO fnames(docid, name) VALUES(new.rowid, new.name);"
                    "END;"
                    // delete
                    "CREATE TRIGGER IF NOT EXISTS files_fts3 BEFORE DELETE ON files BEGIN"
                    "   DELETE FROM fnames WHERE docid=old.rowid;"
                    "END;"
                    // insert
                    "CREATE TRIGGER IF NOT EXISTS files_fts4 AFTER INSERT ON files BEGIN"
                    "   INSERT INTO fnames(docid, name) VALUES(new.rowid, new.name);"
                    "END;"

                    "DELETE FROM files;"
                    "DELETE FROM fnames;"
                    "DELETE FROM sources;";

    int err;

    if (!sqlite3_threadsafe()) {
        ED2KD_LOGERR("sqlite3 must be threadsafe");
        return 0;
    }

    err = sqlite3_open_v2(DB_NAME, &s_db, DB_OPEN_FLAGS, NULL);

    if (SQLITE_OK == err) {
        char *errmsg;

        err = sqlite3_exec(s_db, query, NULL, NULL, &errmsg);
        if (SQLITE_OK != err) {
            ED2KD_LOGERR("failed to execute database init script (%s)", errmsg);
            sqlite3_free(errmsg);
            return 0;
        }
    } else {
        ED2KD_LOGERR("failed to create DB (%s)", sqlite3_errmsg(s_db));
        return 0;
    }

    return 1;
}
Example #14
0
static void pk_backend_refresh_cache_thread(PkBackendJob *job, GVariant *params, gpointer user_data) {
	gchar *tmp_dir_name, *db_err, *path = NULL;
	gint ret;
	gboolean force;
	GSList *file_list = NULL, *l;
	GFile *db_file = NULL;
	GFileInfo *file_info = NULL;
	GError *err = NULL;
	sqlite3_stmt *stmt = NULL;
	PkBackendKatjaJobData *job_data = pk_backend_job_get_user_data(job);

	pk_backend_job_set_status(job, PK_STATUS_ENUM_DOWNLOAD_CHANGELOG);

	/* Create temporary directory */
	tmp_dir_name = g_dir_make_tmp("PackageKit.XXXXXX", &err);
	if (!tmp_dir_name) {
		pk_backend_job_error_code(job, PK_ERROR_ENUM_INTERNAL_ERROR, "%s", err->message);
		g_error_free(err);
		pk_backend_job_finished(job);
		return;
	}

	g_variant_get(params, "(b)", &force);

	/* Force the complete cache refresh if the read configuration file is newer than the metadata cache */
	if (!force) {
		path = g_build_filename(LOCALSTATEDIR, "cache", "PackageKit", "metadata", "metadata.db", NULL);
		db_file = g_file_new_for_path(path);
		file_info = g_file_query_info(db_file, "time::modified-usec", G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, &err);
		if (err) {
			pk_backend_job_error_code(job, PK_ERROR_ENUM_NO_CACHE, "%s: %s", path, err->message);
			g_error_free(err);
			goto out;
		}
		ret = sqlite3_prepare_v2(job_data->db,
								 "SELECT value FROM cache_info WHERE key LIKE 'last_modification'",
								 -1,
								 &stmt,
								 NULL);
		if ((ret != SQLITE_OK) || ((ret = sqlite3_step(stmt)) != SQLITE_ROW)) {
			pk_backend_job_error_code(job, PK_ERROR_ENUM_NO_CACHE, "%s: %s", path, sqlite3_errstr(ret));
			goto out;
		}
		if ((guint32) sqlite3_column_int(stmt, 0) > g_file_info_get_attribute_uint32(file_info, "time::modified-usec"))
			force = TRUE;
	}

	if (force) { /* It should empty all tables */
		if (sqlite3_exec(job_data->db, "DELETE FROM repos", NULL, 0, &db_err) != SQLITE_OK) {
			pk_backend_job_error_code(job, PK_ERROR_ENUM_INTERNAL_ERROR, "%s", db_err);
			sqlite3_free(db_err);
			goto out;
		}
	}

	for (l = repos; l; l = g_slist_next(l))	/* Get list of files that should be downloaded */
		file_list = g_slist_concat(file_list, katja_pkgtools_collect_cache_info(l->data, tmp_dir_name));

	/* Download repository */
	pk_backend_job_set_status(job, PK_STATUS_ENUM_DOWNLOAD_REPOSITORY);

	for (l = file_list; l; l = g_slist_next(l))
		katja_get_file(&job_data->curl, ((gchar **)l->data)[0], ((gchar **)l->data)[1]);
	g_slist_free_full(file_list, (GDestroyNotify)g_strfreev);

	/* Refresh cache */
	pk_backend_job_set_status(job, PK_STATUS_ENUM_REFRESH_CACHE);

	for (l = repos; l; l = g_slist_next(l))
		katja_pkgtools_generate_cache(l->data, job, tmp_dir_name);

out:
	sqlite3_finalize(stmt);
	if (file_info)
		g_object_unref(file_info);
	if (db_file)
		g_object_unref(db_file);
	g_free(path);

	pk_directory_remove_contents(tmp_dir_name);
	g_rmdir(tmp_dir_name);
	g_free(tmp_dir_name);
	pk_backend_job_finished(job);
}
Example #15
0
/*
** Load the content of the amatch data table into memory.
*/
static int amatchLoadRules(
  sqlite3 *db,                    /* Database handle */
  amatch_vtab *p,                 /* Virtual amatch table to configure */
  char **pzErr                    /* OUT: Error message */
){
  int rc = SQLITE_OK;             /* Return code */
  char *zSql;                     /* SELECT used to read from rules table */
  amatch_rule *pHead = 0;

  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zCostTab);
  if( zSql==0 ){
    rc = SQLITE_NOMEM;
  }else{
    int rc2;                      /* finalize() return code */
    sqlite3_stmt *pStmt = 0;
    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
    if( rc!=SQLITE_OK ){
      *pzErr = sqlite3_mprintf("%s: %s", p->zClassName, sqlite3_errmsg(db));
    }else if( sqlite3_column_count(pStmt)!=4 ){
      *pzErr = sqlite3_mprintf("%s: %s has %d columns, expected 4",
          p->zClassName, p->zCostTab, sqlite3_column_count(pStmt)
      );
      rc = SQLITE_ERROR;
    }else{
      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
        amatch_rule *pRule = 0;
        rc = amatchLoadOneRule(p, pStmt, &pRule, pzErr);
        if( pRule ){
          pRule->pNext = pHead;
          pHead = pRule;
        }
      }
    }
    rc2 = sqlite3_finalize(pStmt);
    if( rc==SQLITE_OK ) rc = rc2;
  }
  sqlite3_free(zSql);

  /* All rules are now in a singly linked list starting at pHead. This
  ** block sorts them by cost and then sets amatch_vtab.pRule to point to 
  ** point to the head of the sorted list.
  */
  if( rc==SQLITE_OK ){
    unsigned int i;
    amatch_rule *pX;
    amatch_rule *a[15];
    for(i=0; i<sizeof(a)/sizeof(a[0]); i++) a[i] = 0;
    while( (pX = pHead)!=0 ){
      pHead = pX->pNext;
      pX->pNext = 0;
      for(i=0; a[i] && i<sizeof(a)/sizeof(a[0])-1; i++){
        pX = amatchMergeRules(a[i], pX);
        a[i] = 0;
      }
      a[i] = amatchMergeRules(a[i], pX);
    }
    for(pX=a[0], i=1; i<sizeof(a)/sizeof(a[0]); i++){
      pX = amatchMergeRules(a[i], pX);
    }
    p->pRule = amatchMergeRules(p->pRule, pX);
  }else{
    /* An error has occurred. Setting p->pRule to point to the head of the
    ** allocated list ensures that the list will be cleaned up in this case.
    */
    assert( p->pRule==0 );
    p->pRule = pHead;
  }

  return rc;
}
Example #16
0
int
pkg_update(const char *name, const char *packagesite, bool force)
{
	char url[MAXPATHLEN];
	struct archive *a = NULL;
	struct archive_entry *ae = NULL;
	char repofile[MAXPATHLEN];
	char repofile_unchecked[MAXPATHLEN];
	char tmp[MAXPATHLEN];
	const char *dbdir = NULL;
	const char *repokey;
	unsigned char *sig = NULL;
	int siglen = 0;
	int fd, rc = EPKG_FATAL, ret;
	struct stat st;
	time_t t = 0;
	sqlite3 *sqlite;
	char *archreq = NULL;
	const char *myarch;
	int64_t res;
	const char *tmpdir;

	snprintf(url, MAXPATHLEN, "%s/repo.txz", packagesite);

	tmpdir = getenv("TMPDIR");
	if (tmpdir == NULL)
		tmpdir = "/tmp";
	strlcpy(tmp, tmpdir, sizeof(tmp));
	strlcat(tmp, "/repo.txz.XXXXXX", sizeof(tmp));

	fd = mkstemp(tmp);
	if (fd == -1) {
		pkg_emit_error("Could not create temporary file %s, "
		    "aborting update.\n", tmp);
		return (EPKG_FATAL);
	}

	if (pkg_config_string(PKG_CONFIG_DBDIR, &dbdir) != EPKG_OK) {
		pkg_emit_error("Cant get dbdir config entry");
		return (EPKG_FATAL);
	}

	snprintf(repofile, sizeof(repofile), "%s/%s.sqlite", dbdir, name);
	if (force)
		t = 0;		/* Always fetch */
	else {
		if (stat(repofile, &st) != -1) {
			t = st.st_mtime;
			/* add 1 minute to the timestamp because
			 * repo.sqlite is always newer than repo.txz,
			 * 1 minute should be enough.
			 */
			t += 60;
		}
	}

	rc = pkg_fetch_file_to_fd(url, fd, t);
	close(fd);
	if (rc != EPKG_OK) {
		goto cleanup;
	}

	a = archive_read_new();
	archive_read_support_compression_all(a);
	archive_read_support_format_tar(a);

	archive_read_open_filename(a, tmp, 4096);

	while (archive_read_next_header(a, &ae) == ARCHIVE_OK) {
		if (strcmp(archive_entry_pathname(ae), "repo.sqlite") == 0) {
			snprintf(repofile_unchecked, sizeof(repofile_unchecked),
			    "%s.unchecked", repofile);
			archive_entry_set_pathname(ae, repofile_unchecked);

			/*
			 * The repo should be owned by root and not writable
			 */
			archive_entry_set_uid(ae, 0);
			archive_entry_set_gid(ae, 0);
			archive_entry_set_perm(ae, 0644);

			archive_read_extract(a, ae, EXTRACT_ARCHIVE_FLAGS);
		}
		if (strcmp(archive_entry_pathname(ae), "signature") == 0) {
			siglen = archive_entry_size(ae);
			sig = malloc(siglen);
			archive_read_data(a, sig, siglen);
		}
	}

	if (pkg_config_string(PKG_CONFIG_REPOKEY, &repokey) != EPKG_OK) {
		free(sig);
		
		return (EPKG_FATAL);
	}

	if (repokey != NULL) {
		if (sig != NULL) {
			ret = rsa_verify(repofile_unchecked, repokey,
			    sig, siglen - 1);
			if (ret != EPKG_OK) {
				pkg_emit_error("Invalid signature, "
				    "removing repository.\n");
				unlink(repofile_unchecked);
				free(sig);
				rc = EPKG_FATAL;
				goto cleanup;
			}
			free(sig);
		} else {
			pkg_emit_error("No signature found in the repository.  "
			    "Can not validate against %s key.", repokey);
			rc = EPKG_FATAL;
			unlink(repofile_unchecked);
			goto cleanup;
		}
	}

	/* check is the repository is for valid architecture */
	sqlite3_initialize();

	if (sqlite3_open(repofile_unchecked, &sqlite) != SQLITE_OK) {
		unlink(repofile_unchecked);
		pkg_emit_error("Corrupted repository");
		rc = EPKG_FATAL;
		goto cleanup;
	}

	pkg_config_string(PKG_CONFIG_ABI, &myarch);

	archreq = sqlite3_mprintf("select count(arch) from packages "
	    "where arch not GLOB '%q'", myarch);
	if (get_pragma(sqlite, archreq, &res) != EPKG_OK) {
		sqlite3_free(archreq);
		pkg_emit_error("Unable to query repository");
		rc = EPKG_FATAL;
		sqlite3_close(sqlite);
		goto cleanup;
	}

	if (res > 0) {
		pkg_emit_error("At least one of the packages provided by"
		    "the repository is not compatible with your abi: %s",
		    myarch);
		rc = EPKG_FATAL;
		sqlite3_close(sqlite);
		goto cleanup;
	}

	sqlite3_close(sqlite);
	sqlite3_shutdown();


	if (rename(repofile_unchecked, repofile) != 0) {
		pkg_emit_errno("rename", "");
		rc = EPKG_FATAL;
		goto cleanup;
	}

	if ((rc = remote_add_indexes(name)) != EPKG_OK)
		goto cleanup;

	rc = EPKG_OK;

	cleanup:
	if (a != NULL)
		archive_read_finish(a);

	(void)unlink(tmp);

	return (rc);
}
Example #17
0
/*
** xConnect/xCreate method for the amatch module. Arguments are:
**
**   argv[0]    -> module name  ("approximate_match")
**   argv[1]    -> database name
**   argv[2]    -> table name
**   argv[3...] -> arguments
*/
static int amatchConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  int rc = SQLITE_OK;             /* Return code */
  amatch_vtab *pNew = 0;          /* New virtual table */
  const char *zModule = argv[0];
  const char *zDb = argv[1];
  const char *zVal;
  int i;

  (void)pAux;
  *ppVtab = 0;
  pNew = sqlite3_malloc( sizeof(*pNew) );
  if( pNew==0 ) return SQLITE_NOMEM;
  rc = SQLITE_NOMEM;
  memset(pNew, 0, sizeof(*pNew));
  pNew->db = db;
  pNew->zClassName = sqlite3_mprintf("%s", zModule);
  if( pNew->zClassName==0 ) goto amatchConnectError;
  pNew->zDb = sqlite3_mprintf("%s", zDb);
  if( pNew->zDb==0 ) goto amatchConnectError;
  pNew->zSelf = sqlite3_mprintf("%s", argv[2]);
  if( pNew->zSelf==0 ) goto amatchConnectError;
  for(i=3; i<argc; i++){
    zVal = amatchValueOfKey("vocabulary_table", argv[i]);
    if( zVal ){
      sqlite3_free(pNew->zVocabTab);
      pNew->zVocabTab = amatchDequote(zVal);
      if( pNew->zVocabTab==0 ) goto amatchConnectError;
      continue;
    }
    zVal = amatchValueOfKey("vocabulary_word", argv[i]);
    if( zVal ){
      sqlite3_free(pNew->zVocabWord);
      pNew->zVocabWord = amatchDequote(zVal);
      if( pNew->zVocabWord==0 ) goto amatchConnectError;
      continue;
    }
    zVal = amatchValueOfKey("vocabulary_language", argv[i]);
    if( zVal ){
      sqlite3_free(pNew->zVocabLang);
      pNew->zVocabLang = amatchDequote(zVal);
      if( pNew->zVocabLang==0 ) goto amatchConnectError;
      continue;
    }
    zVal = amatchValueOfKey("edit_distances", argv[i]);
    if( zVal ){
      sqlite3_free(pNew->zCostTab);
      pNew->zCostTab = amatchDequote(zVal);
      if( pNew->zCostTab==0 ) goto amatchConnectError;
      continue;
    }
    *pzErr = sqlite3_mprintf("unrecognized argument: [%s]\n", argv[i]);
    amatchFree(pNew);
    *ppVtab = 0;
    return SQLITE_ERROR;
  }
  rc = SQLITE_OK;
  if( pNew->zCostTab==0 ){
    *pzErr = sqlite3_mprintf("no edit_distances table specified");
    rc = SQLITE_ERROR;
  }else{
    rc = amatchLoadRules(db, pNew, pzErr);
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3_declare_vtab(db,
           "CREATE TABLE x(word,distance,language,"
           "command HIDDEN,nword HIDDEN)"
         );
#define AMATCH_COL_WORD       0
#define AMATCH_COL_DISTANCE   1
#define AMATCH_COL_LANGUAGE   2
#define AMATCH_COL_COMMAND    3
#define AMATCH_COL_NWORD      4
  }
  if( rc!=SQLITE_OK ){
    amatchFree(pNew);
  }
  *ppVtab = &pNew->base;
  return rc;

amatchConnectError:
  amatchFree(pNew);
  return rc;
}
Example #18
0
 SqliteDataset::~SqliteDataset(){
   if (errmsg) sqlite3_free(errmsg);
 }
Example #19
0
/* Close or free all handles and commit or rollback the transaction. */
static int backupCleanup(sqlite3_backup *p)
{
	int rc, rc2, ret;
	void *app;
	DB *db;

	rc = rc2 = SQLITE_OK;

	if (!p || p->rc == SQLITE_OK)
		return rc;

	rc2 = sqlite3BtreeCloseCursor(&p->destCur);
	if (rc2 != SQLITE_OK)
		rc = rc2;
	if (p->srcCur) {
		db = p->srcCur->dbp;
		app = db->app_private;
		if ((ret = p->srcCur->close(p->srcCur)) == 0)
			ret = db->close(db, DB_NOSYNC);
		rc2 = dberr2sqlite(ret, NULL);
		/*
		 * The KeyInfo was allocated in btreeSetupIndex,
		 * so have to deallocate it here.
		 */
		if (app)
			sqlite3DbFree(p->pSrcDb, app);
	}
	if (rc2 != SQLITE_OK)
		rc = rc2;
	p->srcCur = 0;

	/*
	 * May retry on a locked or busy error, so keep
	 * these values.
	 */
	if (p->rc != SQLITE_LOCKED && p->rc != SQLITE_BUSY) {
		if (p->srcName)
			sqlite3_free(p->srcName);
		if (p->destName != 0)
			sqlite3_free(p->destName);
		p->srcName = p->destName = NULL;
	}

	if (p->tables != 0)
			sqlite3_free(p->tables);
	p->tables = NULL;

	if (p->pSrc->nBackup)
		p->pSrc->nBackup--;
	if (p->pDest != NULL && p->pDest->nBackup)
		p->pDest->nBackup--;
	if (p->srcTxn) {
		if (p->rc == SQLITE_DONE)
			ret = p->srcTxn->commit(p->srcTxn, 0);
		else
			ret = p->srcTxn->abort(p->srcTxn);
		rc2 = dberr2sqlite(ret, NULL);
	}
	p->srcTxn = 0;
	if (rc2 != SQLITE_OK && sqlite3BtreeIsInTrans(p->pDest)) {
		rc = rc2;
		if (p->rc == SQLITE_DONE)
			rc2 = sqlite3BtreeCommit(p->pDest);
		else
			rc2 = sqlite3BtreeRollback(p->pDest, SQLITE_OK);
		if (rc2 != SQLITE_OK)
			rc = rc2;
	}

	if (p->pDest && p->openDest) {
		char path[512];

		/*
		 * If successfully done then delete the old backup, if
		 * an error then delete the current database and restore
		 * the old backup.
		 */
		sqlite3_snprintf(sizeof(path), path,
		    "%s%s", p->fullName, BACKUP_SUFFIX);
		if (p->rc == SQLITE_DONE) {
			rc2 = btreeDeleteEnvironment(p->pDest, path, 0);
		} else {
			rc2 = btreeDeleteEnvironment(p->pDest, p->fullName, 0);
			if (!__os_exists(NULL, path, 0))
				__os_rename(NULL, path, p->fullName, 0);
		}
		if (rc2 != SQLITE_BUSY) {
		    p->pDest = p->pDestDb->aDb[p->iDb].pBt = NULL;
		    p->pDestDb->aDb[p->iDb].pSchema = NULL;
		}
		if (rc == SQLITE_OK)
			rc = rc2;
		if (rc == SQLITE_OK) {
			p->pDest = NULL;
			p->pDestDb->aDb[p->iDb].pBt = NULL;
			p->openDest = 0;
			rc = sqlite3BtreeOpen(NULL, p->fullName, p->pDestDb,
			    &p->pDest,
			    SQLITE_DEFAULT_CACHE_SIZE | SQLITE_OPEN_MAIN_DB,
			    p->pDestDb->openFlags);
			p->pDestDb->aDb[p->iDb].pBt = p->pDest;
			if (p->pDest) {
				p->pDestDb->aDb[p->iDb].pSchema = 
				    sqlite3SchemaGet(p->pDestDb, p->pDest);
				if (p->pDestDb->aDb[p->iDb].pSchema == NULL)
					rc = SQLITE_NOMEM;
			}
			if (rc == SQLITE_OK)
				p->pDest->pBt->db_oflags |= DB_CREATE;

#ifdef SQLITE_HAS_CODEC
			if (rc == SQLITE_OK) {
				if (p->iDb == 0)
					rc = sqlite3_key(p->pDestDb,
					    p->pSrc->pBt->encrypt_pwd,
					    p->pSrc->pBt->encrypt_pwd_len);
				else
					rc = sqlite3CodecAttach(p->pDestDb,
					    p->iDb, p->pSrc->pBt->encrypt_pwd,
					    p->pSrc->pBt->encrypt_pwd_len);
			}
#endif
		}
	}
	if (p->rc != SQLITE_LOCKED && p->rc != SQLITE_BUSY) {
		if (p->fullName != 0)
			sqlite3_free(p->fullName);
		p->fullName = NULL;
	}
	p->lastUpdate = p->pSrc->updateDuringBackup;
	return rc;
}
Example #20
0
/*
** Close a intarray table cursor.
*/
static int intarrayClose(sqlite3_vtab_cursor *cur){
  intarray_cursor *pCur = (intarray_cursor *)cur;
  sqlite3_free(pCur);
  return SQLITE_OK;
}
Example #21
0
/*
** Destroy a tokenizer
*/
static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  sqlite3_free(p);
  return SQLITE_OK;
}
Example #22
0
/*
** Free an sqlite3_intarray object.
*/
static void intarrayFree(sqlite3_intarray *p){
  if( p->xFree ){
    p->xFree(p->a);
  }
  sqlite3_free(p);
}
Example #23
0
static int
apply_repo_change(struct pkgdb *db, const char *database,
		  const struct repo_changes *repo_changes, const char *updown,
		  int version, int *next_version)
{
	const struct repo_changes	*change;
	bool			 found = false;
	int			 ret = EPKG_OK;
	char			 sql[BUFSIZ];
	char			*errmsg;

	for (change = repo_changes; change->version != -1; change++) {
		if (change->version == version) {
			found = true;
			break;
		}
	}
	if (!found) {
		pkg_emit_error("Failed to %s \"%s\" repo schema "
			" version %d (target version %d) "
			"-- change not found", updown, database, version,
			REPO_SCHEMA_VERSION);
		return (EPKG_FATAL);
	}

	/* substitute the repo database name */
	ret = substitute_into_sql(sql, sizeof(sql), change->sql, database);

	/* begin transaction */
	if (ret == EPKG_OK)
		ret = pkgdb_transaction_begin(db->sqlite, NULL);

	/* apply change */
	if (ret == EPKG_OK) {
		ret = sqlite3_exec(db->sqlite, sql, NULL, NULL, &errmsg);
		if (ret != SQLITE_OK) {
			pkg_emit_error("sqlite: %s", errmsg);
			sqlite3_free(errmsg);
			ret = EPKG_FATAL;
		}
	}

	/* update repo user_version */
	if (ret == EPKG_OK) {
		*next_version = change->next_version;
		ret = set_repo_user_version(db->sqlite, database, *next_version);
	}

	/* commit or rollback */
	if (ret == EPKG_OK)
		ret = pkgdb_transaction_commit(db->sqlite, NULL);
	else
		pkgdb_transaction_rollback(db->sqlite, NULL);

	if (ret == EPKG_OK) {
		pkg_emit_notice("Repo \"%s\" %s schema %d to %d: %s",
				database, updown, version,
				change->next_version, change->message);
	}

	return (ret);
}
Example #24
0
/*
** Table destructor for the intarray module.
*/
static int intarrayDestroy(sqlite3_vtab *p){
  intarray_vtab *pVtab = (intarray_vtab*)p;
  sqlite3_free(pVtab);
  return 0;
}
bool QgsNewSpatialiteLayerDialog::apply()
{
  // Build up the sql statement for creating the table
  QString sql = QStringLiteral( "create table %1(" ).arg( quotedIdentifier( leLayerName->text() ) );
  QString delim;

  if ( checkBoxPrimaryKey->isChecked() )
  {
    sql += QLatin1String( "pkuid integer primary key autoincrement" );
    delim = QStringLiteral( "," );
  }

  QTreeWidgetItemIterator it( mAttributeView );
  while ( *it )
  {
    sql += delim + QStringLiteral( "%1 %2" ).arg( quotedIdentifier( ( *it )->text( 0 ) ), ( *it )->text( 1 ) );
    delim = QStringLiteral( "," );
    ++it;
  }
  // complete the create table statement
  sql += ')';

  QgsDebugMsg( QStringLiteral( "Creating table in database %1" ).arg( mDatabaseComboBox->currentText() ) );
  QgsDebugMsg( sql );

  spatialite_database_unique_ptr database;
  int rc = database.open( mDatabaseComboBox->currentText() );
  if ( rc != SQLITE_OK )
  {
    QMessageBox::warning( this,
                          tr( "SpatiaLite Database" ),
                          tr( "Unable to open the database: %1" ).arg( mDatabaseComboBox->currentText() ) );
    return false;
  }

  char *errmsg = nullptr;

  // create the table
  rc = sqlite3_exec( database.get(), sql.toUtf8(), nullptr, nullptr, &errmsg );
  if ( rc != SQLITE_OK )
  {
    QMessageBox::warning( this,
                          tr( "Error Creating SpatiaLite Table" ),
                          tr( "Failed to create the SpatiaLite table %1. The database returned:\n%2" ).arg( leLayerName->text(), errmsg ) );
    sqlite3_free( errmsg );
    return false;
  }

  // create the geometry column and the spatial index
  if ( mGeometryTypeBox->currentIndex() != 0 )
  {
    QString sqlAddGeom = QStringLiteral( "select AddGeometryColumn(%1,%2,%3,%4,%5)" )
                         .arg( QgsSqliteUtils::quotedString( leLayerName->text() ),
                               QgsSqliteUtils::quotedString( leGeometryColumn->text() ) )
                         .arg( mCrsId.split( ':' ).value( 1, QStringLiteral( "0" ) ).toInt() )
                         .arg( QgsSqliteUtils::quotedString( selectedType() ) )
                         .arg( QgsSqliteUtils::quotedString( selectedZM() ) );
    QgsDebugMsg( sqlAddGeom );

    rc = sqlite3_exec( database.get(), sqlAddGeom.toUtf8(), nullptr, nullptr, &errmsg );
    if ( rc != SQLITE_OK )
    {
      QMessageBox::warning( this,
                            tr( "Error Creating Geometry Column" ),
                            tr( "Failed to create the geometry column. The database returned:\n%1" ).arg( errmsg ) );
      sqlite3_free( errmsg );
      return false;
    }

    QString sqlCreateIndex = QStringLiteral( "select CreateSpatialIndex(%1,%2)" )
                             .arg( QgsSqliteUtils::quotedString( leLayerName->text() ),
                                   QgsSqliteUtils::quotedString( leGeometryColumn->text() ) );
    QgsDebugMsg( sqlCreateIndex );

    rc = sqlite3_exec( database.get(), sqlCreateIndex.toUtf8(), nullptr, nullptr, &errmsg );
    if ( rc != SQLITE_OK )
    {
      QMessageBox::warning( this,
                            tr( "Error Creating Spatial Index" ),
                            tr( "Failed to create the spatial index. The database returned:\n%1" ).arg( errmsg ) );
      sqlite3_free( errmsg );
      return false;
    }
  }

  const QgsVectorLayer::LayerOptions options { QgsProject::instance()->transformContext() };
  QgsVectorLayer *layer = new QgsVectorLayer( QStringLiteral( "dbname='%1' table='%2'%3 sql=" )
      .arg( mDatabaseComboBox->currentText(),
            leLayerName->text(),
            mGeometryTypeBox->currentIndex() != 0 ? QStringLiteral( "(%1)" ).arg( leGeometryColumn->text() ) : QString() ),
      leLayerName->text(), QStringLiteral( "spatialite" ), options );
  if ( layer->isValid() )
  {
    // Reload connections to refresh browser panel
    QgisApp::instance()->reloadConnections();

    // register this layer with the central layers registry
    QList<QgsMapLayer *> myList;
    myList << layer;
    //addMapLayers returns a list of all successfully added layers
    //so we compare that to our original list.
    if ( myList == QgsProject::instance()->addMapLayers( myList ) )
      return true;
  }
  else
  {
    QgsDebugMsg( leLayerName->text() + " is an invalid layer - not loaded" );
    QMessageBox::critical( this, tr( "SpatiaLite Database" ), tr( "%1 is an invalid layer and cannot be loaded." ).arg( leLayerName->text() ) );
    delete layer;
  }

  return false;
}
Example #26
0
/*
 * Open a BFILE
 */
static void BFileOpenFunc(
	sqlite3_context *context,
	int argc,
	sqlite3_value **argv)
{
	int rc;
	sqlite3 *db;		/* db handle */
	int loc_size;		/* BFile locater size */
	int fd;			/* file descriptor */
	char *pLoc;		/* BFile locater */
	char *full_path;	/* full path */
	BfileHdl *pHdl;		/* BFile handle */

	assert(context != NULL && argc == 1 && argv != NULL);
	full_path = NULL, pHdl = NULL;
	fd = -1;

	loc_size = sqlite3_value_bytes(argv[0]);
	if (loc_size <= strlen(BFILE_PREFIX)) {
		sqlite3_result_int(context, 0);
		return;
	}

	db = (sqlite3 *)sqlite3_user_data(context);
	pLoc = (char *)sqlite3_value_text(argv[0]);
	assert(db != NULL && pLoc != NULL);

	rc = get_full_path(db, pLoc, loc_size, &full_path);
	if (rc)
		goto err;

	fd = open(full_path, O_RDONLY);
	if (fd == -1) {
		if (errno == ENOENT)
		    sqlite3_result_int(context, 0);
		else
		    rc = -1;
		goto err;
	}

	pHdl = sqlite3_malloc(sizeof(BfileHdl));
	if (pHdl == NULL) {
		rc = SQLITE_NOMEM;
		goto err;
	}

	memset(pHdl, 0, sizeof(BfileHdl));
	pHdl->full_path = full_path;
	pHdl->fd = fd;
	sqlite3_result_int(context, (int)pHdl);
	return;

err:
	if (rc == SQLITE_NOMEM)
		sqlite3_result_error_nomem(context);
	else if (rc)
		sqlite3_result_error(context, "internal error", -1);

	if (pHdl != NULL)
		sqlite3_free(pHdl);

	if (fd >= 0)
		close(fd);

	if (full_path != NULL)
		sqlite3_free(full_path);
}
Example #27
0
int main(int argc, char **argv)
{
    char *dev = argv[1];
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;
	char *file = NULL;
	sqlite3 *db;
	char *zErrMsg = 0;
	int  rc;
	char *sql;
	
    if(argc<=2)
    {
        printf ("usage : %s capture_device \n", argv[0]);
        exit (1);
    }
	file =  argv[2];
	
	
	//pcap initialisation
    handle = pcap_open_live (dev, BUFSIZ, 0, -1, errbuf);

    if (handle == NULL)
    {
        printf ("pcap_open_live : %s\n", errbuf);
        exit (1);
    }
	
	
	
	/* Open database */
	rc = sqlite3_open(file, &db);
	if( rc ){
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		exit(0);
	}else{
		fprintf(stdout, "Opened database successfully\n");
	}
	//create database table 
	sql = "CREATE TABLE IF NOT EXISTS mac_log (" \
		"id INTEGER  PRIMARY KEY  AUTOINCREMENT NOT NULL," \
		"mac CHAR(17)  NOT NULL ," \
		"date datetime NOT NULL " \
		");";
	
	rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
	if( rc != SQLITE_OK ){
	fprintf(stderr, "SQL error: %s\n", zErrMsg);
	  sqlite3_free(zErrMsg);
	}else{
	  fprintf(stdout, "Table created successfully\n");
	}
	
	
	
    printf ("\nStarting Capture ...........\n");
	// tell pcap to pass on captures frames to our packet_decoder fn
    //pcap_loop(handle, -1, packet_decoder, null);
	pcap_loop(handle, -1, packet_decoder_db, (u_char *)db);
	
	sqlite3_close(db);
    return (0);
}
Example #28
0
/*
** Advance a cursor to its next row of output
*/
static int amatchNext(sqlite3_vtab_cursor *cur){
  amatch_cursor *pCur = (amatch_cursor*)cur;
  amatch_word *pWord = 0;
  amatch_avl *pNode;
  int isMatch = 0;
  amatch_vtab *p = pCur->pVtab;
  int nWord;
  int rc;
  int i;
  const char *zW;
  amatch_rule *pRule;
  char *zBuf = 0;
  char nBuf = 0;
  char zNext[8];
  char zNextIn[8];
  int nNextIn;

  if( p->pVCheck==0 ){
    char *zSql;
    if( p->zVocabLang && p->zVocabLang[0] ){
      zSql = sqlite3_mprintf(
          "SELECT \"%w\" FROM \"%w\"",
          " WHERE \"%w\">=?1 AND \"%w\"=?2"
          " ORDER BY 1",
          p->zVocabWord, p->zVocabTab,
          p->zVocabWord, p->zVocabLang
      );
    }else{
      zSql = sqlite3_mprintf(
          "SELECT \"%w\" FROM \"%w\""
          " WHERE \"%w\">=?1"
          " ORDER BY 1",
          p->zVocabWord, p->zVocabTab,
          p->zVocabWord
      );
    }
    rc = sqlite3_prepare_v2(p->db, zSql, -1, &p->pVCheck, 0);
    sqlite3_free(zSql);
    if( rc ) return rc;
  }
  sqlite3_bind_int(p->pVCheck, 2, pCur->iLang);

  do{
    pNode = amatchAvlFirst(pCur->pCost);
    if( pNode==0 ){
      pWord = 0;
      break;
    }
    pWord = pNode->pWord;
    amatchAvlRemove(&pCur->pCost, &pWord->sCost);

#ifdef AMATCH_TRACE_1
    printf("PROCESS [%s][%.*s^%s] %d (\"%s\" \"%s\")\n",
       pWord->zWord+2, pWord->nMatch, pCur->zInput, pCur->zInput+pWord->nMatch,
       pWord->rCost, pWord->zWord, pWord->zCost);
#endif
    nWord = (int)strlen(pWord->zWord+2);
    if( nWord+20>nBuf ){
      nBuf = nWord+100;
      zBuf = sqlite3_realloc(zBuf, nBuf);
      if( zBuf==0 ) return SQLITE_NOMEM;
    }
    amatchStrcpy(zBuf, pWord->zWord+2);
    zNext[0] = 0;
    zNextIn[0] = pCur->zInput[pWord->nMatch];
    if( zNextIn[0] ){
      for(i=1; i<=4 && (pCur->zInput[pWord->nMatch+i]&0xc0)==0x80; i++){
        zNextIn[i] = pCur->zInput[pWord->nMatch+i];
      }
      zNextIn[i] = 0;
      nNextIn = i;
    }else{
      nNextIn = 0;
    }

    if( zNextIn[0] && zNextIn[0]!='*' ){
      sqlite3_reset(p->pVCheck);
      amatchStrcat(zBuf, zNextIn);
      sqlite3_bind_text(p->pVCheck, 1, zBuf, nWord+nNextIn, SQLITE_STATIC);
      rc = sqlite3_step(p->pVCheck);
      if( rc==SQLITE_ROW ){
        zW = (const char*)sqlite3_column_text(p->pVCheck, 0);
        if( strncmp(zBuf, zW, nWord+nNextIn)==0 ){
          amatchAddWord(pCur, pWord->rCost, pWord->nMatch+nNextIn, zBuf, "");
        }
      }
      zBuf[nWord] = 0;
    }

    while( 1 ){
      amatchStrcpy(zBuf+nWord, zNext);
      sqlite3_reset(p->pVCheck);
      sqlite3_bind_text(p->pVCheck, 1, zBuf, -1, SQLITE_TRANSIENT);
      rc = sqlite3_step(p->pVCheck);
      if( rc!=SQLITE_ROW ) break;
      zW = (const char*)sqlite3_column_text(p->pVCheck, 0);
      amatchStrcpy(zBuf+nWord, zNext);
      if( strncmp(zW, zBuf, nWord)!=0 ) break;
      if( (zNextIn[0]=='*' && zNextIn[1]==0)
       || (zNextIn[0]==0 && zW[nWord]==0)
      ){
        isMatch = 1;
        zNextIn[0] = 0;
        nNextIn = 0;
        break;
      }
      zNext[0] = zW[nWord];
      for(i=1; i<=4 && (zW[nWord+i]&0xc0)==0x80; i++){
        zNext[i] = zW[nWord+i];
      }
      zNext[i] = 0;
      zBuf[nWord] = 0;
      if( p->rIns>0 ){
        amatchAddWord(pCur, pWord->rCost+p->rIns, pWord->nMatch, 
                      zBuf, zNext);
      }
      if( p->rSub>0 ){
        amatchAddWord(pCur, pWord->rCost+p->rSub, pWord->nMatch+nNextIn, 
                      zBuf, zNext);
      }
      if( p->rIns<0 && p->rSub<0 ) break;
      zNext[i-1]++;  /* FIX ME */
    }
    sqlite3_reset(p->pVCheck);

    if( p->rDel>0 ){
      zBuf[nWord] = 0;
      amatchAddWord(pCur, pWord->rCost+p->rDel, pWord->nMatch+nNextIn,
                    zBuf, "");
    }

    for(pRule=p->pRule; pRule; pRule=pRule->pNext){
      if( pRule->iLang!=pCur->iLang ) continue;
      if( strncmp(pRule->zFrom, pCur->zInput+pWord->nMatch, pRule->nFrom)==0 ){
        amatchAddWord(pCur, pWord->rCost+pRule->rCost,
                      pWord->nMatch+pRule->nFrom, pWord->zWord+2, pRule->zTo);
      }
    }
  }while( !isMatch );
  pCur->pCurrent = pWord;
  sqlite3_free(zBuf);
  return SQLITE_OK;
}
Example #29
0
static tb_bool_t tb_database_sqlite3_done(tb_database_sql_impl_t* database, tb_char_t const* sql)
{
    // check
    tb_database_sqlite3_t* sqlite = tb_database_sqlite3_cast(database);
    tb_assert_and_check_return_val(sqlite && sqlite->database && sql, tb_false);

    // done
    tb_bool_t ok = tb_false;
    do
    {
        // exit result first if exists
        if (sqlite->result.result) sqlite3_free_table(sqlite->result.result);
        sqlite->result.result = tb_null;

        // clear the lasr statement first
        sqlite->result.statement = tb_null;

        // clear the result row count first
        sqlite->result.count = 0;

        // clear the result col count first
        sqlite->result.row.count = 0;

        // done sql
        tb_int_t    row_count = 0;
        tb_int_t    col_count = 0;
        tb_char_t*  error = tb_null;
        if (SQLITE_OK != sqlite3_get_table(sqlite->database, sql, &sqlite->result.result, &row_count, &col_count, &error))
        {
            // save state
            sqlite->base.state = tb_database_sqlite3_state_from_errno(sqlite3_errcode(sqlite->database));

            // trace
            tb_trace_e("done: sql: %s failed, error[%d]: %s", sql, sqlite3_errcode(sqlite->database), error);

            // exit error
            if (error) sqlite3_free(error);
            break;
        }

        // no result?
        if (!row_count)
        {
            // exit result
            if (sqlite->result.result) sqlite3_free_table(sqlite->result.result);
            sqlite->result.result = tb_null;

            // trace
            tb_trace_d("done: sql: %s: ok", sql);

            // ok
            ok = tb_true;
            break;
        }

        // save the result iterator mode
        sqlite->result.itor.mode = TB_ITERATOR_MODE_RACCESS | TB_ITERATOR_MODE_READONLY;

        // save result row count
        sqlite->result.count = row_count;

        // save result col count
        sqlite->result.row.count = col_count;

        // trace
        tb_trace_d("done: sql: %s: ok", sql);

        // ok
        ok = tb_true;
    
    } while (0);
    
    // ok?
    return ok;
}
Example #30
0
int main(int argc, char **argv) {
	if(argc < 2 || 0 == strcmp(argv[1],"--help") || 0 == strcmp(argv[1], "-h")) {
		fprintf(stderr, "Usage: %s <dbname> [metadb]\n", argv[0]);
		exit(1);
	}

	sqlite3 *db = NULL;
	int rc;
	char *dbname = argv[1];
	rc = sqlite3_open_v2(dbname, &db, SQLITE_OPEN_READONLY, NULL);
	if(SQLITE_OK != rc) {
		fprintf(stderr, "Can't open database %s (%i): %s\n", dbname, rc, sqlite3_errmsg(db));
		sqlite3_close(db);
		exit(1);
	}

	int have_meta = 0;
	if(argc > 2) {
		char attach_sql[1024];
		char *exec_errmsg;
		snprintf(attach_sql,sizeof(attach_sql),"ATTACH \"%s\" AS meta", argv[2]);
		rc = sqlite3_exec(db, attach_sql, NULL, NULL, &exec_errmsg);
		if(SQLITE_OK != rc) {
			fprintf(stderr, "Error attaching meta db (%i): %s\n", rc, exec_errmsg);
			sqlite3_free(exec_errmsg);
			sqlite3_close(db);
			exit(1);
		}
		have_meta = 1;
	}

	const char *tbl_list_sql = "SELECT tbl_name,NULL AS label,NULL AS color,NULL AS clusterid "
		"FROM sqlite_master WHERE type='table'";
	if(have_meta) {
		tbl_list_sql = "SELECT sqlite_master.tbl_name AS tbl_name, meta.cluster.label AS label, meta.cluster.color AS color, meta.cluster.clusterid AS clusterid \n"
			"FROM sqlite_master \n"
			"LEFT JOIN meta.tbl_cluster ON sqlite_master.tbl_name=meta.tbl_cluster.tbl_name \n"
			"LEFT JOIN meta.cluster ON meta.tbl_cluster.clusterid=meta.cluster.clusterid \n"
			"LEFT JOIN meta.ignorelist ON sqlite_master.tbl_name=meta.ignorelist.tbl_name \n"
			"WHERE meta.ignorelist.tbl_name IS NULL \n"
			"       AND main.sqlite_master.type='table'\n"
			"GROUP BY sqlite_master.tbl_name\n"
			"ORDER BY meta.cluster.clusterid\n";
	}
	sqlite3_stmt *tbl_list_stmt;

	// fprintf(stderr, "%s\n", tbl_list_sql);

	rc = sqlite3_prepare_v2(db, tbl_list_sql, -1, &tbl_list_stmt, NULL);
	if(SQLITE_OK != rc) {
		fprintf(stderr, "Can't prepare table list statement (%i): %s\n", rc, sqlite3_errmsg(db));
		sqlite3_close(db);
		exit(1);
	}

	printf("digraph sqliteschema {\n");
	printf("node [shape=plaintext];\n");

	if(have_meta) {
		const char settings_sql[] = "SELECT setting FROM meta.graphsettings";
		sqlite3_stmt *settings_stmt;
		rc = sqlite3_prepare_v2(db, settings_sql, -1, &settings_stmt, NULL);
		if(SQLITE_OK != rc) {
			fprintf(stderr, "Warning: Cannot find meta.graphsettings (%i): %s\n", rc, sqlite3_errmsg(db));
		} else {
			while(SQLITE_ROW == (rc = sqlite3_step(settings_stmt))) {
				printf("%s\n", sqlite3_column_text(settings_stmt,0));
			}
			sqlite3_finalize(settings_stmt);
		}
	} else {
		printf("rankdir=LR\n");
		printf("splines=true\n");
		printf("overlap=scale\n");
	}

	const int cols = 4;

	int curr_cluster = -1;
	while(SQLITE_ROW == (rc = sqlite3_step(tbl_list_stmt))) {
		const char *tbl_name = (char *)sqlite3_column_text(tbl_list_stmt, 0);

		int cluster_id = SQLITE_NULL==sqlite3_column_type(tbl_list_stmt,3)?-1:sqlite3_column_int(tbl_list_stmt,3);
		if(cluster_id != curr_cluster && curr_cluster != -1) {
			printf("}\n");
		}
		if(cluster_id != curr_cluster && cluster_id != -1) {
			printf("subgraph cluster_%i {\n", cluster_id);
			if(SQLITE_NULL!=sqlite3_column_type(tbl_list_stmt,1)) {
				printf("label=\"%s\"\n", sqlite3_column_text(tbl_list_stmt,1));
			}
			if(SQLITE_NULL!=sqlite3_column_type(tbl_list_stmt,2)) {
				printf("color=\"%s\"\n", sqlite3_column_text(tbl_list_stmt,2));
			}
		}
		curr_cluster=cluster_id;

		char *tbl_info_sql = sqlite3_mprintf("PRAGMA table_info(%q)", tbl_name);
		sqlite3_stmt *tbl_info_stmt;

		rc = sqlite3_prepare_v2(db, tbl_info_sql, -1, &tbl_info_stmt, NULL);
		if(SQLITE_OK != rc) {
			fprintf(stderr, "Can't prepare table info statement on table %s (%i): %s\n", tbl_name, rc, sqlite3_errmsg(db));
			sqlite3_close(db);
			exit(1);
		}

		printf("%s [label=<<TABLE CELLSPACING=\"0\"><TR><TD COLSPAN=\"%i\"><U>%s</U></TD></TR>", tbl_name, cols, tbl_name);
		int curr_row = 0;
		int in_brace = 0;
		while(SQLITE_ROW == (rc = sqlite3_step(tbl_info_stmt))) {
			if(0 == curr_row%cols) {
				in_brace = 1;
				printf("<TR>");
			}
			printf("<TD PORT=\"%s\">%s</TD>",
				sqlite3_column_text(tbl_info_stmt, 1),
				sqlite3_column_text(tbl_info_stmt, 1));
			curr_row++;
			if(0 == curr_row%cols) {
				in_brace = 0;
				printf("</TR>");
			}
		}
		if(in_brace) {
			printf("</TR>");
		}
		printf("</TABLE>>];\n");

		sqlite3_free(tbl_info_sql);
		sqlite3_finalize(tbl_info_stmt);

	}
	if(curr_cluster != -1) {
		printf("}\n");
	}

	sqlite3_reset(tbl_list_stmt);
	while(SQLITE_ROW == (rc = sqlite3_step(tbl_list_stmt))) {
		const char *tbl_name = (char *)sqlite3_column_text(tbl_list_stmt, 0);

		char *fkey_info_sql = sqlite3_mprintf("PRAGMA foreign_key_list(%q)", tbl_name);
		sqlite3_stmt *fkey_info_stmt;

		rc = sqlite3_prepare_v2(db, fkey_info_sql, -1, &fkey_info_stmt, NULL);
		if(SQLITE_OK != rc) {
			fprintf(stderr, "Can't prepare foreign key statement on table %s (%i): %s\n", tbl_name, rc, sqlite3_errmsg(db));
			sqlite3_close(db);
			exit(1);
		}

		while(SQLITE_ROW == (rc = sqlite3_step(fkey_info_stmt))) {
			printf("%s:%s -> %s:%s;\n",
				tbl_name,
				sqlite3_column_text(fkey_info_stmt, 3),
				sqlite3_column_text(fkey_info_stmt, 2),
				sqlite3_column_text(fkey_info_stmt, 4));
		}

		sqlite3_free(fkey_info_sql);
		sqlite3_finalize(fkey_info_stmt);
	}

	printf("}\n");

	sqlite3_finalize(tbl_list_stmt);
	sqlite3_close(db);

	return 0;
}