Example #1
0
File: dbpage.c Project: cznic/cc
static int dbpageColumn(
  sqlite3_vtab_cursor *pCursor, 
  sqlite3_context *ctx, 
  int i
){
  DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  int rc = SQLITE_OK;
  switch( i ){
    case 0: {           /* pgno */
      sqlite3_result_int(ctx, pCsr->pgno);
      break;
    }
    case 1: {           /* data */
      DbPage *pDbPage = 0;
      rc = sqlite3PagerGet(pTab->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
      if( rc==SQLITE_OK ){
        sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pTab->szPage,
                            SQLITE_TRANSIENT);
      }
      sqlite3PagerUnref(pDbPage);
      break;
    }
    default: {          /* schema */
      sqlite3 *db = sqlite3_context_db_handle(ctx);
      sqlite3_result_text(ctx, db->aDb[pTab->iDb].zDbSName, -1, SQLITE_STATIC);
      break;
    }
  }
  return SQLITE_OK;
}
Example #2
0
File: shathree.c Project: cznic/cc
/*
** Implementation of the sha3(X,SIZE) function.
**
** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
** size is 256.  If X is a BLOB, it is hashed as is.  
** For all other non-NULL types of input, X is converted into a UTF-8 string
** and the string is hashed without the trailing 0x00 terminator.  The hash
** of a NULL value is NULL.
*/
static void sha3Func(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  SHA3Context cx;
  int eType = sqlite3_value_type(argv[0]);
  int nByte = sqlite3_value_bytes(argv[0]);
  int iSize;
  if( argc==1 ){
    iSize = 256;
  }else{
    iSize = sqlite3_value_int(argv[1]);
    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
      sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
                                    "384 512", -1);
      return;
    }
  }
  if( eType==SQLITE_NULL ) return;
  SHA3Init(&cx, iSize);
  if( eType==SQLITE_BLOB ){
    SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  }else{
    SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  }
  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
}
/*
 ** The implementation of the sqlite_record() function. This function accepts
 ** a single argument of any type. The return value is a formatted database
 ** record (a blob) containing the argument value.
 **
 ** This is used to convert the value stored in the 'sample' column of the
 ** sqlite_stat3 table to the record format SQLite uses internally.
 */
static void recordFunc(
                       sqlite3_context *context,
                       int argc,
                       sqlite3_value **argv
                       ){
    const int file_format = 1;
    int iSerial;                    /* Serial type */
    int nSerial;                    /* Bytes of space for iSerial as varint */
    int nVal;                       /* Bytes of space required for argv[0] */
    int nRet;
    sqlite3 *db;
    u8 *aRet;
    
    UNUSED_PARAMETER( argc );
    iSerial = sqlite3VdbeSerialType(argv[0], file_format);
    nSerial = sqlite3VarintLen(iSerial);
    nVal = sqlite3VdbeSerialTypeLen(iSerial);
    db = sqlite3_context_db_handle(context);
    
    nRet = 1 + nSerial + nVal;
    aRet = sqlite3DbMallocRaw(db, nRet);
    if( aRet==0 ){
        sqlite3_result_error_nomem(context);
    }else{
        aRet[0] = nSerial+1;
        sqlite3PutVarint(&aRet[1], iSerial);
        sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format);
        sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
        sqlite3DbFree(db, aRet);
    }
}
static
void OGR2SQLITE_ogr_inflate(sqlite3_context* pContext,
                            int argc, sqlite3_value** argv)
{
    if( argc != 1 ||
            sqlite3_value_type (argv[0]) != SQLITE_BLOB )
    {
        sqlite3_result_null (pContext);
        return;
    }

    size_t nOutBytes = 0;
    void* pOut;

    const void* pSrc = sqlite3_value_blob (argv[0]);
    int nLen = sqlite3_value_bytes (argv[0]);
    pOut = CPLZLibInflate( pSrc, nLen, NULL, 0, &nOutBytes);

    if( pOut != NULL )
    {
        sqlite3_result_blob (pContext, pOut, nOutBytes, VSIFree);
    }
    else
    {
        sqlite3_result_null (pContext);
    }

    return;
}
Example #5
0
SQLITE_EXTENSION_INIT1
#include <stdio.h>

