static geos_prepared_geometry_t *get_geos_prepared_geom(sqlite3_context *context, const geos_context_t *geos_context, sqlite3_value *value, errorstream_t *error) {
  geom_blob_header_t header;

  uint8_t *blob = (uint8_t *)sqlite3_value_blob(value);
  size_t blob_length = (size_t) sqlite3_value_bytes(value);

  if (blob == NULL) {
    return NULL;
  }

  binstream_t stream;
  binstream_init(&stream, blob, blob_length);

  geos_writer_t writer;
  geos_writer_init_srid(&writer, geos_context->geos_handle, header.srid);

  geos_context->spatialdb->read_blob_header(&stream, &header, error);
  geos_context->spatialdb->read_geometry(&stream, geos_writer_geom_consumer(&writer), error);

  GEOSGeometry *g = geos_writer_getgeometry(&writer);
  geos_writer_destroy(&writer, g == NULL);

  if (g == NULL) {
    return NULL;
  }

  struct GEOSPrepGeom_t const *prepared_g = GEOSPrepare_r(geos_context->geos_handle, g);
  if (prepared_g == NULL) {
    return NULL;
  }

  geos_prepared_geometry_t *result = sqlite3_malloc(sizeof(geos_prepared_geometry_t));
  if (result == NULL) {
    GEOSPreparedGeom_destroy_r(geos_context->geos_handle, prepared_g);
    return NULL;
  }

  result->context = geos_context->geos_handle;
  result->geometry = prepared_g;
  result->srid = header.srid;

  return result;
}
int bfp_to_blob(Bfp *pBfp, u8 **ppBlob, int *pLen)
{
  assert(pBfp);
  *ppBlob = 0;
  *pLen = 0;

  int rc = SQLITE_OK;

  *ppBlob = (u8 *)sqlite3_malloc(pBfp->size());
  if (*ppBlob) {
    memcpy(*ppBlob, pBfp->data(), pBfp->size());
    *pLen = pBfp->size();
  }
  else {
    rc = SQLITE_NOMEM;
  }

  return rc;
}
Example #3
0
/* 
** CSV virtual table module xColumn method.
*/
static int csvColumn(sqlite3_vtab_cursor *pVtabCursor, sqlite3_context *ctx, int i){
  CSV *pCSV = (CSV *)pVtabCursor->pVtab;

  if( i<0 || i>=pCSV->nCol ){
    sqlite3_result_null( ctx );
  }else{
    // TODO SQLite uses dynamic typing...
    const char *col = pCSV->aCols[i];
    if( !col ){
      sqlite3_result_null( ctx );
    }else if( pCSV->aEscapedQuotes[i] ){
      char *z;

      int nByte = (int)(strlen(col) - pCSV->aEscapedQuotes[i] + 1);
      if( nByte>sqlite3_limit(pCSV->db, SQLITE_LIMIT_LENGTH, -1) ){
        sqlite3_result_error_toobig( ctx );
        z = 0;
      }else{
        z = sqlite3_malloc( nByte );
        if( !z ){
          sqlite3_result_error_nomem( ctx );
        }
      }
      if( z ){
        int j,k;
        for(j=0, k=0; col[j]; j++){
          z[k++] = col[j];
          if( col[j]=='\"' ){
            /* unescape quote */
            j++;
          }
        }
        z[k] = 0;
        sqlite3_result_text( ctx, z, k, sqlite3_free ); // FIXME sqlite3_result_int64/double
      }
    }else{
      sqlite3_result_text( ctx, col, -1, SQLITE_TRANSIENT ); // FIXME sqlite3_result_int64/double
    }
  }

  return SQLITE_OK;
}
void qquncompress(sqlite3_context* context, int argc, sqlite3_value** argv)
{
#ifdef ZIP
    int len = sqlite3_value_bytes(argv[0]);
    unsigned char* msg = sqlite3_malloc(sizeof(unsigned char) * len);
    memcpy(msg, sqlite3_value_blob(argv[0]), len);

    unsigned long destlen;
    unsigned char* msg2 = qq_uncompress(msg, &destlen, len);
    sqlite3_free(msg);

    sqlite3_result_blob(context, msg2, destlen, sqlite3_free);
#else
    const char* msg = sqlite3_value_text(argv[0]);

    char* msg2 = base64_decode((char*) msg);

    sqlite3_result_text(context, msg2, strlen(msg2), sqlite3_free);
#endif
}
Example #5
0
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  char *z1;
  const char *z2;
  int i, n;
  if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = sqlite3_malloc(n+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = tolower(z1[i]);
      }
      sqlite3_result_text(context, z1, -1, sqlite3_free);
    }
  }
}
/*
** Extract all tokens from hash table iHash and link them into a list
** in sorted order. The hash table is cleared before returning. It is
** the responsibility of the caller to free the elements of the returned
** list.
*/
static int fts5HashEntrySort(
  Fts5Hash *pHash, 
  const char *pTerm, int nTerm,   /* Query prefix, if any */
  Fts5HashEntry **ppSorted
){
  const int nMergeSlot = 32;
  Fts5HashEntry **ap;
  Fts5HashEntry *pList;
  int iSlot;
  int i;

  *ppSorted = 0;
  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  if( !ap ) return SQLITE_NOMEM;
  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);

  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
    Fts5HashEntry *pIter;
    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
      if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
        Fts5HashEntry *pEntry = pIter;
        pEntry->pScanNext = 0;
        for(i=0; ap[i]; i++){
          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
          ap[i] = 0;
        }
        ap[i] = pEntry;
      }
    }
  }

  pList = 0;
  for(i=0; i<nMergeSlot; i++){
    pList = fts5HashEntryMerge(pList, ap[i]);
  }

  pHash->nEntry = 0;
  sqlite3_free(ap);
  *ppSorted = pList;
  return SQLITE_OK;
}
Example #7
0
void gbk(sqlite3_context *context,int argc,sqlite3_value **argv)
{
	if(argc == 1 && sqlite3_value_type(argv[0]) == SQLITE_TEXT)
	{ 
		const unsigned char* text = sqlite3_value_text(argv[0]);
		size_t textLen = sqlite3_value_bytes(argv[0]);

		size_t outLen = textLen * 4;
		char* out = (char*)sqlite3_malloc(outLen);
		char* pout = out;

		iconv_t handle = iconv_open("gbk","utf-8");
		memset(out,0,outLen);
		iconv(handle,(const char**)&text,&textLen,&pout,&outLen);
		iconv_close(handle);

		sqlite3_result_text(context,out,-1,SQLITE_TRANSIENT);

		sqlite3_free(out);
	}
}
Example #8
0
/*
** Implementation of the "compress(X)" SQL function.  The input X is
** compressed using zLib and the output is returned.
*/
static void sqlcmd_compress(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const unsigned char *pIn;
  unsigned char *pOut;
  unsigned int nIn;
  unsigned long int nOut;

  pIn = sqlite3_value_blob(argv[0]);
  nIn = sqlite3_value_bytes(argv[0]);
  nOut = 13 + nIn + (nIn+999)/1000;
  pOut = sqlite3_malloc( nOut+4 );
  pOut[0] = nIn>>24 & 0xff;
  pOut[1] = nIn>>16 & 0xff;
  pOut[2] = nIn>>8 & 0xff;
  pOut[3] = nIn & 0xff;
  compress(&pOut[4], &nOut, pIn, nIn);
  sqlite3_result_blob(context, pOut, nOut+4, sqlite3_free);
}
Example #9
0
static int weblog_open( sqlite3_vtab *vtab, sqlite3_vtab_cursor **cur )
{
    weblog_vtab     *v = (weblog_vtab*)vtab;
    weblog_cursor   *c;
    FILE            *fptr;

    *cur = NULL;

    fptr = fopen( v->filename, "r" );
    if ( fptr == NULL ) return SQLITE_ERROR;

    c = sqlite3_malloc( sizeof( weblog_cursor ) );
    if ( c == NULL ) {
        fclose( fptr );
        return SQLITE_NOMEM;
    }
    
    c->fptr = fptr;
    *cur = (sqlite3_vtab_cursor*)c;
    return SQLITE_OK;
}
Example #10
0
/*
** The hex() function.  Interpret the argument as a blob.  Return
** a hexadecimal rendering as text.
*/
static void hexFunc(
    sqlite3_context *context,
    int argc,
    sqlite3_value **argv
) {
    int i, n;
    const unsigned char *pBlob;
    char *zHex, *z;
    assert( argc==1 );
    pBlob = sqlite3_value_blob(argv[0]);
    n = sqlite3_value_bytes(argv[0]);
    z = zHex = sqlite3_malloc(n*2 + 1);
    if( zHex==0 ) return;
    for(i=0; i<n; i++, pBlob++) {
        unsigned char c = *pBlob;
        *(z++) = hexdigits[(c>>4)&0xf];
        *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
}
static int rehash(intarray_map *map) {
  int newsize = map->size + (map->size >> 1);
  int newlen = newsize * sizeof(intarray_map_entry);
  intarray_map_entry *newtable = (intarray_map_entry*)sqlite3_malloc(newlen);
  intarray_map_entry *t = map->hashtable;
  int i = 0;

  if (!newtable) return SQLITE_NOMEM;
  memset(newtable, 0, newlen);
  for (i = 0; i < map->size; i++) {
    if (t[i].key) {
      mapPut_(newtable, newsize, (sqlite3_intarray*)t[i].value, t[i].hash);
    }
  }
  map->rehashSize = map->size;
  map->size = newsize;
  map->hashtable = newtable;

  sqlite3_free(t);
  return SQLITE_OK;
}
Example #12
0
static char *
unquote(char const *in)
{
    char c, *ret;
    int i;

    ret = sqlite3_malloc(strlen(in) + 1);
    if (ret) {
	c = in[0];
	if ((c == '"') || (c == '\'')) {
	    i = strlen(in + 1);
	    if ((i > 0) && (in[i] == c)) {
		strcpy(ret, in + 1);
		ret[i - 1] = '\0';
		return ret;
	    }
	}
	strcpy(ret, in);
    }
    return ret;
}
Example #13
0
/*
** Usage:   btree_open FILENAME NCACHE
**
** Open a new database
*/
static int btree_open(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int rc, nCache;
  char zBuf[100];
  int n;
  char *zFilename;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " FILENAME NCACHE FLAGS\"", 0);
    return TCL_ERROR;
  }
  if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR;
  nRefSqlite3++;
  if( nRefSqlite3==1 ){
    sDb.pVfs = sqlite3_vfs_find(0);
    sDb.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    sqlite3_mutex_enter(sDb.mutex);
  }
  n = (int)strlen(argv[1]);
  zFilename = sqlite3_malloc( n+2 );
  if( zFilename==0 ) return TCL_ERROR;
  memcpy(zFilename, argv[1], n+1);
  zFilename[n+1] = 0;
  rc = sqlite3BtreeOpen(sDb.pVfs, zFilename, &sDb, &pBt, 0, 
     SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB);
  sqlite3_free(zFilename);
  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, sqlite3ErrName(rc), 0);
    return TCL_ERROR;
  }
  sqlite3BtreeSetCacheSize(pBt, nCache);
  sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pBt);
  Tcl_AppendResult(interp, zBuf, 0);
  return TCL_OK;
}
Example #14
0
/** Create auxiliary data for matchFunction, leaves ppAuxData NULL on pattern
 * failure */
