Beispiel #1
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 = contextMalloc(context, ((i64)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);
    }
  }
}
static
void OGRSQLITE_hstore_get_value(sqlite3_context* pContext,
                                CPL_UNUSED int argc,
                                sqlite3_value** argv)
{
    if( sqlite3_value_type (argv[0]) != SQLITE_TEXT ||
        sqlite3_value_type (argv[1]) != SQLITE_TEXT )
    {
        sqlite3_result_null (pContext);
        return;
    }

    const char* pszHStore = (const char*)sqlite3_value_text(argv[0]);
    const char* pszSearchedKey = (const char*)sqlite3_value_text(argv[1]);
    char* pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    if( pszValue != NULL )
        sqlite3_result_text( pContext, pszValue, -1, CPLFree );
    else
        sqlite3_result_null( pContext );
}
Beispiel #3
0
/*
** Implementation of the substr() function.
**
** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
** p1 is 1-indexed.  So substr(x,1,1) returns the first character
** of x.  If x is text, then we actually count UTF-8 characters.
** If x is a blob, then we count bytes.
**
** If p1 is negative, then we begin abs(p1) from the end of x[].
*/
static void substrFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const unsigned char *z;
  const unsigned char *z2;
  int len;
  int p0type;
  i64 p1, p2;

  assert( argc==3 );
  p0type = sqlite3_value_type(argv[0]);
  if( p0type==SQLITE_BLOB ){
    len = sqlite3_value_bytes(argv[0]);
    z = sqlite3_value_blob(argv[0]);
    if( z==0 ) return;
    assert( len==sqlite3_value_bytes(argv[0]) );
  }else{
    z = sqlite3_value_text(argv[0]);
    if( z==0 ) return;
    len = 0;
    for(z2=z; *z2; len++){
      SQLITE_SKIP_UTF8(z2);
    }
  }
  p1 = sqlite3_value_int(argv[1]);
  p2 = sqlite3_value_int(argv[2]);
  if( p1<0 ){
    p1 += len;
    if( p1<0 ){
      p2 += p1;
      p1 = 0;
    }
  }else if( p1>0 ){
    p1--;
  }
  if( p1+p2>len ){
    p2 = len-p1;
  }
  if( p0type!=SQLITE_BLOB ){
    while( *z && p1 ){
      SQLITE_SKIP_UTF8(z);
      p1--;
    }
    for(z2=z; *z2 && p2; p2--){
      SQLITE_SKIP_UTF8(z2);
    }
    sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
  }else{
    if( p2<0 ) p2 = 0;
    sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
  }
}
Beispiel #4
0
/**************************** sqlite3_value_  *******************************
** The following routines extract information from a Mem or sqlite3_value
** structure.
*/
const void *sqlite3_value_blob(sqlite3_value *pVal){
  Mem *p = (Mem*)pVal;
  if( p->flags & (MEM_Blob|MEM_Str) ){
    sqlite3VdbeMemExpandBlob(p);
    p->flags &= ~MEM_Str;
    p->flags |= MEM_Blob;
    return p->n ? p->z : 0;
  }else{
    return sqlite3_value_text(pVal);
  }
}
Beispiel #5
0
/*
 * unsigned int v; // count the number of bits set in v
 * unsigned int c; // c accumulates the total bits set in v
 * for (c = 0; v; c++)
 * {
 *   v &= v - 1; // clear the least significant bit set
 *   }
 */