/*
** Implementation of the "readfile(X)" SQL function.  The entire content
** of the file named X is read and returned as a BLOB.  NULL is returned
** if the file does not exist or is unreadable.
*/
static void readfileFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zName;
  FILE *in;
  long nIn;
  void *pBuf;

  zName = (const char*)sqlite3_value_text(argv[0]);
  if( zName==0 ) return;
  in = fopen(zName, "rb");
  if( in==0 ) return;
  fseek(in, 0, SEEK_END);
  nIn = ftell(in);
  rewind(in);
  pBuf = sqlite3_malloc( nIn );
  if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
    sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
  }else{
    sqlite3_free(pBuf);
  }
  fclose(in);
}
Example #6
0
static void fts5MatchinfoFunc(
  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
  Fts5Context *pFts,              /* First arg to pass to pApi functions */
  sqlite3_context *pCtx,          /* Context for returning result/error */
  int nVal,                       /* Number of values in apVal[] array */
  sqlite3_value **apVal           /* Array of trailing arguments */
){
  const char *zArg;
  Fts5MatchinfoCtx *p;
  int rc;

  if( nVal>0 ){
    zArg = (const char*)sqlite3_value_text(apVal[0]);
  }else{
    zArg = "pcx";
  }

  p = (Fts5MatchinfoCtx*)pApi->xGetAuxdata(pFts, 0);
  if( p==0 || sqlite3_stricmp(zArg, p->zArg) ){
    p = fts5MatchinfoNew(pApi, pFts, pCtx, zArg);
    pApi->xSetAuxdata(pFts, p, sqlite3_free);
    if( p==0 ) return;
  }

  rc = fts5MatchinfoIter(pApi, pFts, p, fts5MatchinfoLocalCb);
  if( rc!=SQLITE_OK ){
    sqlite3_result_error_code(pCtx, rc);
  }else{
    /* No errors has occured, so return a copy of the array of integers. */
    int nByte = p->nRet * sizeof(u32);
    sqlite3_result_blob(pCtx, (void*)p->aRet, nByte, SQLITE_TRANSIENT);
  }
}
Example #7
0
void geo_simplify(sqlite3_context *context,int argc,sqlite3_value **argv)
{
	if(argc == 2 && sqlite3_value_type(argv[0]) == SQLITE_BLOB)
	{ 
		GEOSGeometry* geometry;
		GEOSGeometry* simplify_geo;
		unsigned char* wkb;
		size_t size;
		const void* data = sqlite3_value_blob(argv[0]);
		size_t data_size = sqlite3_value_bytes(argv[0]);

		double tolerance = sqlite3_value_double(argv[1]);

		_init_geos();
		geometry = _geo_from_wkb((const unsigned char*)data,data_size);
		if(geometry != 0)
		{
			simplify_geo = GEOSSimplify(geometry,tolerance);
			if(simplify_geo != 0)
			{
				wkb = GEOSGeomToWKB_buf(simplify_geo,&size);
				sqlite3_result_blob(context,wkb,size,SQLITE_TRANSIENT);
				GEOSGeom_destroy(simplify_geo);
				GEOSFree(wkb);
			}
		}
		GEOSGeom_destroy(geometry);
		finishGEOS();
	}
}
static
void OGR2SQLITE_ST_AsBinary(sqlite3_context* pContext,
                            int argc, sqlite3_value** argv)
{
    OGRGeometry* poGeom = OGR2SQLITE_GetGeom(pContext, argc, argv, NULL);
    if( poGeom != NULL )
    {
        int nBLOBLen = poGeom->WkbSize();
        GByte* pabyGeomBLOB = (GByte*) VSIMalloc(nBLOBLen);
        if( pabyGeomBLOB != NULL )
        {
            if( poGeom->exportToWkb(wkbNDR, pabyGeomBLOB) == OGRERR_NONE )
                sqlite3_result_blob( pContext, pabyGeomBLOB, nBLOBLen, CPLFree);
            else
            {
                VSIFree(pabyGeomBLOB);
                sqlite3_result_null (pContext);
            }
        }
        else
            sqlite3_result_null (pContext);
        delete poGeom;
    }
    else
        sqlite3_result_null (pContext);
}
Example #9
0
static int sqlite_callback_return(Value v, sqlite3_context *ctx)
{
    const RefNode *r_type = fs->Value_type(v);
    if (r_type == fs->cls_int) {
        int err = FALSE;
        int64_t i64 = fs->Value_int64(v, &err);
        if (err) {
            fs->throw_errorf(mod_sqlite, "SQLiteError", "'INTEGER' out of range (-2^63 - 2^63-1)");
            return FALSE;
        }
        sqlite3_result_int64(ctx, i64);
    } else if (r_type == fs->cls_bool) {
        int i32 = Value_bool(v);
        sqlite3_result_int(ctx, i32);
    } else if (r_type == fs->cls_float) {
        double dval = Value_float2(v);
        sqlite3_result_double(ctx, dval);
    } else if (r_type == fs->cls_str) {
        RefStr *s = Value_vp(v);
        sqlite3_result_text(ctx, s->c, s->size, SQLITE_TRANSIENT);
    } else if (r_type == fs->cls_bytes) {
        RefStr *s = Value_vp(v);
        sqlite3_result_blob(ctx, s->c, s->size, SQLITE_TRANSIENT);
    } else if (r_type == fs->cls_null) {
        sqlite3_result_null(ctx);
    } else {
        fs->throw_errorf(fs->mod_lang, "TypeError", "Bool, Int, Float, Str, Bytes or Null required but %n", r_type);
        return FALSE;
    }
    return TRUE;
}
Example #10
0
static void _relation_compute(sqlite3_context *context,int argc,sqlite3_value **argv,RelationCompute Func)
{
	if(argc == 2 && sqlite3_value_type(argv[0]) == SQLITE_BLOB &&
		sqlite3_value_type(argv[1]) == SQLITE_BLOB)
	{ 
		GEOSGeometry* geometry1;
		GEOSGeometry* geometry2;
		GEOSGeometry* geo_result;
		unsigned char* wkb;
		size_t size;
		const void* data1 = sqlite3_value_blob(argv[0]);
		size_t data_size1 = sqlite3_value_bytes(argv[0]);

		const void* data2 = sqlite3_value_blob(argv[1]);
		size_t data_size2 = sqlite3_value_bytes(argv[1]);

		_init_geos();
		geometry1 = _geo_from_wkb((const unsigned char*)data1,data_size1);
		geometry2 = _geo_from_wkb((const unsigned char*)data2,data_size2);
		if(geometry1 != 0 && geometry2 != 0)
		{
			geo_result = Func(geometry1,geometry2);
			if(geo_result != 0)
			{
				wkb = GEOSGeomToWKB_buf(geo_result,&size);
				sqlite3_result_blob(context,wkb,size,SQLITE_TRANSIENT);
				GEOSGeom_destroy(geo_result);
				GEOSFree(wkb);
			}
		}
		if(geometry1!=0)GEOSGeom_destroy(geometry1);
		if(geometry2!=0)GEOSGeom_destroy(geometry2);
		finishGEOS();
	}
}
Example #11
0
/*
** Implementation of the "readfile(X)" SQL function.  The entire content
** of the file named X is read and returned as a BLOB.  NULL is returned
** if the file does not exist or is unreadable.
*/
static void readfileFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zName;
  FILE *in;
  long nIn;
  void *pBuf;

  zName = (const char*)sqlite3_value_text(argv[0]);
  if( zName==0 ) return;
  in = fopen(zName, "rb");
  if( in==0 ) return;
  fseek(in, 0, SEEK_END);
  nIn = ftell(in);
  rewind(in);
  pBuf = sqlite3_malloc64( nIn );
  if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
    sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
  }else{
    sqlite3_free(pBuf);
  }
  fclose(in);
}
Example #12
0
static void ST_SRID(sqlite3_context *context, int nbArgs, sqlite3_value **args) {
  spatialdb_t *spatialdb;
  FUNCTION_GEOM_ARG(geomblob);

  FUNCTION_START_STATIC(context, 256);
  spatialdb = (spatialdb_t *)sqlite3_user_data(context);
  FUNCTION_GET_GEOM_ARG_UNSAFE(context, spatialdb, geomblob, 0);

  if (nbArgs == 1) {
    sqlite3_result_int(context, geomblob.srid);
  } else {
    FUNCTION_GET_INT_ARG(geomblob.srid, 1);
    if (binstream_seek(&FUNCTION_GEOM_ARG_STREAM(geomblob), 0) != SQLITE_OK) {
      sqlite3_result_error(context, "Error writing geometry blob header", -1);
      goto exit;
    }
    if (spatialdb->write_blob_header(&FUNCTION_GEOM_ARG_STREAM(geomblob), &geomblob, FUNCTION_ERROR) != SQLITE_OK) {
      if (error_count(FUNCTION_ERROR) == 0) {
        error_append(FUNCTION_ERROR, "Error writing geometry blob header");
      }
      goto exit;
    }
    binstream_seek(&FUNCTION_GEOM_ARG_STREAM(geomblob), 0);
    sqlite3_result_blob(context, binstream_data(&FUNCTION_GEOM_ARG_STREAM(geomblob)), (int) binstream_available(&FUNCTION_GEOM_ARG_STREAM(geomblob)), SQLITE_TRANSIENT);
  }

  FUNCTION_END(context);
  FUNCTION_FREE_GEOM_ARG(geomblob);
}
Example #13
0
void geo_polyline_decode(sqlite3_context *context,int argc,sqlite3_value **argv)
{
	if(argc >= 1 && sqlite3_value_type(argv[0]) == SQLITE_TEXT)
	{ 
		GEOSGeometry* geometry;
		const unsigned char* data = sqlite3_value_text(argv[0]);
		int point = 1;
		size_t size = 0;

		if(argc > 1)
		{
			point = sqlite3_value_int(argv[1]);
		}

		_init_geos();
		geometry = polyline_decode(data,point);
		if(geometry != 0)
		{
			unsigned char* wkb = GEOSGeomToWKB_buf(geometry,&size);
			if(wkb != NULL)
			{
				sqlite3_result_blob(context,wkb,size,SQLITE_TRANSIENT);
				GEOSFree(wkb);
			}
		}
		GEOSGeom_destroy(geometry);
		finishGEOS();
	}
}
Example #14
0
extern void  my_load_file(sqlite3_context * context,
                          int               argc,
                          sqlite3_value  ** argv) {

   struct stat    statbuf;
   char          *fname;
   unsigned char *blob;
   FILE          *fp;
   size_t         nread;

   _ksu_null_if_null_param(argc, argv);
   fname = (char *)sqlite3_value_text(argv[0]);
   if (stat((const char *)fname, &statbuf) == -1) {
     sqlite3_result_null(context);
     return;
   }
   if ((blob = (unsigned char *)sqlite3_malloc((int)statbuf.st_size))
            == (unsigned char *)NULL) {
     sqlite3_result_error_nomem(context);
     return;
   }
   if ((fp = fopen(fname, "r")) != (FILE *)NULL) {
      nread = fread((void *)blob, sizeof(unsigned char),
                                  (size_t)statbuf.st_size, fp);
      fclose(fp);
      sqlite3_result_blob(context, (const void *)blob,
                          (int)nread, sqlite3_free);
   } else {
      sqlite3_free(blob);
      sqlite3_result_null(context);
   }
}
static
void OGR2SQLITE_Transform(sqlite3_context* pContext,
                          int argc, sqlite3_value** argv)
{
    if( argc != 3 )
    {
        sqlite3_result_null (pContext);
        return;
    }

    if( sqlite3_value_type (argv[0]) != SQLITE_BLOB )
    {
        sqlite3_result_null (pContext);
        return;
    }

    if( sqlite3_value_type (argv[1]) != SQLITE_INTEGER )
    {
        sqlite3_result_null (pContext);
        return;
    }

    if( sqlite3_value_type (argv[2]) != SQLITE_INTEGER )
    {
        sqlite3_result_null (pContext);
        return;
    }

    int nSrcSRSId = sqlite3_value_int(argv[1]);
    int nDstSRSId = sqlite3_value_int(argv[2]);

    OGRSQLiteExtensionData* poModule =
        (OGRSQLiteExtensionData*) sqlite3_user_data(pContext);
    OGRCoordinateTransformation* poCT =
        poModule->GetTransform(nSrcSRSId, nDstSRSId);
    if( poCT == NULL )
    {
        sqlite3_result_null (pContext);
        return;
    }

    GByte* pabySLBLOB = (GByte *) sqlite3_value_blob (argv[0]);
    int nBLOBLen = sqlite3_value_bytes (argv[0]);
    OGRGeometry* poGeom = NULL;
    if( OGRSQLiteLayer::ImportSpatiaLiteGeometry(
                pabySLBLOB, nBLOBLen, &poGeom ) == CE_None &&
            poGeom->transform(poCT) == OGRERR_NONE &&
            OGRSQLiteLayer::ExportSpatiaLiteGeometry(
                poGeom, nDstSRSId, wkbNDR, FALSE,
                FALSE, FALSE, &pabySLBLOB, &nBLOBLen ) == CE_None )
    {
        sqlite3_result_blob(pContext, pabySLBLOB, nBLOBLen, CPLFree);
    }
    else
    {
        sqlite3_result_null (pContext);
    }
    delete poGeom;
}
Example #16
0
void context::result(const blob &value, bool copy) {
	if (value.data) {
		sqlite3_result_blob(handle, value.data, value.length, (copy ? SQLITE_TRANSIENT : SQLITE_STATIC));
	}
	else {
		sqlite3_result_zeroblob(handle, value.length);
	}
}
Example #17
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 || argc==2 );
  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]);
  if( argc==3 ){
    p2 = sqlite3_value_int(argv[2]);
  }else{
    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  }
  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);
  }
}
static
void OGR2SQLITE_ogr_geocode_set_result(sqlite3_context* pContext,
                                       OGRLayerH hLayer,
                                       const char* pszField)
{
    if( hLayer == NULL )
        sqlite3_result_null (pContext);
    else
    {
        OGRLayer* poLayer = (OGRLayer*)hLayer;
        OGRFeatureDefn* poFDefn = poLayer->GetLayerDefn();
        OGRFeature* poFeature = poLayer->GetNextFeature();
        int nIdx = -1;
        if( poFeature == NULL )
            sqlite3_result_null (pContext);
        else if( strcmp(pszField, "geometry") == 0 &&
                 poFeature->GetGeometryRef() != NULL )
        {
            GByte* pabyGeomBLOB = NULL;
            int nGeomBLOBLen = 0;
            if( OGRSQLiteLayer::ExportSpatiaLiteGeometry(
                        poFeature->GetGeometryRef(), 4326, wkbNDR, FALSE, FALSE, FALSE,
                        &pabyGeomBLOB,
                        &nGeomBLOBLen ) != CE_None )
            {
                sqlite3_result_null (pContext);
            }
            else
            {
                sqlite3_result_blob (pContext, pabyGeomBLOB, nGeomBLOBLen, CPLFree);
            }
        }
        else if( (nIdx = poFDefn->GetFieldIndex(pszField)) >= 0 &&
                 poFeature->IsFieldSet(nIdx) )
        {
            OGRFieldType eType = poFDefn->GetFieldDefn(nIdx)->GetType();
            if( eType == OFTInteger )
                sqlite3_result_int(pContext,
                                   poFeature->GetFieldAsInteger(nIdx));
            else if( eType == OFTInteger64 )
                sqlite3_result_int64(pContext,
                                     poFeature->GetFieldAsInteger64(nIdx));
            else if( eType == OFTReal )
                sqlite3_result_double(pContext,
                                      poFeature->GetFieldAsDouble(nIdx));
            else
                sqlite3_result_text(pContext,
                                    poFeature->GetFieldAsString(nIdx),
                                    -1, SQLITE_TRANSIENT);
        }
        else
            sqlite3_result_null (pContext);
        delete poFeature;
        OGRGeocodeFreeResult(hLayer);
    }
}
Example #19
0
void geo_bound(sqlite3_context *context,int argc,sqlite3_value **argv)
{
	if(argc >= 1)
	{
		const unsigned char* ogc;
		unsigned char* ret_geo_buf;
		size_t size;
		double x1,x2,y1,y2;
		GEOSCoordSequence* seq = 0;
		GEOSGeometry* geometry = 0;
		GEOSGeometry* middle_geo = 0;
		
		_init_geos();
		if(argc == 1 && sqlite3_value_type(argv[0]) == SQLITE_BLOB)
		{
			size = sqlite3_value_bytes(argv[0]);
			ogc = (const unsigned char*)sqlite3_value_blob(argv[0]);
			middle_geo = _geo_from_wkb(ogc,size);
		}
		else if(argc == 1 && sqlite3_value_type(argv[0]) == SQLITE_TEXT)
		{
			ogc = sqlite3_value_text(argv[0]);
			middle_geo = _geo_from_wkt(ogc);
		}
		else if(argc == 4)
		{
			x1 = sqlite3_value_double(argv[0]);
			y1 = sqlite3_value_double(argv[1]);
			x2 = sqlite3_value_double(argv[2]);
			y2 = sqlite3_value_double(argv[3]);

			seq = GEOSCoordSeq_create(2,2);
			GEOSCoordSeq_setX(seq,0,x1);
			GEOSCoordSeq_setY(seq,0,y1);
			GEOSCoordSeq_setX(seq,1,x2);
			GEOSCoordSeq_setY(seq,1,y2);

			middle_geo = GEOSGeom_createLineString(seq);
		}

		if(middle_geo != 0)
		{
			geometry = GEOSEnvelope(middle_geo);
			if(geometry != 0)
			{
				ret_geo_buf = GEOSGeomToWKB_buf(geometry,&size);
				sqlite3_result_blob(context,ret_geo_buf,size,SQLITE_TRANSIENT);
				GEOSGeom_destroy(geometry);
				GEOSFree(ret_geo_buf);
			}
			GEOSGeom_destroy(middle_geo);
		}

		finishGEOS();
	}
}
Example #20
0
GEOPACKAGE_DECLARE void
fnct_gpkgMakePoint (sqlite3_context * context, int argc UNUSED,
		    sqlite3_value ** argv)
{
/* SQL function:
/ gpkgMakePoint(x, y)
/
/ Creates a GeoPackage geometry POINT
/
/ returns nothing on success, raises exception on error
*/
    unsigned int len;
    int int_value;
    unsigned char *p_result = NULL;
    double x;
    double y;
    GEOPACKAGE_UNUSED ();	/* LCOV_EXCL_LINE */
    if (sqlite3_value_type (argv[0]) == SQLITE_FLOAT)
      {
	  x = sqlite3_value_double (argv[0]);
      }
    else if (sqlite3_value_type (argv[0]) == SQLITE_INTEGER)
      {
	  int_value = sqlite3_value_int (argv[0]);
	  x = int_value;
      }
    else
      {
	  sqlite3_result_null (context);
	  return;
      }
    if (sqlite3_value_type (argv[1]) == SQLITE_FLOAT)
      {
	  y = sqlite3_value_double (argv[1]);
      }
    else if (sqlite3_value_type (argv[1]) == SQLITE_INTEGER)
      {
	  int_value = sqlite3_value_int (argv[1]);
	  y = int_value;
      }
    else
      {
	  sqlite3_result_null (context);
	  return;
      }
    gpkgMakePoint (x, y, GEOPACKAGE_DEFAULT_UNDEFINED_SRID, &p_result, &len);
    if (!p_result)
      {
	  sqlite3_result_null (context);
      }
    else
      {
	  sqlite3_result_blob (context, p_result, len, free);
      }
}
// sql function. takes ESSID and PASSWD, gives PMK
void sql_calcpmk(sqlite3_context* context, int argc, sqlite3_value** values) {
	unsigned char pmk[40];
	char* passwd = (char*)sqlite3_value_blob(values[1]);
	char* essid = (char*)sqlite3_value_blob(values[0]);
	if (argc < 2 || passwd == 0 || essid == 0) {
		sqlite3_result_error(context, "SQL function PMK() called with invalid arguments.\n", -1);
		return;
	}
	calc_pmk(passwd,essid,pmk);
	sqlite3_result_blob(context,pmk,32,SQLITE_TRANSIENT);
}
Example #22
0
static void
function_property_names (sqlite3_context *context,
                         int              argc,
                         sqlite3_value   *argv[])
{
	static gchar **names = NULL;
	static GMutex mutex;
	int rc = SQLITE_DONE;

	g_mutex_lock (&mutex);

	if (G_UNLIKELY (names == NULL)) {
		GPtrArray *names_array;
		sqlite3_stmt *stmt;
		sqlite3 *db;

		names_array = g_ptr_array_new ();
		db = sqlite3_context_db_handle (context);
		rc = sqlite3_prepare_v2 (db,
		                         "SELECT Uri "
		                         "FROM Resource "
		                         "JOIN \"rdf:Property\" "
		                         "ON Resource.ID = \"rdf:Property\".ID "
		                         "WHERE \"rdf:Property\".\"tracker:fulltextIndexed\" = 1 "
		                         "ORDER BY \"rdf:Property\".ID ",
		                         -1, &stmt, NULL);

		while ((rc = sqlite3_step (stmt)) != SQLITE_DONE) {
			if (rc == SQLITE_ROW) {
				const gchar *name;

				name = sqlite3_column_text (stmt, 0);
				g_ptr_array_add (names_array, g_strdup (name));
			} else if (rc != SQLITE_BUSY) {
				break;
			}
		}

		sqlite3_finalize (stmt);

		if (rc == SQLITE_DONE) {
			names = (gchar **) g_ptr_array_free (names_array, FALSE);
		} else {
			g_ptr_array_free (names_array, TRUE);
		}
	}

	g_mutex_unlock (&mutex);

	if (rc == SQLITE_DONE)
		sqlite3_result_blob (context, names, sizeof (names), NULL);
	else
		sqlite3_result_error_code (context, rc);
}
Example #23
0
static void geometry_constructor(sqlite3_context *context, const spatialdb_t *spatialdb, geometry_constructor_func constructor, void* user_data, geom_type_t requiredType, int nbArgs, sqlite3_value **args) {
  FUNCTION_START_STATIC(context, 256);

  geom_blob_auxdata *geom = (geom_blob_auxdata *)sqlite3_get_auxdata(context, 0);

  if (geom == NULL) {
    geom_blob_writer_t writer;

    if (sqlite3_value_type(args[nbArgs - 1]) == SQLITE_INTEGER) {
      spatialdb->writer_init_srid(&writer, sqlite3_value_int(args[nbArgs - 1]));
      nbArgs -= 1;
    } else {
      spatialdb->writer_init(&writer);
    }

    FUNCTION_RESULT = constructor(context, user_data, geom_blob_writer_geom_consumer(&writer), nbArgs, args, FUNCTION_ERROR);

    if (FUNCTION_RESULT == SQLITE_OK) {
      if (geometry_is_assignable(requiredType, writer.geom_type, FUNCTION_ERROR) == SQLITE_OK) {
        uint8_t *data = geom_blob_writer_getdata(&writer);
        int length = (int) geom_blob_writer_length(&writer);
        sqlite3_result_blob(context, data, length, SQLITE_TRANSIENT);
        spatialdb->writer_destroy(&writer, 0);

        geom = geom_blob_auxdata_malloc();
        if (geom != NULL) {
          geom->data = data;
          geom->length = length;
          sqlite3_set_auxdata(context, 0, geom, geom_blob_auxdata_free);
        }
      }
    } else {
      spatialdb->writer_destroy(&writer, 1);
    }
  } else {
    sqlite3_result_blob(context, geom->data, geom->length, SQLITE_TRANSIENT);
  }

  FUNCTION_END(context);
}
Example #24
0
/*
** 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);
}
Example #25
0
static void
function_weights (sqlite3_context *context,
                  int              argc,
                  sqlite3_value   *argv[])
{
	static guint *weights = NULL;
	static GMutex mutex;
	int rc = SQLITE_DONE;

	g_mutex_lock (&mutex);

	if (G_UNLIKELY (weights == NULL)) {
		GArray *weight_array;
		sqlite3_stmt *stmt;
		sqlite3 *db;

		weight_array = g_array_new (FALSE, FALSE, sizeof (guint));
		db = sqlite3_context_db_handle (context);
		rc = sqlite3_prepare_v2 (db,
		                         "SELECT \"rdf:Property\".\"tracker:weight\" "
		                         "FROM \"rdf:Property\" "
		                         "WHERE \"rdf:Property\".\"tracker:fulltextIndexed\" = 1 "
		                         "ORDER BY \"rdf:Property\".ID ",
		                         -1, &stmt, NULL);

		while ((rc = sqlite3_step (stmt)) != SQLITE_DONE) {
			if (rc == SQLITE_ROW) {
				guint weight;
				weight = sqlite3_column_int (stmt, 0);
				g_array_append_val (weight_array, weight);
			} else if (rc != SQLITE_BUSY) {
				break;
			}
		}

		sqlite3_finalize (stmt);

		if (rc == SQLITE_DONE) {
			weights = (guint *) g_array_free (weight_array, FALSE);
		} else {
			g_array_free (weight_array, TRUE);
		}
	}

	g_mutex_unlock (&mutex);

	if (rc == SQLITE_DONE)
		sqlite3_result_blob (context, weights, sizeof (weights), NULL);
	else
		sqlite3_result_error_code (context, rc);
}
Example #26
0
/*
** Implementation of randomblob(N).  Return a random blob
** that is N bytes long.
*/
static void randomBlob(
    sqlite3_context *context,
    int argc,
    sqlite3_value **argv
) {
    int n;
    unsigned char *p;
    assert( argc==1 );
    n = sqlite3_value_int(argv[0]);
    if( n<1 ) n = 1;
    p = sqlite3_malloc(n);
    sqlite3Randomness(n, p);
    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
}
Example #27
0
void ObjToSqliteContextValue(Tcl_Obj *objP, sqlite3_context *sqlctxP)
{
    unsigned char *data;
    int len;
    if (objP->typePtr) {
        /*
         * Note there is no return code checking here. Once the typePtr
         * is checked, the corresponding Tcl_Get* function should
         * always succeed.
         */

        if (objP->typePtr == gTclStringTypeP) {
            /*
             * Do nothing, fall thru below to handle as default type.
             * This check is here just so the most common case of text
             * columns does not needlessly go through other type checks.
             */
        } else if (objP->typePtr == gTclIntTypeP) {
            int ival;
            Tcl_GetIntFromObj(NULL, objP, &ival);
            sqlite3_result_int(sqlctxP, ival);
            return;
        } else if (objP->typePtr == gTclWideIntTypeP) {
            Tcl_WideInt i64val;
            Tcl_GetWideIntFromObj(NULL, objP, &i64val);
            sqlite3_result_int64(sqlctxP, i64val);
            return;
        } else if (objP->typePtr == gTclDoubleTypeP) {
            double dval;
            Tcl_GetDoubleFromObj(NULL, objP, &dval);
            sqlite3_result_double(sqlctxP, dval);
            return;
        } else if (objP->typePtr == gTclBooleanTypeP ||
                   objP->typePtr == gTclBooleanStringTypeP) {
            int bval;
            Tcl_GetBooleanFromObj(NULL, objP, &bval);
            sqlite3_result_int(sqlctxP, bval);
            return;
        } else if (objP->typePtr == gTclByteArrayTypeP) {
            /* TBD */
            data = Tcl_GetByteArrayFromObj(objP, &len);
            sqlite3_result_blob(sqlctxP, data, len, SQLITE_TRANSIENT);
            return;
        }
    }

    /* Handle everything else as text by default */
    data = (unsigned char *)Tcl_GetStringFromObj(objP, &len);
    sqlite3_result_text(sqlctxP, data, len, SQLITE_TRANSIENT);
}
  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);
}
Example #29
0
static void set_sqlite3_func_result(sqlite3_context * ctx, VALUE result)
{
  switch(TYPE(result)) {
    case T_NIL:
      sqlite3_result_null(ctx);
      break;
    case T_FIXNUM:
      sqlite3_result_int64(ctx, (sqlite3_int64)FIX2LONG(result));
      break;
    case T_BIGNUM: {
#if SIZEOF_LONG < 8
      sqlite3_int64 num64;

      if (bignum_to_int64(result, &num64)) {
	  sqlite3_result_int64(ctx, num64);
	  break;
      }
#endif
    }
    case T_FLOAT:
      sqlite3_result_double(ctx, NUM2DBL(result));
      break;
    case T_STRING:
      if(CLASS_OF(result) == cSqlite3Blob
#ifdef HAVE_RUBY_ENCODING_H
              || rb_enc_get_index(result) == rb_ascii8bit_encindex()
#endif
        ) {
        sqlite3_result_blob(
            ctx,
            (const void *)StringValuePtr(result),
            (int)RSTRING_LEN(result),
            SQLITE_TRANSIENT
        );
      } else {
        sqlite3_result_text(
            ctx,
            (const char *)StringValuePtr(result),
            (int)RSTRING_LEN(result),
            SQLITE_TRANSIENT
        );
      }
      break;
    default:
      rb_raise(rb_eRuntimeError, "can't return %s",
          rb_class2name(CLASS_OF(result)));
  }
}
Example #30
0
/*
** build a simple bitstring (mostly for testing)
*/
static void bfp_dummy_f(sqlite3_context* ctx,
			int argc, sqlite3_value** argv)
{
  assert(argc == 2);
  int rc = SQLITE_OK;
  int len, value;

  u8 * pBlob = 0;

  /* Check that value is a blob */
  if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER) {
    rc = SQLITE_MISMATCH;
  }
  else if (sqlite3_value_type(argv[1]) != SQLITE_INTEGER) {
    rc = SQLITE_MISMATCH;
  }
  else {

    len = sqlite3_value_int(argv[0]);
    if (len <= 0) { len = 1; }
    if (len > MAX_BITSTRING_SIZE) { len = MAX_BITSTRING_SIZE; }

    value = sqlite3_value_int(argv[1]);
    if (value < 0) { value = 0; }
    if (value > 255) { value = 255; }

    pBlob = (u8 *)sqlite3_malloc(len);
    if (!pBlob) {
      rc = SQLITE_NOMEM;
    }
    else {
      u8 *p = pBlob; 
      int ii;
      for (ii = 0; ii < len; ++ii) {
	*p++ = value;
      }
    }

  }

  if (rc == SQLITE_OK) {
    sqlite3_result_blob(ctx, pBlob, len, sqlite3_free);
  }	
  else {
    sqlite3_result_error_code(ctx, rc);
  }

}