void matchCreate(aux_pattern_data **ppAuxData, const unsigned char *pattern, int nPattern){
  /* Allocate a structure */
  *ppAuxData = (aux_pattern_data*)sqlite3_malloc(sizeof(aux_pattern_data) + nPattern + 1);

  /* Copy the pattern, including the null char */
  (*ppAuxData)->pattern = (unsigned char*)(*ppAuxData + 1);

  /* Let's figure out what kind of pattern we have */
  int offset = 0;
  if(strncmp((const char*)pattern, "substr:", 7) == 0){
    (*ppAuxData)->eType     = PATTERN_SUBSTR;
    (*ppAuxData)->pRegExp   = NULL;
    offset                  = 7;
  }else if(strncmp((const char*)pattern, "substr-extents:", 15) == 0){
    (*ppAuxData)->eType     = PATTERN_SUBSTR | PATTERN_EXTENTS;
    (*ppAuxData)->pRegExp   = NULL;
    offset                  = 15;
  }else if(strncmp((const char*)pattern, "regexp:", 7) == 0){
    (*ppAuxData)->eType = PATTERN_REGEXP;
    int rc              = regexpCompile(&(*ppAuxData)->pRegExp, pattern + 7, nPattern - 7);
    offset              = 7;
    assert(rc == SQLITE_OK);  /*Errors should be handled else where */
  }else if(strncmp((const char*)pattern, "regexp-extents:", 15) == 0){
    (*ppAuxData)->eType = PATTERN_REGEXP | PATTERN_EXTENTS;
    int rc              = regexpCompile(&(*ppAuxData)->pRegExp, pattern + 15, nPattern - 15);
    offset              = 15;
    assert(rc == SQLITE_OK);  /*Errors should be handled else where */
  /*}else if(strncmp(pattern, "egrep:", 6) == 0){ */
  /*  pAuxData->eType = PATTERN_REGEXP; */
  /*  pfxLen = 6; */
  }else{
    sqlite3_free(*ppAuxData);
    *ppAuxData = NULL;
    return;
  }

  memcpy((*ppAuxData)->pattern, pattern + offset, nPattern - offset);
  (*ppAuxData)->pattern[nPattern - offset] = '\0';
  (*ppAuxData)->nPattern = nPattern - offset;
}
Example #15
0
static int leafCursorCreate(Pager *pPager, unsigned nPageSize,
                            u32 iRootPage, RecoverLeafCursor **ppCursor){
  DbPage *pPage;               
  RecoverLeafCursor *pCursor;  
  int rc;

  
  rc = sqlite3PagerAcquire(pPager, iRootPage, &pPage, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  pCursor = sqlite3_malloc(sizeof(RecoverLeafCursor));
  if( !pCursor ){
    sqlite3PagerUnref(pPage);
    return SQLITE_NOMEM;
  }
  memset(pCursor, 0, sizeof(*pCursor));

  pCursor->nPageSize = nPageSize;

  rc = leafCursorLoadPage(pCursor, pPage);
  if( rc!=SQLITE_OK ){
    sqlite3PagerUnref(pPage);
    leafCursorDestroy(pCursor);
    return rc;
  }

  
  if( !pCursor->pPage ){
    rc = leafCursorNextPage(pCursor);
    if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ){
      leafCursorDestroy(pCursor);
      return rc;
    }
  }

  *ppCursor = pCursor;
  return SQLITE_OK;
}
Example #16
0
/*
** Gobble up the first bareword or quoted word from the input buffer zIn.
** Return a pointer to the character immediately following the last in
** the gobbled word if successful, or a NULL pointer otherwise (failed
** to find close-quote character).
**
** Before returning, set pzOut to point to a new buffer containing a
** nul-terminated, dequoted copy of the gobbled word. If the word was
** quoted, *pbQuoted is also set to 1 before returning.
**
** If *pRc is other than SQLITE_OK when this function is called, it is
** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
** set if a parse error (failed to find close quote) occurs.
*/
static const char *fts5ConfigGobbleWord(
  int *pRc,                       /* IN/OUT: Error code */
  const char *zIn,                /* Buffer to gobble string/bareword from */
  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
  int *pbQuoted                   /* OUT: Set to true if dequoting required */
){
  const char *zRet = 0;

  int nIn = (int)strlen(zIn);
  char *zOut = sqlite3_malloc(nIn+1);

  assert( *pRc==SQLITE_OK );
  *pbQuoted = 0;
  *pzOut = 0;

  if( zOut==0 ){
    *pRc = SQLITE_NOMEM;
  }else{
    memcpy(zOut, zIn, nIn+1);
    if( fts5_isopenquote(zOut[0]) ){
      int ii = fts5Dequote(zOut);
      zRet = &zIn[ii];
      *pbQuoted = 1;
    }else{
      zRet = fts5ConfigSkipBareword(zIn);
      if( zRet ){
        zOut[zRet-zIn] = '\0';
      }
    }
  }

  if( zRet==0 ){
    sqlite3_free(zOut);
  }else{
    *pzOut = zOut;
  }

  return zRet;
}
Example #17
0
/* Compute the filename for the iChunk-th chunk
*/
static int multiplexSubFilename(multiplexGroup *pGroup, int iChunk){
  if( iChunk>=pGroup->nReal ){
    struct multiplexReal *p;
    p = sqlite3_realloc(pGroup->aReal, (iChunk+1)*sizeof(*p));
    if( p==0 ){
      return SQLITE_NOMEM;
    }
    memset(&p[pGroup->nReal], 0, sizeof(p[0])*(iChunk+1-pGroup->nReal));
    pGroup->aReal = p;
    pGroup->nReal = iChunk+1;
  }
  if( pGroup->zName && pGroup->aReal[iChunk].z==0 ){
    char *z;
    int n = pGroup->nName;
    pGroup->aReal[iChunk].z = z = sqlite3_malloc( n+5 );
    if( z==0 ){
      return SQLITE_NOMEM;
    }
    multiplexFilename(pGroup->zName, pGroup->nName, pGroup->flags, iChunk, z);
  }
  return SQLITE_OK;
}
/*
** 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 unicodeOpen(
  sqlite3_tokenizer *p,           /* The tokenizer */
  const char *aInput,             /* Input string */
  int nInput,                     /* Size of string aInput in bytes */
  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
){
  unicode_tokenizer *pTokenizer;
  unicode_cursor *pCsr;

  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  if( pCsr==0 ){
    return SQLITE_NOMEM;
  }
  memset(pCsr, 0, sizeof(unicode_cursor));

  pCsr->aInput = (const unsigned char *)aInput;
  if( aInput==0 ){
    pCsr->nInput = 0;
  }else if( nInput<0 ){
    pCsr->nInput = (int)strlen(aInput);
  }else{
    pCsr->nInput = nInput;
  }

  pTokenizer = (unicode_tokenizer *)p;
  if ( pTokenizer->stemmer.create!=NULL ) {
     pCsr->pStemmer = pTokenizer->stemmer.create();
     if ( pCsr->pStemmer==0 ) {
	sqlite3_free(p);
	return SQLITE_NOMEM;
     }
  }else {
     pCsr->pStemmer = NULL;
  }

  *pp = &pCsr->base;
  UNUSED_PARAMETER(p);
  return SQLITE_OK;
}
Example #19
0
/** Create a trigram expression for matching against a single trigram */
int exprTrigram(expr **ppExpr, trilite_vtab *pTrgVtab, trilite_trigram trigram){
  int rc = SQLITE_OK;

  sqlite3_blob *pBlob;
  char *zTable = sqlite3_mprintf("%s_index", pTrgVtab->zName);
  /* Open the blob */
  rc = sqlite3_blob_open(pTrgVtab->db, pTrgVtab->zDb, zTable, "doclist", trigram, 0, &pBlob);
  sqlite3_free(zTable);

  /* If we didn't get a blob */
  if(rc != SQLITE_OK){
    *ppExpr = NULL;
    return SQLITE_OK;
  }
  /* Get size of blob */
  int nSize = sqlite3_blob_bytes(pBlob);

  /* Allocate space for expr and doclist at the same time */
  *ppExpr = (expr*)sqlite3_malloc(sizeof(expr) + nSize);

  /* Set the expr */
  (*ppExpr)->eType                 = EXPR_TRIGRAM;
  (*ppExpr)->expr.trigram.docList  = ((unsigned char*)(*ppExpr)) + sizeof(expr);
  (*ppExpr)->expr.trigram.nSize    = nSize;

  /* Read doclist into memory */
  sqlite3_blob_read(pBlob, (*ppExpr)->expr.trigram.docList, nSize, 0);

  /* Release blob */
  sqlite3_blob_close(pBlob);

  /* Read first id */
  int read = readVarInt((*ppExpr)->expr.trigram.docList, &(*ppExpr)->expr.trigram.curId);
  (*ppExpr)->expr.trigram.curId   += DELTA_LIST_OFFSET;
  (*ppExpr)->expr.trigram.nSize   -= read;
  (*ppExpr)->expr.trigram.docList += read;

  return rc;
}
Example #20
0
/*
** Create an "ascii" tokenizer.
*/
static int fts5AsciiCreate(
  void *pUnused, 
  const char **azArg, int nArg,
  Fts5Tokenizer **ppOut
){
  int rc = SQLITE_OK;
  AsciiTokenizer *p = 0;
  UNUSED_PARAM(pUnused);
  if( nArg%2 ){
    rc = SQLITE_ERROR;
  }else{
    p = sqlite3_malloc(sizeof(AsciiTokenizer));
    if( p==0 ){
      rc = SQLITE_NOMEM;
    }else{
      int i;
      memset(p, 0, sizeof(AsciiTokenizer));
      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
        const char *zArg = azArg[i+1];
        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
          fts5AsciiAddExceptions(p, zArg, 1);
        }else
        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
          fts5AsciiAddExceptions(p, zArg, 0);
        }else{
          rc = SQLITE_ERROR;
        }
      }
      if( rc!=SQLITE_OK ){
        fts5AsciiDelete((Fts5Tokenizer*)p);
        p = 0;
      }
    }
  }

  *ppOut = (Fts5Tokenizer*)p;
  return rc;
}
Example #21
0
/*
** Implementations of scalar functions for case mapping - upper() and 
** lower(). Function upper() converts its input to upper-case (ABC).
** Function lower() converts to lower-case (abc).
**
** ICU provides two types of case mapping, "general" case mapping and
** "language specific". Refer to ICU documentation for the differences
** between the two.
**
** To utilise "general" case mapping, the upper() or lower() scalar 
** functions are invoked with one argument:
**
**     upper('ABC') -> 'abc'
**     lower('abc') -> 'ABC'
**
** To access ICU "language specific" case mapping, upper() or lower()
** should be invoked with two arguments. The second argument is the name
** of the locale to use. Passing an empty string ("") or SQL NULL value
** as the second argument is the same as invoking the 1 argument version
** of upper() or lower().
**
**     lower('I', 'en_us') -> 'i'
**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
**
** http://www.icu-project.org/userguide/posix.html#case_mappings
*/
static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  const UChar *zInput;
  UChar *zOutput;
  int nInput;
  int nOutput;

  UErrorCode status = U_ZERO_ERROR;
  const char *zLocale = 0;

  assert(nArg==1 || nArg==2);
  if( nArg==2 ){
    zLocale = (const char *)sqlite3_value_text(apArg[1]);
  }

  zInput = sqlite3_value_text16(apArg[0]);
  if( !zInput ){
    return;
  }
  nInput = sqlite3_value_bytes16(apArg[0]);

  nOutput = nInput * 2 + 2;
  zOutput = sqlite3_malloc(nOutput);
  if( !zOutput ){
    return;
  }

  if( sqlite3_user_data(p) ){
    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  }else{
    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  }

  if( !U_SUCCESS(status) ){
    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
    return;
  }

  sqlite3_result_text16(p, zOutput, -1, xFree);
}
Example #22
0
/*
** Implementation of the "decompress(X)" SQL function.  The argument X
** is a blob which was obtained from compress(Y).  The output will be
** the value Y.
*/
static void sqlcmd_decompress(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const unsigned char *pIn;
  unsigned char *pOut;
  unsigned int nIn;
  unsigned long int nOut;
  int rc;

  pIn = sqlite3_value_blob(argv[0]);
  nIn = sqlite3_value_bytes(argv[0]);
  nOut = (pIn[0]<<24) + (pIn[1]<<16) + (pIn[2]<<8) + pIn[3];
  pOut = sqlite3_malloc( nOut+1 );
  rc = uncompress(pOut, &nOut, &pIn[4], nIn-4);
  if( rc==Z_OK ){
    sqlite3_result_blob(context, pOut, nOut, sqlite3_free);
  }else{
    sqlite3_result_error(context, "input is not zlib compressed", -1);
  }
}
Example #23
0
static int characterOpen(
                   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
                   const char *pInput, int nBytes,        /* String to be tokenized */
                   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
                   ){
    character_tokenizer_cursor *c;
    if(pInput == 0){
        nBytes = 0;
    }else if(nBytes < 0){
        nBytes = (int)strlen(pInput);
    }
    c = (character_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
    if(c == NULL){
        return SQLITE_NOMEM;
    }
    c->iToken = c->iPosition = 0;
    c->pToken = NULL;
    c->nBytes = nBytes;
    c->pInput = pInput;
    *ppCursor = &c->base;
    return SQLITE_OK;
}
Example #24
0
/*
** Usage:   btree_integrity_check ID ROOT ...
**
** Look through every page of the given BTree file to verify correct
** formatting and linkage.  Return a line of text for each problem found.
** Return an empty string if everything worked.
*/
static int btree_integrity_check(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  const char **argv      /* Text of each argument */
){
  Btree *pBt;
  int nRoot;
  int *aRoot;
  int i;
  int nErr;
  char *zResult;

  if( argc<3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " ID ROOT ...\"", 0);
    return TCL_ERROR;
  }
  pBt = sqlite3TestTextToPtr(argv[1]);
  nRoot = argc-2;
  aRoot = (int*)sqlite3_malloc( sizeof(int)*(argc-2) );
  for(i=0; i<argc-2; i++){
    if( Tcl_GetInt(interp, argv[i+2], &aRoot[i]) ) return TCL_ERROR;
  }
#ifndef SQLITE_OMIT_INTEGRITY_CHECK
  sqlite3BtreeEnter(pBt);
  zResult = sqlite3BtreeIntegrityCheck(pBt, aRoot, nRoot, 10000, &nErr);
  sqlite3BtreeLeave(pBt);
#else
  zResult = 0;
#endif
  sqlite3_free((void*)aRoot);
  if( zResult ){
    Tcl_AppendResult(interp, zResult, 0);
    sqlite3_free(zResult); 
  }
  return TCL_OK;
}
/*
** Create a new tokenizer instance.
*/
static int simpleCreate(
  int argc, const char * const *argv,
  sqlite3_tokenizer **ppTokenizer
){
  simple_tokenizer *t;

  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  if( t==NULL ) return SQLITE_NOMEM;
  memset(t, 0, sizeof(*t));

  /* TODO(shess) Delimiters need to remain the same from run to run,
  ** else we need to reindex.  One solution would be a meta-table to
  ** track such information in the database, then we'd only want this
  ** information on the initial create.
  */
  if( argc>1 ){
    int i, n = strlen(argv[1]);
    for(i=0; i<n; i++){
      unsigned char ch = argv[1][i];
      /* We explicitly don't support UTF-8 delimiters for now. */
      if( ch>=0x80 ){
        sqlite3_free(t);
        return SQLITE_ERROR;
      }
      t->delim[ch] = 1;
    }
  } else {
    /* Mark non-alphanumeric ASCII characters as delimiters */
    int i;
    for(i=1; i<0x80; i++){
      t->delim[i] = !((i>='0' && i<='9') || (i>='A' && i<='Z') ||
                      (i>='a' && i<='z'));
    }
  }

  *ppTokenizer = &t->base;
  return SQLITE_OK;
}
Example #26
0
/*
** Open a crash-file file handle.
**
** The caller will have allocated pVfs->szOsFile bytes of space
** at pFile. This file uses this space for the CrashFile structure
** and allocates space for the "real" file structure using 
** sqlite3_malloc(). The assumption here is (pVfs->szOsFile) is
** equal or greater than sizeof(CrashFile).
*/
static int cfOpen(
  sqlite3_vfs *pCfVfs,
  const char *zName,
  sqlite3_file *pFile,
  int flags,
  int *pOutFlags
){
  sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData;
  int rc;
  CrashFile *pWrapper = (CrashFile *)pFile;
  sqlite3_file *pReal = (sqlite3_file*)&pWrapper[1];

  memset(pWrapper, 0, sizeof(CrashFile));
  rc = sqlite3OsOpen(pVfs, zName, pReal, flags, pOutFlags);

  if( rc==SQLITE_OK ){
    i64 iSize;
    pWrapper->pMethod = &CrashFileVtab;
    pWrapper->zName = (char *)zName;
    pWrapper->pRealFile = pReal;
    rc = sqlite3OsFileSize(pReal, &iSize);
    pWrapper->iSize = (int)iSize;
  }
  if( rc==SQLITE_OK ){
    pWrapper->nData = (4096 + pWrapper->iSize);
    pWrapper->zData = sqlite3_malloc(pWrapper->nData);
    if( pWrapper->zData ){
      memset(pWrapper->zData, 0, pWrapper->nData);
      rc = sqlite3OsRead(pReal, pWrapper->zData, pWrapper->iSize, 0); 
    }else{
      rc = SQLITE_NOMEM;
    }
  }
  if( rc!=SQLITE_OK && pWrapper->pMethod ){
    sqlite3OsClose(pFile);
  }
  return rc;
}
Example #27
0
static int error_log_open( sqlite3_vtab *vtab, sqlite3_vtab_cursor **cur )
{
    error_log_vtab     *v = (error_log_vtab*)vtab;
    error_log_cursor   *c;
    gzFile            *fptr;
    char            *cmd;

    *cur = NULL;

    fptr = gzopen( v->filename, "rb" );

    if ( fptr == NULL ) return SQLITE_ERROR;

    c = sqlite3_malloc( sizeof( error_log_cursor ) );
    if ( c == NULL ) {
        gzclose( fptr );
        return SQLITE_NOMEM;
    }
    
    c->fptr = fptr;
    *cur = (sqlite3_vtab_cursor*)c;
    return SQLITE_OK;
}
Example #28
0
static int vt_open(sqlite3_vtab *p_svt, sqlite3_vtab_cursor **pp_cursor)
{
    vtab* p_vt         = (vtab*)p_svt;
    p_vt->base.zErrMsg = NULL;
    vtab_cursor *p_cur = (vtab_cursor*)sqlite3_malloc(sizeof(vtab_cursor));

    /* Allocate pools */
    apr_pool_create_ex(&p_cur->pool, p_vt->pool, NULL, NULL);
    apr_pool_create_ex(&p_cur->tmp_pool, p_vt->pool, NULL, NULL);

    /* Initialize the root node */

    p_cur->root_node         = malloc(sizeof(struct filenode));
    p_cur->root_node->parent = NULL;
    p_cur->root_node->path   = NULL;
    p_cur->current_node      = p_cur->root_node;
    p_cur->search_paths      = NULL;
    p_cur->root_path         = 0;

    *pp_cursor = (sqlite3_vtab_cursor*)p_cur;

    return (p_cur ? SQLITE_OK : SQLITE_NOMEM);
}
VALUE do_sqlite3_cExtension_load_extension(VALUE self, VALUE path) {
#ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION
  VALUE connection = rb_iv_get(self, "@connection");

  if (connection == Qnil) { return Qfalse; }

  // Retrieve the actual connection from the object
  VALUE sqlite3_connection = rb_iv_get(connection, "@connection");

  if (sqlite3_connection == Qnil) { return Qfalse; }

  sqlite3 *db;

  Data_Get_Struct(sqlite3_connection, sqlite3, db);

  const char *extension_path  = rb_str_ptr_readonly(path);
  char *errmsg = sqlite3_malloc(1024);

  if (!errmsg) {
    return Qfalse;
  }

  int status = sqlite3_load_extension(db, extension_path, 0, &errmsg);

  if (status != SQLITE_OK) {
    VALUE errexp = rb_exc_new2(eDO_ConnectionError, errmsg);

    sqlite3_free(errmsg);
    rb_exc_raise(errexp);
  }

  sqlite3_free(errmsg);
  return Qtrue;
#else
  return Qfalse;
#endif
}
Example #30
0
/*
    The goal of this version of close is different than that of sqlite3_close(), and is designed to lend itself better to .NET's non-deterministic finalizers and
    the GC thread.  SQLite will not close a database if statements are open on it -- but for our purposes, we'd rather finalize all active statements
    and forcibly close the database.  The reason is simple -- a lot of people don't Dispose() of their objects correctly and let the garbage collector
    do it.  This leads to unexpected behavior when a user thinks they've closed a database, but it's still open because not all the statements have
    hit the GC yet.

    So, here we have a problem ... .NET has a pointer to any number of sqlite3_stmt objects.  We can't call sqlite3_finalize() on these because
    their memory is freed and can be used for something else.  The GC thread could potentially try and call finalize again on the statement after
    that memory was deallocated.  BAD.  So, what we need to do is make a copy of each statement, and call finalize() on the copy -- so that the original
    statement's memory is preserved, and marked as BAD, but we can still manage to finalize everything and forcibly close the database.  Later when the 
    GC gets around to calling finalize_interop() on the "bad" statement, we detect that and finish deallocating the pointer.
*/
__declspec(dllexport) int WINAPI sqlite3_close_interop(sqlite3 *db)
{
  int ret = sqlite3_closeAndFreeMutex(db);

  if (ret == SQLITE_BUSY && db->pVdbe)
  {
    while (db->pVdbe)
    {
      // Make a copy of the first prepared statement
      Vdbe *p = (Vdbe *)sqlite3_malloc(sizeof(Vdbe));
      Vdbe *po = db->pVdbe;

      if (!p) return SQLITE_NOMEM;

      CopyMemory(p, po, sizeof(Vdbe));

      // Put it on the chain so we can free it
      db->pVdbe = p;
      ret = sqlite3_finalize((sqlite3_stmt *)p); // This will also free the copy's memory
      if (ret)
      {
        // finalize failed -- so we must put back anything we munged
        CopyMemory(po, p, sizeof(Vdbe));
        db->pVdbe = po;
        break;
      }
      else
      {
        ZeroMemory(po, sizeof(Vdbe));
        po->magic = VDBE_MAGIC_DEAD;
      }
    }
    ret = sqlite3_closeAndFreeMutex(db);
  }

  return ret;
}