extern void my_bit_count(sqlite3_context * context,
                         int               argc,
                         sqlite3_value  ** argv) {
    int             i;
    char           *binstring;
    unsigned char  *val;
    int             sz;
    unsigned int    v;
    unsigned int    cnt = 0;
    unsigned int    c;
    int             ok = 1;
        
    _ksu_null_if_null_param(argc, argv);
    binstring = (char *)sqlite3_value_text(argv[0]);
    if (*binstring == 'b') {
      binstring++;
      while (ok && *binstring) {
        switch(*binstring) {
           case '0':
                break;
           case '1':
                cnt++;
                break;
           default: // Not a binary string representation
                cnt = 0;
                ok = 0;
                break;
        }
        binstring++;
      }
      if (ok) {
        sqlite3_result_int(context, cnt);
        return;
      }
    }
    if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER) {
       v = (unsigned int)sqlite3_value_int(argv[0]);
       // Brian Kernighan's method
       for (cnt = 0; v; cnt++) {
          v &= v - 1; // clear the least significant bit set
       }
    } else {
       sz = sqlite3_value_bytes(argv[0]);
       val = (unsigned char *)sqlite3_value_blob(argv[0]);
       for (i = 0; i < sz; i++) {
         v = (unsigned int)val[i];
         for (c = 0; v; c++) {
           v &= v - 1;
         }
         cnt += c;
       }
    }
    sqlite3_result_int(context, cnt);
} 
Beispiel #6
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') -> '\u131' (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;            /* Pointer to input string */
  UChar *zOutput = 0;             /* Pointer to output buffer */
  int nInput;                     /* Size of utf-16 input string in bytes */
  int nOut;                       /* Size of output buffer in bytes */
  int cnt;
  int bToUpper;                   /* True for toupper(), false for tolower() */
  UErrorCode status;
  const char *zLocale = 0;

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

  zInput = sqlite3_value_text16(apArg[0]);
  if( !zInput ){
    return;
  }
  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  if( nOut==0 ){
    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
    return;
  }

  for(cnt=0; cnt<2; cnt++){
    UChar *zNew = sqlite3_realloc(zOutput, nOut);
    if( zNew==0 ){
      sqlite3_free(zOutput);
      sqlite3_result_error_nomem(p);
      return;
    }
    zOutput = zNew;
    status = U_ZERO_ERROR;
    if( bToUpper ){
      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
    }else{
      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
    }

    if( U_SUCCESS(status) ){
      sqlite3_result_text16(p, zOutput, nOut, xFree);
    }else if( status==U_BUFFER_OVERFLOW_ERROR ){
      assert( cnt==0 );
      continue;
    }else{
      icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
    }
    return;
  }
  assert( 0 );     /* Unreachable */
}
static void listStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  Ltx *p;
  int i;
  std::string d="";

  if( argc<1 ) 
     return;

  p = (Ltx *) sqlite3_aggregate_context(context, sizeof(*p));
  if ( p->cnt == 0)
    {
      if (sscntL >= MAXSSL )
        { 
	  fprintf(stderr,"Above in listStep increase MAXSSL size\n");
          exit(1);
	}
    p->sscnt=sscntL;
    sscntL++;
    ssL[p->sscnt].str("");
    ssL[p->sscnt] << "(";
    }	else {

      d=",";
    }



  p->cnt++;   
  //ssL[p->sscnt] << "(" <<  p->cnt<< "," << sqlite3_value_text(argv[0]) << ")";
  ssL[p->sscnt] << d <<  sqlite3_value_text(argv[0]);
  d=",";

  if (p->cnt == 1)
   {
    for(i=1; i< argc; ++i) {
     p->cnt++;
     ssL[p->sscnt] << d  << sqlite3_value_text(argv[i]) ;
      }
    }
}
Beispiel #8
0
static void scoreFunc(
    sqlite3_context *context,
    int argc,
    sqlite3_value **argv
) {
    const char* needle = sqlite3_value_text(argv[0]);
    const char* haystack = sqlite3_value_text(argv[1]);
    int match1 = -1, match1_len, needle_len;
    match_fuzzy(needle, haystack, &match1, &match1_len, &needle_len);
    if (match1 == -1) {
        sqlite3_result_int(context, 0);
        return;
    }

    if (needle_len == match1_len) { // exact match
        sqlite3_result_int(context, score_exact(
            match1, match1_len, haystack
        ));
        return;
    }

    int best = score_fuzzy(match1, match1_len, haystack);
    int last_index_of_dot = -1, i;
    for (i = 0; haystack[i] != 0; ++i) {
        if (haystack[i] == '.') last_index_of_dot = i;
    }
    if (last_index_of_dot != -1) {
        int match2 = -1, match2_len;
        match_fuzzy(
            needle, haystack + last_index_of_dot + 1, &match2, &match2_len,
            0
        );
        if (match2 != -1) {
            best = max(best,
                score_fuzzy(match2, match2_len, haystack + last_index_of_dot + 1)
            );
        }
    }
    sqlite3_result_int(context, best);
}
/*
** Implementation of the SQL scalar function for accessing the underlying 
** hash table. This function may be called as follows:
**
**   SELECT <function-name>(<key-name>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
**
** If the <pointer> argument is specified, it must be a blob value
** containing a pointer to be stored as the hash data corresponding
** to the string <key-name>. If <pointer> is not specified, then
** the string <key-name> must already exist in the has table. Otherwise,
** an error is returned.
**
** Whether or not the <pointer> argument is specified, the value returned
** is a blob containing the pointer stored as the hash data corresponding
** to string <key-name> (after the hash-table is updated, if applicable).
*/
static void scalarFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  Fts3Hash *pHash;
  void *pPtr = 0;
  const unsigned char *zName;
  int nName;

  assert( argc==1 || argc==2 );

  pHash = (Fts3Hash *)sqlite3_user_data(context);

  zName = sqlite3_value_text(argv[0]);
  nName = sqlite3_value_bytes(argv[0])+1;

  if( argc==2 ){
#ifdef SQLITE_ENABLE_FTS3_TOKENIZER
    void *pOld;
    int n = sqlite3_value_bytes(argv[1]);
    if( zName==0 || n!=sizeof(pPtr) ){
      sqlite3_result_error(context, "argument type mismatch", -1);
      return;
    }
    pPtr = *(void **)sqlite3_value_blob(argv[1]);
    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
    if( pOld==pPtr ){
      sqlite3_result_error(context, "out of memory", -1);
      return;
    }
#else
    sqlite3_result_error(context, "fts3tokenize: " 
        "disabled - rebuild with -DSQLITE_ENABLE_FTS3_TOKENIZER", -1
    );
    return;
#endif /* SQLITE_ENABLE_FTS3_TOKENIZER */
  }else
  {
    if( zName ){
      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
    }
    if( !pPtr ){
      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
      sqlite3_result_error(context, zErr, -1);
      sqlite3_free(zErr);
      return;
    }
  }

  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
}
/* wrapper for Jaro-Winkler string comparison */
void jarowinkler_wrapper(sqlite3_context *ctx, int n_values, sqlite3_value **value)
{
	// check for NULL values, return NULL if any of the input strings is NULL
	if(sqlite3_value_type(value[0]) == SQLITE_NULL || 
  	 sqlite3_value_type(value[1]) == SQLITE_NULL)
  {
		sqlite3_result_null(ctx);
		return;
	}
  const unsigned char *str1 = sqlite3_value_text(value[0]);
  const unsigned char *str2 = sqlite3_value_text(value[1]);
	#ifdef DEBUG
 	  Rprintf("String 1: %s\n", str1);
		Rprintf("String 2: %s\n", str2);
	#endif
  double result;
  result = jarowinkler_core(str1, str2, 1.0/3, 1.0/3, 1.0/3, 0.5);
	#ifdef DEBUG
  	Rprintf("Ergebnis des Stringvergleichs: %f\n", result);
  #endif
  sqlite3_result_double(ctx, result);
}
Beispiel #11
0
void function(sqlite3_context* ctx, int nargs, sqlite3_value** values)
{
    int i; const char *msg;

    fprintf(stdout, "function() : Called with %i arguments\n", nargs);

    for(i=0; i < nargs; i++) {
        fprintf( stdout, "    arg %i: value=%-7s type=%i\n", i, 
                 sqlite3_value_text(values[i]), 
                 sqlite3_value_type(values[i]));
    }

    if(strcmp(sqlite3_value_text(values[0]), "fail") == 0) {
        msg = "function() : Failing because you told me to.";
        sqlite3_result_error(ctx, msg, strlen(msg));
        fprintf(stdout, "\n");
        return;
    }

    fprintf(stdout, "\n");
    sqlite3_result_int(ctx, 0);
}
Beispiel #12
0
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  unsigned char *z;
  int i;
  if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
  z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
  if( z==0 ) return;
  strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
  for(i=0; z[i]; i++){
    z[i] = tolower(z[i]);
  }
  sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
  sqliteFree(z);
}
Beispiel #13
0
/**************************** sqlite3_value_  *******************************
** The following routines extract information from a Mem or sqlite3_value
** structure.
*/
const void *sqlite3_value_blob(sqlite3_value *pVal){
  Mem *p = (Mem*)pVal;
  if( p->flags & (MEM_Blob|MEM_Str) ){
    if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
      assert( p->flags==MEM_Null && p->z==0 );
      return 0;
    }
    p->flags |= MEM_Blob;
    return p->n ? p->z : 0;
  }else{
    return sqlite3_value_text(pVal);
  }
}
static
void OGR2SQLITE_ogr_SetConfigOption(sqlite3_context* pContext,
                                    int argc, sqlite3_value** argv)
{
    if( sqlite3_value_type (argv[0]) != SQLITE_TEXT )
    {
        sqlite3_result_null (pContext);
        return;
    }
    if( sqlite3_value_type (argv[1]) != SQLITE_TEXT &&
            sqlite3_value_type (argv[1]) != SQLITE_NULL )
    {
        sqlite3_result_null (pContext);
        return;
    }

    const char* pszKey = (const char*)sqlite3_value_text(argv[0]);
    const char* pszVal = (sqlite3_value_type (argv[1]) == SQLITE_TEXT) ?
                         (const char*)sqlite3_value_text(argv[1]) : NULL;
    CPLSetConfigOption(pszKey, pszVal);
    sqlite3_result_null (pContext);
}
Beispiel #15
0
/*
** This function is used by SQL generated to implement the 
** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
** CREATE INDEX command. The second is a table name. The table name in 
** the CREATE TABLE or CREATE INDEX statement is replaced with the second
** argument and the result returned. Examples:
**
** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
**     -> 'CREATE TABLE def(a, b, c)'
**
** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
**     -> 'CREATE INDEX i ON def(a, b, c)'
*/
static void renameTableFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  unsigned char const *zSql = sqlite3_value_text(argv[0]);
  unsigned char const *zTableName = sqlite3_value_text(argv[1]);

  int token;
  Token tname;
  unsigned char const *zCsr = zSql;
  int len = 0;
  char *zRet;

  /* The principle used to locate the table name in the CREATE TABLE 
  ** statement is that the table name is the first token that is immediatedly
  ** followed by a left parenthesis - TK_LP.
  */
  if( zSql ){
    do {
      /* Store the token that zCsr points to in tname. */
      tname.z = zCsr;
      tname.n = len;

      /* Advance zCsr to the next token. Store that token type in 'token',
      ** and it's length in 'len' (to be used next iteration of this loop).
      */
      do {
        zCsr += len;
        len = sqlite3GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP );

    zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
  }
}
void sqlite_regexp(sqlite3_context* context, int argc, sqlite3_value** values) {
	int ret;
	regex_t regex;
	char* reg = (char*)sqlite3_value_text(values[0]);
	char* text = (char*)sqlite3_value_text(values[1]);

	if ( argc != 2 || reg == 0 || text == 0) {
		sqlite3_result_error(context, "SQL function regexp() called with invalid arguments.\n", -1);
		return;
	}

	ret = regcomp(&regex, reg, REG_EXTENDED | REG_NOSUB);
	if ( ret != 0 ) {
		sqlite3_result_error(context, "error compiling regular expression", -1);
		return;
	}

	ret = regexec(&regex, text , 0, NULL, 0);
	regfree(&regex);

	sqlite3_result_int(context, (ret != REG_NOMATCH));
}
Beispiel #17
0
/*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A LIKE B
**
** is implemented as like(B, A). If there is an escape character E, 
**
**       A LIKE B ESCAPE E
**
** is mapped to like(B, A, E).
*/
static void icuLikeFunc(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  const unsigned char *zA = sqlite3_value_text(argv[0]);
  const unsigned char *zB = sqlite3_value_text(argv[1]);
  UChar32 uEsc = 0;

  /* Limit the length of the LIKE or GLOB pattern to avoid problems
  ** of deep recursion and N*N behavior in patternCompare().
  */
  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
    return;
  }


  if( argc==3 ){
    /* The escape character string must consist of a single UTF-8 character.
    ** Otherwise, return an error.
    */
    int nE= sqlite3_value_bytes(argv[2]);
    const unsigned char *zE = sqlite3_value_text(argv[2]);
    int i = 0;
    if( zE==0 ) return;
    U8_NEXT(zE, i, nE, uEsc);
    if( i!=nE){
      sqlite3_result_error(context, 
          "ESCAPE expression must be a single character", -1);
      return;
    }
  }

  if( zA && zB ){
    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  }
}
Beispiel #18
0
/*
** Return UTF-8 encoded English language explanation of the most recent
** error.
*/
const char *sqlite3_errmsg(sqlite3 *db){
  const char *z;
  if( sqlite3_malloc_failed ){
    return sqlite3ErrStr(SQLITE_NOMEM);
  }
  if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
    return sqlite3ErrStr(SQLITE_MISUSE);
  }
  z = sqlite3_value_text(db->pErr);
  if( z==0 ){
    z = sqlite3ErrStr(db->errCode);
  }
  return z;
}
ikptr
ik_sqlite3_value_text (ikptr s_value, ikpcb * pcb)
{
#ifdef HAVE_SQLITE3_VALUE_TEXT
  sqlite3_value *	value = IK_SQLITE_VALUE(s_value);
  const void *		data;
  int			bytes;
  bytes = sqlite3_value_bytes(value);
  data  = sqlite3_value_text(value);
  return ika_bytevector_from_memory_block(pcb, data, bytes);
#else
  feature_failure(__func__);
#endif
}
Beispiel #20
0
/*
  Get the last n characters from a string
 This is motivated by pulling the year from the end of a string such as
   USA:22 September 1986 
 to get 1986
 */
void 
lastNChars(sqlite3_context *context, int argc, sqlite3_value **argv)
{
    const char * str;
    const char *ptr;
    str = sqlite3_value_text(argv[0]);
    int n = sqlite3_value_int(argv[1]);
    int len = strlen(str);
    if(n > 0) {
        n = MIN(len, n);
	ptr = str +  len - n ;
	sqlite3_result_text(context, ptr, -1, SQLITE_TRANSIENT);
    }
}
Beispiel #21
0
void
ActionLog::apply_action_xFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
  ActionLog* the = reinterpret_cast<ActionLog*>(sqlite3_user_data(context));

  if (argc != 11) {
    sqlite3_result_error(context, "``apply_action'' expects 10 arguments", -1);
    return;
  }

  Buffer device_name(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0]));
  sqlite3_int64 seq_no = sqlite3_value_int64(argv[1]);
  int action = sqlite3_value_int(argv[2]);
  std::string filename = reinterpret_cast<const char*>(sqlite3_value_text(argv[3]));
  sqlite3_int64 version = sqlite3_value_int64(argv[4]);

  _LOG_TRACE("apply_function called with " << argc);
  _LOG_TRACE("device_name: " << Name(Block(reinterpret_cast<const char*>(device_name.buf()),
                                           device_name.size()))
                             << ", action: "
                             << action
                             << ", file: "
                             << filename);

  if (action == 0) // update
  {
    Buffer hash(sqlite3_value_blob(argv[5]), sqlite3_value_bytes(argv[5]));
    time_t atime = static_cast<time_t>(sqlite3_value_int64(argv[6]));
    time_t mtime = static_cast<time_t>(sqlite3_value_int64(argv[7]));
    time_t ctime = static_cast<time_t>(sqlite3_value_int64(argv[8]));
    int mode = sqlite3_value_int(argv[9]);
    int seg_num = sqlite3_value_int(argv[10]);

    _LOG_DEBUG("Update " << filename << " " << atime << " " << mtime << " " << ctime << " "
                         << toHex(hash));

    the->m_fileState->UpdateFile(filename, version, hash, device_name, seq_no, atime, mtime, ctime,
                                 mode, seg_num);

    // no callback here
  }
  else if (action == 1) // delete
  {
    the->m_fileState->DeleteFile(filename);

    the->m_onFileRemoved(filename);
  }

  sqlite3_result_null(context);
}
  SQLITE_EXTENSION_INIT1
#endif

#include "fts3Int.h"
#include <assert.h>
#include <string.h>

static void scalarFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  Fts3Hash *pHash;
  void *pPtr = 0;
  const unsigned char *zName;
  int nName;

  assert( argc==1 || argc==2 );

  pHash = (Fts3Hash *)sqlite3_user_data(context);

  zName = sqlite3_value_text(argv[0]);
  nName = sqlite3_value_bytes(argv[0])+1;

  if( argc==2 ){
    void *pOld;
    int n = sqlite3_value_bytes(argv[1]);
    if( n!=sizeof(pPtr) ){
      sqlite3_result_error(context, "argument type mismatch", -1);
      return;
    }
    pPtr = *(void **)sqlite3_value_blob(argv[1]);
    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
    if( pOld==pPtr ){
      sqlite3_result_error(context, "out of memory", -1);
      return;
    }
  }else{
    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
    if( !pPtr ){
      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
      sqlite3_result_error(context, zErr, -1);
      sqlite3_free(zErr);
      return;
    }
  }

  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
}
Beispiel #23
0
extern void pg_bool_or_step(sqlite3_context *context,
                            int              argc,
                            sqlite3_value  **argv) {
  CONTEXT_T *ctx;
  int        typ;
  int        val;

  typ = sqlite3_value_type(argv[0]);
  if (typ != SQLITE_NULL) {
    if (typ == SQLITE_INTEGER) {
      val = sqlite3_value_int(argv[0]);
      if ((val != 0) && (val != 1)) {
        ksu_err_msg(context, KSU_ERR_INV_DATATYPE, "bool_or");
        return;
      }
    } else {
      char *p = (char *)sqlite3_value_text(argv[0]);
      int   len = strlen(p);

      if (len == 1) {
        if (toupper(*p) == 'T') {
          val = 1;
        } else if (toupper(*p) == 'F') {
          val = 0;
        } else {
          ksu_err_msg(context, KSU_ERR_INV_DATATYPE, "bool_or");
          return;
        }
      } else if (strcasecmp(p, "true") == 0) {
        val = 1;
      } else if (strcasecmp(p, "false") == 0) {
        val = 0;
      } else {
        ksu_err_msg(context, KSU_ERR_INV_DATATYPE, "bool_or");
        return;
      }
    }
    val = sqlite3_value_int64(argv[0]);
    ctx = (CONTEXT_T *)sqlite3_aggregate_context(context, sizeof(CONTEXT_T));
    if (ctx) {
      if (ctx->n == 0) {
        ctx->boolval = val;
      } else {
        ctx->boolval |= val;
      }
      (ctx->n)++;
    }
  }
}
Beispiel #24
0
/*
** Return UTF-8 encoded English language explanation of the most recent
** error.
*/
const char *sqlite3_errmsg(sqlite3 *db){
  const char *z;
  assert( !sqlite3MallocFailed() );
  if( !db ){
    return sqlite3ErrStr(SQLITE_NOMEM);
  }
  if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
    return sqlite3ErrStr(SQLITE_MISUSE);
  }
  z = (char*)sqlite3_value_text(db->pErr);
  if( z==0 ){
    z = sqlite3ErrStr(db->errCode);
  }
  return z;
}
static
void OGR2SQLITE_ogr_version(sqlite3_context* pContext,
                            int argc, sqlite3_value** argv)
{
    if( argc == 0 || sqlite3_value_type (argv[0]) != SQLITE_TEXT )
    {
        sqlite3_result_text( pContext, GDAL_RELEASE_NAME, -1, SQLITE_STATIC );
    }
    else
    {
        sqlite3_result_text( pContext,
                             GDALVersionInfo((const char*)sqlite3_value_text(argv[0])),
                             -1, SQLITE_TRANSIENT );
    }
}
Beispiel #26
0
/*
** Implementation of the scalar function icu_load_collation().
**
** This scalar function is used to add ICU collation based collation 
** types to an SQLite database connection. It is intended to be called
** as follows:
**
**     SELECT icu_load_collation(<locale>, <collation-name>);
**
** Where <locale> is a string containing an ICU locale identifier (i.e.
** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
** collation sequence to create.
*/
static void icuLoadCollation(
  sqlite3_context *p, 
  int nArg, 
  sqlite3_value **apArg
){
  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  UErrorCode status = U_ZERO_ERROR;
  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
  UCollator *pUCollator;    /* ICU library collation object */
  int rc;                   /* Return code from sqlite3_create_collation_x() */

  assert(nArg==2);
  (void)nArg; /* Unused parameter */
  zLocale = (const char *)sqlite3_value_text(apArg[0]);
  zName = (const char *)sqlite3_value_text(apArg[1]);

  if( !zLocale || !zName ){
    return;
  }

  pUCollator = ucol_open(zLocale, &status);
  if( !U_SUCCESS(status) ){
    icuFunctionError(p, "ucol_open", status);
    return;
  }
  assert(p);

  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
      icuCollationColl, icuCollationDel
  );
  if( rc!=SQLITE_OK ){
    ucol_close(pUCollator);
    sqlite3_result_error(p, "Error registering collation function", -1);
  }
}
Beispiel #27
0
/*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A LIKE B
**
** is implemented as like(B,A).
**
** If the pointer retrieved by via a call to sqlite3_user_data() is
** not NULL, then this function uses UTF-16. Otherwise UTF-8.
*/
static void likeFunc(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  const unsigned char *zA = sqlite3_value_text(argv[0]);
  const unsigned char *zB = sqlite3_value_text(argv[1]);
  int escape = 0;
  if( argc==3 ){
    /* The escape character string must consist of a single UTF-8 character.
    ** Otherwise, return an error.
    */
    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
    if( sqlite3utf8CharLen(zEsc, -1)!=1 ){
      sqlite3_result_error(context, 
          "ESCAPE expression must be a single character", -1);
      return;
    }
    escape = sqlite3ReadUtf8(zEsc);
  }
  if( zA && zB ){
    sqlite3_result_int(context, patternCompare(zA, zB, &likeInfo, escape));
  }
}
Beispiel #28
0
extern void  my_dayofweek(sqlite3_context * context,
                          int               argc,
                          sqlite3_value ** argv) {
   KSU_TIME_T  t;
   KSU_TM_T   *tmptr;
   KSU_TM_T    mydate;

   _ksu_null_if_null_param(argc, argv);
   if (my_is_datetime((const char *)sqlite3_value_text(argv[0]), &t, 0)
       && ((tmptr = ksu_localtime(t, &mydate)) != (KSU_TM_T *)NULL)) {
     sqlite3_result_int(context, 1 + (int)tmptr->wday);
   } else {
     sqlite3_result_null(context);
   }
}
Beispiel #29
0
/*
** If a row with rowid iDel is present in the %_content table, add the
** delete-markers to the FTS index necessary to delete it. Do not actually
** remove the %_content row at this time though.
*/
static int fts5StorageDeleteFromIndex(
  Fts5Storage *p, 
  i64 iDel, 
  sqlite3_value **apVal
){
  Fts5Config *pConfig = p->pConfig;
  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
  int rc;                         /* Return code */
  int rc2;                        /* sqlite3_reset() return code */
  int iCol;
  Fts5InsertCtx ctx;

  if( apVal==0 ){
    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
    if( rc!=SQLITE_OK ) return rc;
    sqlite3_bind_int64(pSeek, 1, iDel);
    if( sqlite3_step(pSeek)!=SQLITE_ROW ){
      return sqlite3_reset(pSeek);
    }
  }

  ctx.pStorage = p;
  ctx.iCol = -1;
  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
    if( pConfig->abUnindexed[iCol-1]==0 ){
      const char *zText;
      int nText;
      if( pSeek ){
        zText = (const char*)sqlite3_column_text(pSeek, iCol);
        nText = sqlite3_column_bytes(pSeek, iCol);
      }else{
        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
        nText = sqlite3_value_bytes(apVal[iCol-1]);
      }
      ctx.szCol = 0;
      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, 
          zText, nText, (void*)&ctx, fts5StorageInsertCallback
      );
      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
    }
  }
  p->nTotalRow--;

  rc2 = sqlite3_reset(pSeek);
  if( rc==SQLITE_OK ) rc = rc2;
  return rc;
}
static void delete_file(sqlite3_context * context, int argc, sqlite3_value ** argv)
{
    if (argc != 1) {
        sqlite3_result_int(context, 0);
        return;
    }

    char const * path = (char const *)sqlite3_value_text(argv[0]);
    // Don't allow ".." in paths
    if (path == NULL || strstr(path, "/../") != NULL) {
        sqlite3_result_null(context);
        return;
    }

    // We only allow deleting files in the EXTERNAL_STORAGE path, or one of the
    // SECONDARY_STORAGE paths
    bool good_path = false;
    char const * external_storage = getenv("EXTERNAL_STORAGE");
    if (external_storage && strncmp(external_storage, path, strlen(external_storage)) == 0) {
        good_path = true;
    } else {
        // check SECONDARY_STORAGE, which should be a colon separated list of paths
        char const * secondary_paths = getenv("SECONDARY_STORAGE");
        while (secondary_paths && secondary_paths[0]) {
            const char* colon = strchr(secondary_paths, ':');
            int length = (colon ? colon - secondary_paths : strlen(secondary_paths));
            if (strncmp(secondary_paths, path, length) == 0) {
                good_path = true;
            }
            secondary_paths += length;
            while (*secondary_paths == ':') secondary_paths++;
        }
    }

    if (!good_path) {
        sqlite3_result_null(context);
        return;
    }

    int err = unlink(path);
    if (err != -1) {
        // No error occured, return true
        sqlite3_result_int(context, 1);
    } else {
        // An error occured, return false
        sqlite3_result_int(context, 0);
    }
}