PyObject *Client_connect(PyClient *self, PyObject *args)
{
  if (self->desc.prv == NULL)
  {
    return PyErr_Format(PyExc_RuntimeError, "Client can not be reconnected");
  }

  if (!self->client->connect (PyString_AS_STRING(self->host), self->port))
  {
    PRINTMARK();
    return NULL;
  }

  Py_RETURN_NONE;
}
int Client_init(PyClient *self, PyObject *args)
{
    /* Args:
     def __init__(self, address, protocol = "text", codec = "default"):
    */

    self->client = NULL;
    self->host = NULL;


    char *address;
    PRINTMARK();

    if (!PyArg_ParseTuple (args, "s", &address))
    {
        PRINTMARK();
        return -1;
    }

    PRINTMARK();
    char *offset = strchr (address, ':');

    if (offset == NULL)
    {
        PyErr_Format(PyExc_RuntimeError, "Invalid argument for address");
        return -1;
    }

    char *port = address + (offset - address) + 1;


    self->host = PyString_FromStringAndSize(address, (offset - address));
    self->port = atoi(port);
    Py_INCREF(self->host);
    PRINTMARK();
    self->sock = (PyObject *) API_createSocket(AF_INET, SOCK_STREAM, 0);
    PRINTMARK();
    self->sockfd = API_getSocketFD(self->sock);

    self->desc.prv = self;
    self->desc.connect = API_connect;
    self->desc.destroy = API_destroy;
    self->desc.recv = API_recv;
    self->desc.send = API_send;
    PRINTMARK();
    self->client = new Client(&self->desc);
    PRINTMARK();

    return 0;
}
int API_recv(SOCKETDESC *desc, void *data, size_t cbMaxData)
{
    PyClient *client = (PyClient *) desc->prv;

    if (client == NULL)
    {
        PyErr_Format(PyExc_IOError, "No client object");

        PRINTMARK();
        return -1;
    }

    int result;

    while (true)
    {
        result = recv ( client->sockfd, (char *) data, cbMaxData, MSG_NOSIGNAL);

        if (result == 0)
        {
            PRINTMARK();
            PyErr_Format(PyExc_IOError, "Connection reset by peer while reading on socket");
            return -1;
        }

        if (result > 0)
        {
            PRINTMARK();
            break;
        }

        PRINTMARK();
        if (!SocketWouldBlock(client->sockfd))
        {
            PyErr_Format(PyExc_IOError, "Socket error %d when reading", SocketGetLastError());
            return -1;
        }

        PRINTMARK();
        if (API_wouldBlock_gevent(client->sock, client->sockfd, 1, 10) == 0)
        {
            PRINTMARK();
            return -1;
        }
        PRINTMARK();

    }

    return result;
}
Exemple #4
0
void Dir_iterEnd(JSOBJ obj, JSONTypeContext *tc)
{
  if (GET_TC(tc)->itemValue)
  {
    Py_DECREF(GET_TC(tc)->itemValue);
    GET_TC(tc)->itemValue = NULL;
  }

  if (GET_TC(tc)->itemName)
  {
    Py_DECREF(GET_TC(tc)->itemName);
    GET_TC(tc)->itemName = NULL;
  }

  Py_DECREF( (PyObject *) GET_TC(tc)->attrList);
  PRINTMARK();
}
PyObject *Client_set_timeout(PyClient *self, PyObject *args)
{

  PyObject *timeout;

  if (!PyArg_ParseTuple (args, "O", &timeout))
  {
    return NULL;
  }

  PyObject *method = PyString_FromString("settimeout");
  PyObject *res = PyObject_CallMethodObjArgs(self->sock, method, timeout, NULL);

  PRINTMARK();

  Py_DECREF(method);

  return res;
}
Exemple #6
0
JSOBJ Object_npyNewArray(void *prv, void* _decoder)
{
  NpyArrContext* npyarr;
  PyObjectDecoder* decoder = (PyObjectDecoder*) _decoder;
  PRINTMARK();
  if (decoder->curdim <= 0)
  {
    // start of array - initialise the context buffer
    npyarr = decoder->npyarr = PyObject_Malloc(sizeof(NpyArrContext));
    decoder->npyarr_addr = npyarr;

    if (!npyarr)
    {
      PyErr_NoMemory();
      return NULL;
    }

    npyarr->dec = decoder;
    npyarr->labels[0] = npyarr->labels[1] = NULL;

    npyarr->shape.ptr = PyObject_Malloc(sizeof(npy_intp)*NPY_MAXDIMS);
    npyarr->shape.len = 1;
    npyarr->ret = NULL;

    npyarr->elsize = 0;
    npyarr->elcount = 4;
    npyarr->i = 0;
  }
  else
  {
    // starting a new dimension continue the current array (and reshape after)
    npyarr = (NpyArrContext*) decoder->npyarr;
    if (decoder->curdim >= npyarr->shape.len)
    {
      npyarr->shape.len++;
    }
  }

  npyarr->shape.ptr[decoder->curdim] = 0;
  decoder->curdim++;
  return npyarr;
}
Exemple #7
0
// free the numpy context buffer
void Npy_releaseContext(NpyArrContext* npyarr)
{
  PRINTMARK();
  if (npyarr)
  {
    if (npyarr->shape.ptr)
    {
      PyObject_Free(npyarr->shape.ptr);
    }
    if (npyarr->dec)
    {
      npyarr->dec->npyarr = NULL;
      npyarr->dec->curdim = 0;
    }
    Py_XDECREF(npyarr->labels[0]);
    Py_XDECREF(npyarr->labels[1]);
    Py_XDECREF(npyarr->ret);
    PyObject_Free(npyarr);
  }
}
Exemple #8
0
JSOBJ Object_npyEndObject(void *prv, JSOBJ obj)
{
  PyObject *list;
  npy_intp labelidx;
  NpyArrContext* npyarr = (NpyArrContext*) obj;
  PRINTMARK();
  if (!npyarr)
  {
    return NULL;
  }

  labelidx = npyarr->dec->curdim-1;

  list = npyarr->labels[labelidx];
  if (list)
  {
    npyarr->labels[labelidx] = PyArray_FROM_O(list);
    Py_DECREF(list);
  }

  return (PyObject*) ((JSONObjectDecoder*)npyarr->dec)->endArray(prv, obj);
}
Exemple #9
0
JSOBJ Object_npyEndArrayList(void *prv, JSOBJ obj)
{
  PyObject *list, *ret;
  NpyArrContext* npyarr = (NpyArrContext*) obj;
  PRINTMARK();
  if (!npyarr)
  {
    return NULL;
  }

  // convert decoded list to numpy array
  list = (PyObject *) npyarr->ret;
  npyarr->ret = PyArray_FROM_O(list);

  ret = Npy_returnLabelled(npyarr);
  npyarr->ret = list;

  ((JSONObjectDecoder*)npyarr->dec)->newArray = Object_npyNewArray;
  ((JSONObjectDecoder*)npyarr->dec)->arrayAddItem = Object_npyArrayAddItem;
  ((JSONObjectDecoder*)npyarr->dec)->endArray = Object_npyEndArray;
  Npy_releaseContext(npyarr);
  return ret;
}
int API_connect(SOCKETDESC *desc, const char *address, int port)
{
  PyClient *client = (PyClient *) desc->prv;

  char strTemp[256 + 1];
  PRINTMARK();
  snprintf (strTemp, 256, "%s:%d", address, port);
  PRINTMARK();

  PRINTMARK();

  PyObject *args = PyTuple_New(2);
  //Increment client->host before dropping into tuple
  Py_INCREF(client->host);
  PyTuple_SET_ITEM(args, 0, client->host);
  PyTuple_SET_ITEM(args, 1, PyInt_FromLong(client->port));
  PyObject *method = PyString_FromString("connect");

  PyObject *res = PyObject_CallMethodObjArgs(client->sock, method, args, NULL);

  PRINTMARK();

  //PyTuple_SET_ITEM doesn't increment ref counter 
  //Py_DECREF(PyTuple_GET_ITEM(args, 1));
  Py_DECREF(args);
  Py_DECREF(method);

  if (res == NULL)
  {
    PRINTMARK();
    return 0;
  }

  Py_DECREF(res);

  PRINTMARK();
  return 1;
}
Exemple #11
0
PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
{
	static char *kwlist[] = { "obj", "ensure_ascii", NULL};

	char buffer[65536];
	char *ret;
	PyObject *newobj;
	PyObject *oinput = NULL;
	PyObject *oensureAscii = NULL;

	JSONObjectEncoder encoder = 
	{
		Object_beginTypeContext,	//void (*beginTypeContext)(JSOBJ obj, JSONTypeContext *tc);
		Object_endTypeContext, //void (*endTypeContext)(JSOBJ obj, JSONTypeContext *tc);
		Object_getStringValue, //const char *(*getStringValue)(JSOBJ obj, JSONTypeContext *tc, size_t *_outLen);
		Object_getLongValue, //JSLONG (*getLongValue)(JSOBJ obj, JSONTypeContext *tc);
		Object_getIntValue, //JSLONG (*getLongValue)(JSOBJ obj, JSONTypeContext *tc);
		Object_getDoubleValue, //double (*getDoubleValue)(JSOBJ obj, JSONTypeContext *tc);
		Object_iterBegin, //JSPFN_ITERBEGIN iterBegin;
		Object_iterNext, //JSPFN_ITERNEXT iterNext;
		Object_iterEnd, //JSPFN_ITEREND iterEnd;
		Object_iterGetValue, //JSPFN_ITERGETVALUE iterGetValue;
		Object_iterGetName, //JSPFN_ITERGETNAME iterGetName;
		Object_releaseObject, //void (*releaseValue)(JSONTypeContext *ti);
		PyObject_Malloc, //JSPFN_MALLOC malloc;
		PyObject_Realloc, //JSPFN_REALLOC realloc;
		PyObject_Free, //JSPFN_FREE free;
		-1, //recursionMax
		5, //default decimal precision
		1, //forceAscii
	};
	
	PRINTMARK();

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &oinput, &oensureAscii))
	{
		return NULL;
	}

	if (oensureAscii != NULL && !PyObject_IsTrue(oensureAscii))
	{
		encoder.forceASCII = 0;
	}

	PRINTMARK();
	ret = JSON_EncodeObject (oinput, &encoder, buffer, sizeof (buffer));
	PRINTMARK();

	if (PyErr_Occurred())
	{
		return NULL;
	}

	if (encoder.errorMsg)
	{
		if (ret != buffer)
		{
			encoder.free (ret);
		}

		PyErr_Format (PyExc_OverflowError, "%s", encoder.errorMsg);
		return NULL;
	}

	newobj = PyString_FromString (ret);

	if (ret != buffer)
	{
		encoder.free (ret);
	}

	PRINTMARK();

	return newobj;
}
Exemple #12
0
void Object_beginTypeContext (PyObject *obj, JSONTypeContext *tc)
{
	TypeContext *pc = (TypeContext *) tc->prv;
	PyObject *toDictFunc;

	tc->prv[0] = 0;
	tc->prv[1] = 0;
	tc->prv[2] = 0;
	tc->prv[3] = 0;
	tc->prv[4] = 0;
	tc->prv[5] = 0;
	tc->prv[6] = 0;
	tc->prv[7] = 0;
	tc->prv[8] = 0;
	tc->prv[9] = 0;
	tc->prv[10] = 0;
	tc->prv[11] = 0;
	tc->prv[12] = 0;
	tc->prv[13] = 0;
	tc->prv[14] = 0;
	
	if (PyIter_Check(obj))
	{
		goto ISITERABLE;
	}

	if (PyBool_Check(obj))
	{
		PRINTMARK();
		tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
		return;
	}
	else
	if (PyInt_Check(obj))
	{
		PRINTMARK();
#ifdef _LP64
		pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
		pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
		return;
	}
	else 
	if (PyLong_Check(obj))
	{
		PyObject *exc;

		PRINTMARK();
		pc->PyTypeToJSON = PyLongToINT64; 
		tc->type = JT_LONG;
		GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

		exc = PyErr_Occurred();

		if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
		{
			PRINTMARK();
			tc->type = JT_INVALID;
			return;
		}

		return;
	}
	else
	if (PyString_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
		return;
	}
	else
	if (PyUnicode_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
		return;
	}
	else
	if (PyFloat_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
		return;
	}
	else 
	if (PyDateTime_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
		return;
	}
	else 
	if (PyDate_Check(obj))
	{
		PRINTMARK();
		pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
		return;
	}
	else
	if (obj == Py_None)
	{
		PRINTMARK();
		tc->type = JT_NULL;
		return;
	}


ISITERABLE:

	if (PyDict_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_OBJECT;
		pc->iterBegin = Dict_iterBegin;
		pc->iterEnd = Dict_iterEnd;
		pc->iterNext = Dict_iterNext;
		pc->iterGetValue = Dict_iterGetValue;
		pc->iterGetName = Dict_iterGetName;
		pc->dictObj = obj;
		Py_INCREF(obj);

		return;
	}
	else
	if (PyList_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_ARRAY;
		pc->iterBegin = List_iterBegin;
		pc->iterEnd = List_iterEnd;
		pc->iterNext = List_iterNext;
		pc->iterGetValue = List_iterGetValue;
		pc->iterGetName = List_iterGetName;
		return;
	}
	else
	if (PyTuple_Check(obj))
	{
		PRINTMARK();
		tc->type = JT_ARRAY;
		pc->iterBegin = Tuple_iterBegin;
		pc->iterEnd = Tuple_iterEnd;
		pc->iterNext = Tuple_iterNext;
		pc->iterGetValue = Tuple_iterGetValue;
		pc->iterGetName = Tuple_iterGetName;
		return;
	}


	toDictFunc = PyObject_GetAttrString(obj, "toDict");

	if (toDictFunc)
	{
		PyObject* tuple = PyTuple_New(0);
		PyObject* toDictResult = PyObject_Call(toDictFunc, tuple, NULL);
		Py_DECREF(tuple);
		Py_DECREF(toDictFunc);

		if (toDictResult == NULL)
		{
			PyErr_Clear();
			tc->type = JT_NULL;
			return;
		}

		if (!PyDict_Check(toDictResult))
		{
			Py_DECREF(toDictResult);
			tc->type = JT_NULL;
			return;
		}

		PRINTMARK();
		tc->type = JT_OBJECT;
		pc->iterBegin = Dict_iterBegin;
		pc->iterEnd = Dict_iterEnd;
		pc->iterNext = Dict_iterNext;
		pc->iterGetValue = Dict_iterGetValue;
		pc->iterGetName = Dict_iterGetName;
		pc->dictObj = toDictResult;
		return;
	}

	PyErr_Clear();

	tc->type = JT_OBJECT;
	pc->iterBegin = Dir_iterBegin;
	pc->iterEnd = Dir_iterEnd;
	pc->iterNext = Dir_iterNext;
	pc->iterGetValue = Dir_iterGetValue;
	pc->iterGetName = Dir_iterGetName;

	return;
}
Exemple #13
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj, *exc, *toDictFunc, *iter;
  TypeContext *pc;
  PRINTMARK();
  if (!_obj) {
    tc->type = JT_INVALID;
    return;
  }

  obj = (PyObject*) _obj;

  pc = (TypeContext *) tc->prv;
  if (!pc)
  {
    tc->type = JT_INVALID;
    PyErr_NoMemory();
    return;
  }
  pc->newObj = NULL;
  pc->dictObj = NULL;
  pc->itemValue = NULL;
  pc->itemName = NULL;
  pc->iterator = NULL;
  pc->attrList = NULL;
  pc->index = 0;
  pc->size = 0;
  pc->longValue = 0;

  if (PyIter_Check(obj))
  {
    PRINTMARK();
    goto ISITERABLE;
  }

  if (PyBool_Check(obj))
  {
    PRINTMARK();
    tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
    return;
  }
  else
  if (PyLong_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyLongToINT64;
    tc->type = JT_LONG;
    GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

    exc = PyErr_Occurred();

    if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
    {
      PRINTMARK();
      goto INVALID;
    }

    return;
  }
  else
  if (PyInt_Check(obj))
  {
    PRINTMARK();
#ifdef _LP64
    pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
    pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
    return;
  }
  else
  if (PyString_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyUnicode_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyFloat_Check(obj) || (type_decimal && PyObject_IsInstance(obj, type_decimal)))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
    return;
  }
  else
  if (PyDateTime_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (PyDate_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (obj == Py_None)
  {
    PRINTMARK();
    tc->type = JT_NULL;
    return;
  }

ISITERABLE:
  if (PyDict_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_OBJECT;
    SetupDictIter(obj, pc);
    Py_INCREF(obj);
    return;
  }
  else
  if (PyList_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterEnd = List_iterEnd;
    pc->iterNext = List_iterNext;
    pc->iterGetValue = List_iterGetValue;
    pc->iterGetName = List_iterGetName;
    GET_TC(tc)->index =  0;
    GET_TC(tc)->size = PyList_GET_SIZE( (PyObject *) obj);
    return;
  }
  else
  if (PyTuple_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterEnd = Tuple_iterEnd;
    pc->iterNext = Tuple_iterNext;
    pc->iterGetValue = Tuple_iterGetValue;
    pc->iterGetName = Tuple_iterGetName;
    GET_TC(tc)->index = 0;
    GET_TC(tc)->size = PyTuple_GET_SIZE( (PyObject *) obj);
    GET_TC(tc)->itemValue = NULL;

    return;
  }
  /*
  else
  if (PyAnySet_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = NULL;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }
  */

  toDictFunc = PyObject_GetAttrString(obj, "toDict");

  if (toDictFunc)
  {
    PyObject* tuple = PyTuple_New(0);
    PyObject* toDictResult = PyObject_Call(toDictFunc, tuple, NULL);
    Py_DECREF(tuple);
    Py_DECREF(toDictFunc);

    if (toDictResult == NULL)
    {
      PyErr_Clear();
      tc->type = JT_NULL;
      return;
    }

    if (!PyDict_Check(toDictResult))
    {
      Py_DECREF(toDictResult);
      tc->type = JT_NULL;
      return;
    }

    PRINTMARK();
    tc->type = JT_OBJECT;
    SetupDictIter(toDictResult, pc);
    return;
  }

  PRINTMARK();
  PyErr_Clear();

  iter = PyObject_GetIter(obj);

  if (iter != NULL)
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterator = iter;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }

  PRINTMARK();
  PyErr_Clear();

  PRINTMARK();
  tc->type = JT_OBJECT;
  GET_TC(tc)->attrList = PyObject_Dir(obj);
  
  if (GET_TC(tc)->attrList == NULL)
  {
    PyErr_Clear();
    goto INVALID;
  }

  GET_TC(tc)->index = 0;
  GET_TC(tc)->size = PyList_GET_SIZE(GET_TC(tc)->attrList);
  PRINTMARK();
  
  pc->iterEnd = Dir_iterEnd;
  pc->iterNext = Dir_iterNext;
  pc->iterGetValue = Dir_iterGetValue;
  pc->iterGetName = Dir_iterGetName;
  return;

INVALID:
  PRINTMARK();
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
Exemple #14
0
int AppendEscapedArg (Connection *self, char *start, char *end, PyObject *obj)
{
  int ret;
  PyObject *strobj;

  /*
  FIXME: Surround strings with '' could be performed in this function to avoid extra logic in AppendAndEscapeString */
  PRINTMARK();

  if (PyString_Check(obj))
  {
    PRINTMARK();
    return AppendAndEscapeString(start, end, PyString_AS_STRING(obj), PyString_AS_STRING(obj) + PyString_GET_SIZE(obj), TRUE);
  }
  else
    if (PyUnicode_Check(obj))
    {
      PRINTMARK();
      strobj = self->PFN_PyUnicode_Encode(PyUnicode_AS_UNICODE(obj), PyUnicode_GET_SIZE(obj), NULL);

      if (strobj == NULL)
      {
        if (PyErr_Occurred())
        {
          return -1;
        }

        PyErr_SetObject (PyExc_ValueError, obj);
        return -1;
      }


      ret = AppendAndEscapeString(start, end, PyString_AS_STRING(strobj), PyString_AS_STRING(strobj) + PyString_GET_SIZE(strobj), TRUE);
      Py_DECREF(strobj);

      return ret;
    }
    else
      if (obj == Py_None)
      {
        (*start++) = 'n';
        (*start++) = 'u';
        (*start++) = 'l';
        (*start++) = 'l';
        return  4;
      }
      else
        if (PyDateTime_Check(obj))
        {
          int len = sprintf (start, "'%04d-%02d-%02d %02d:%02d:%02d'", 
            PyDateTime_GET_YEAR(obj),
            PyDateTime_GET_MONTH(obj),
            PyDateTime_GET_DAY(obj),
            PyDateTime_DATE_GET_HOUR(obj),
            PyDateTime_DATE_GET_MINUTE(obj),
            PyDateTime_DATE_GET_SECOND(obj));

          return len;
        }
        else
          if (PyDate_Check(obj))
          {
            int len = sprintf (start, "'%04d:%02d:%02d'", 
              PyDateTime_GET_YEAR(obj),
              PyDateTime_GET_MONTH(obj),
              PyDateTime_GET_DAY(obj));

            return len;
          }

          //FIXME: Might possible to avoid this?
          PRINTMARK();
          strobj = PyObject_Str(obj);
          ret = AppendAndEscapeString(start, end, PyString_AS_STRING(strobj), PyString_AS_STRING(strobj) + PyString_GET_SIZE(strobj), FALSE);
          Py_DECREF(strobj);
          return ret;
}
Exemple #15
0
int AppendAndEscapeString(char *buffStart, char *buffEnd, const char *strStart, const char *strEnd, int quote)
{
  //{'\0': '\\0', '\n': '\\n', '\r': '\\r', '\\': '\\\\', "'": "\\'", '"': '\\"', '\x1a': '\\Z'}):
  char *buffOffset = buffStart;

  if (quote)
  {
    (*buffOffset++) = '\'';
  }

  while (strStart < strEnd)
  {
    switch (*strStart)
    {
    case '\0':	// NULL
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = '0';
      break;
    case '\n':	// LF
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = 'n';
      break;
    case '\r':	// CR
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = 'r';
      break;
    case '\\':	// BACKSLASH
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = '\\';
      break;
    case '\'':	// SINGLE QUOTE
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = '\'';
      break;
    case '\"':	// DOUBLE QUOTE
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = '\"';
      break;
    case '\x1a': // SUBSTITUTE CONTROL CHARACTER
      PRINTMARK();
      (*buffOffset++) = '\\';
      (*buffOffset++) = 'Z';
      break;

    default:
      (*buffOffset++) = (*strStart);
      break;
    }

    strStart ++;
  }

  if (quote)
  {
    (*buffOffset++) = '\'';
  }

  return (int) (buffOffset - buffStart);
}
Exemple #16
0
PyObject *Connection_connect(Connection *self, PyObject *args)
{
  /*
  Args:
  UMConnection conn, const char *_host, int _port, const char *_username, const char *_password, const char *_database, int _autoCommit, const char *_charset*/

  char *host;
  int port;
  char *username;
  char *password;
  char *database;

  int autoCommit;
  char *pstrCharset = NULL;
  PyObject *acObj = NULL;

  if (!PyArg_ParseTuple (args, "sisss|Os", &host, &port, &username, &password, &database, &acObj, &pstrCharset))
  {
    return NULL;
  }

  if (acObj)
  {
    PRINTMARK();
    autoCommit = (PyObject_IsTrue(acObj) == 1) ? 1 : 0;
  }
  if (pstrCharset)
  {
    if (strcmp (pstrCharset, "utf8") == 0)
    {
      self->charset = MCS_utf8_general_ci;
      self->PFN_PyUnicode_Encode = PyUnicode_EncodeUTF8;
    }
    else
      if (strcmp (pstrCharset, "latin1") == 0)
      {
        self->charset = MCS_latin1_general_ci;
        self->PFN_PyUnicode_Encode = PyUnicode_EncodeLatin1;
      }
      else
        if (strcmp (pstrCharset, "ascii") == 0)
        {
          self->charset = MCS_ascii_general_ci;
          self->PFN_PyUnicode_Encode = PyUnicode_EncodeASCII;
        }
        else
          if (strcmp (pstrCharset, "cp1250") == 0)
          {
            self->charset = MCS_cp1250_general_ci;
            self->PFN_PyUnicode_Encode = PyUnicode_EncodeCP1250Helper;
          }
          else
          {
            return PyErr_Format (PyExc_ValueError, "Unsupported character set '%s' specified", pstrCharset);
          }
  }
  else
  {
    self->charset = MCS_utf8_general_ci;
    self->PFN_PyUnicode_Encode = PyUnicode_EncodeUTF8;
  }

  if (!UMConnection_Connect (self->conn, host, port, username, password, database, acObj ? &autoCommit : NULL, self->charset))
  {
    return HandleError(self, "connect");
  }

  Py_RETURN_NONE;
}
Exemple #17
0
bool Connection::connect(const char *_host, int _port, const char *_username, const char *_password, const char *_database, int *_autoCommit, MYSQL_CHARSETS _charset)
{
  m_dbgMethodProgress ++;

  if (m_dbgMethodProgress > 1)
  {
    /*
    NOTE: We don't call setError here because it will close the socket worsening the concurrent access error making it impossible to trace */
    m_errorMessage = "Concurrent access in connect method";
    m_errno = 0;
    m_errorType = UME_OTHER;
    m_dbgMethodProgress --;
    return false;
  }


  if (m_sockInst != NULL)
  {
    m_dbgMethodProgress --;
    setError ("Socket already connected", 0, UME_OTHER);
    return false;
  }

  m_host = _host ? _host : "localhost";
  m_port = _port ? _port : 3306;
  m_username = _username ? _username : "";
  m_password = _password ? _password : "";
  m_database = _database ? _database : "";
  m_autoCommit = _autoCommit ? (*_autoCommit) != 0 : false;
  m_charset = _charset;

  PRINTMARK();
  m_sockInst = m_capi.getSocket();

  if (m_sockInst == NULL)
  {
    m_dbgMethodProgress --;
    return false;
  }

  if (m_timeout != -1)
  {
    if (!setTimeout (m_timeout))
    {
      m_dbgMethodProgress --;
      return false;
    }
  }

  if (!connectSocket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  if (!recvPacket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  if (!processHandshake())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  if (!sendPacket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  m_writer.reset();

  if (!recvPacket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  UINT8 result = m_reader.readByte();
  if (result == 0xff)
  {
    handleErrorPacket();
    m_dbgMethodProgress --;
    return false;
  }

  m_reader.skip();

  PRINTMARK();
  if (_autoCommit)
  {
    PRINTMARK();
    char strTemp[256 + 1];
    PRINTMARK();
    size_t len = snprintf (strTemp, 256, "SET AUTOCOMMIT = %d", *_autoCommit);
    PRINTMARK();
    m_writer.reset();
    m_writer.writeByte(MC_QUERY);
    m_writer.writeBytes ( (void *) strTemp, len);
    m_writer.finalize(0);

    PRINTMARK();
    if (!sendPacket())
    {
      m_dbgMethodProgress --;
      return false;
    }

    PRINTMARK();
    if (!recvPacket())
    {
      m_dbgMethodProgress --;
      return false;
    }
    m_reader.skip();
  }

  PRINTMARK();
  m_state = QUERY_WAIT;
  m_dbgMethodProgress --;

  return true;
}
Exemple #18
0
PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
{
  static char *kwlist[] = { "obj", "ensure_ascii", "double_precision", "encode_html_chars", NULL};

  char buffer[65536];
  char *ret;
  PyObject *newobj;
  PyObject *oinput = NULL;
  PyObject *oensureAscii = NULL;
  static const int idoublePrecision = 10; // default double precision setting
  PyObject *oencodeHTMLChars = NULL;

  JSONObjectEncoder encoder =
  {
    Object_beginTypeContext,
    Object_endTypeContext,
    Object_getStringValue,
    Object_getLongValue,
    Object_getIntValue,
    Object_getDoubleValue,
    Object_iterBegin,
    Object_iterNext,
    Object_iterEnd,
    Object_iterGetValue,
    Object_iterGetName,
    Object_releaseObject,
    PyObject_Malloc,
    PyObject_Realloc,
    PyObject_Free,
    -1, //recursionMax
    idoublePrecision,
    1, //forceAscii
#if HAS_JSON_ENCODE_HTML_CHARS_DEFAULT_TRUE
    1, //encodeHTMLChars
#else
    0, //encodeHTMLChars
#endif
  };


  PRINTMARK();

  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OiO", kwlist, &oinput, &oensureAscii, &idoublePrecision, &oencodeHTMLChars))
  {
    return NULL;
  }

  if (oensureAscii != NULL && !PyObject_IsTrue(oensureAscii))
  {
    encoder.forceASCII = 0;
  }

  if (oencodeHTMLChars != NULL && PyObject_IsTrue(oencodeHTMLChars))
  {
    encoder.encodeHTMLChars = 1;
  }

  encoder.doublePrecision = idoublePrecision;

  PRINTMARK();
  ret = JSON_EncodeObject (oinput, &encoder, buffer, sizeof (buffer));
  PRINTMARK();

  if (PyErr_Occurred())
  {
    return NULL;
  }

  if (encoder.errorMsg)
  {
    if (ret != buffer)
    {
      encoder.free (ret);
    }

    PyErr_Format (PyExc_OverflowError, "%s", encoder.errorMsg);
    return NULL;
  }

  newobj = PyString_FromString (ret);

  if (ret != buffer)
  {
    encoder.free (ret);
  }

  PRINTMARK();

  return newobj;
}
Exemple #19
0
//=============================================================================
// Dict iteration functions
// itemName might converted to string (Python_Str). Do refCounting
// itemValue is borrowed from object (which is dict). No refCounting
//=============================================================================
void Dict_iterBegin(JSOBJ obj, JSONTypeContext *tc)
{
  GET_TC(tc)->index = 0;
  PRINTMARK();
}
Exemple #20
0
JSOBJ Dir_iterGetValue(JSOBJ obj, JSONTypeContext *tc)
{
  PRINTMARK();
  return GET_TC(tc)->itemValue;
}
Exemple #21
0
int Object_npyArrayAddItem(void *prv, JSOBJ obj, JSOBJ value)
{
  PyObject* type;
  PyArray_Descr* dtype;
  npy_intp i;
  char *new_data, *item;
  NpyArrContext* npyarr = (NpyArrContext*) obj;
  PRINTMARK();
  if (!npyarr)
  {
    return 0;
  }

  i = npyarr->i;

  npyarr->shape.ptr[npyarr->dec->curdim-1]++;

  if (PyArray_Check((PyObject*)value))
  {
    // multidimensional array, keep decoding values.
    return 1;
  }

  if (!npyarr->ret)
  {
    // Array not initialised yet.
    // We do it here so we can 'sniff' the data type if none was provided
    if (!npyarr->dec->dtype)
    {
      type = PyObject_Type(value);
      if(!PyArray_DescrConverter(type, &dtype))
      {
        Py_DECREF(type);
        goto fail;
      }
      Py_INCREF(dtype);
      Py_DECREF(type);
    }
    else
    {
      dtype = PyArray_DescrNew(npyarr->dec->dtype);
    }

    // If it's an object or string then fill a Python list and subsequently
    // convert. Otherwise we would need to somehow mess about with
    // reference counts when renewing memory.
    npyarr->elsize = dtype->elsize;
    if (PyDataType_REFCHK(dtype) || npyarr->elsize == 0)
    {
      Py_XDECREF(dtype);

      if (npyarr->dec->curdim > 1)
      {
        PyErr_SetString(PyExc_ValueError, "Cannot decode multidimensional arrays with variable length elements to numpy");
        goto fail;
      }
      npyarr->elcount = 0;
      npyarr->ret = PyList_New(0);
      if (!npyarr->ret)
      {
        goto fail;
      }
      ((JSONObjectDecoder*)npyarr->dec)->newArray = Object_npyNewArrayList;
      ((JSONObjectDecoder*)npyarr->dec)->arrayAddItem = Object_npyArrayListAddItem;
      ((JSONObjectDecoder*)npyarr->dec)->endArray = Object_npyEndArrayList;
      return Object_npyArrayListAddItem(prv, obj, value);
    }

    npyarr->ret = PyArray_NewFromDescr(&PyArray_Type, dtype, 1,
        &npyarr->elcount, NULL,NULL, 0, NULL);

    if (!npyarr->ret)
    {
      goto fail;
    }
  }

  if (i >= npyarr->elcount) {
    // Grow PyArray_DATA(ret):
    // this is similar for the strategy for PyListObject, but we use
    // 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ...
    if (npyarr->elsize == 0)
    {
      PyErr_SetString(PyExc_ValueError, "Cannot decode multidimensional arrays with variable length elements to numpy");
      goto fail;
    }

    npyarr->elcount = (i >> 1) + (i < 4 ? 4 : 2) + i;
    if (npyarr->elcount <= NPY_MAX_INTP/npyarr->elsize) {
      new_data = PyDataMem_RENEW(PyArray_DATA(npyarr->ret), npyarr->elcount * npyarr->elsize);
    }
    else {
      PyErr_NoMemory();
      goto fail;
    }
    ((PyArrayObject*) npyarr->ret)->data = (void*) new_data;

    // PyArray_BYTES(npyarr->ret) = new_data;
  }

  PyArray_DIMS(npyarr->ret)[0] = i + 1;

  if ((item = PyArray_GETPTR1(npyarr->ret, i)) == NULL
      || PyArray_SETITEM(npyarr->ret, item, value) == -1) {
    goto fail;
  }

  Py_DECREF( (PyObject *) value);
  npyarr->i++;
  return 1;

fail:

  Npy_releaseContext(npyarr);
  return 0;
}
Exemple #22
0
PyObject* JSONToObj(PyObject* self, PyObject *args, PyObject *kwargs)
{
    PyObject *ret;
    PyObject *sarg;
    JSONObjectDecoder *decoder;
	PyObjectDecoder pyDecoder;
    PyArray_Descr *dtype = NULL;
    static char *kwlist[] = { "obj", "numpy", "labelled", "dtype", NULL};
    int numpy = 0, labelled = 0, decref = 0;
    // PRINTMARK();

    JSONObjectDecoder dec = {
            Object_newString,
            Object_objectAddKey,
            Object_arrayAddItem,
            Object_newTrue,
            Object_newFalse,
            Object_newNull,
            Object_newObject,
            Object_endObject,
            Object_newArray,
            Object_endArray,
            Object_newInteger,
            Object_newLong,
            Object_newDouble,
            Object_releaseObject,
            PyObject_Malloc,
            PyObject_Free,
            PyObject_Realloc,
    };
    pyDecoder.dec = dec;
    pyDecoder.curdim = 0;
    pyDecoder.npyarr = NULL;
    pyDecoder.npyarr_addr = NULL;

    decoder = (JSONObjectDecoder*) &pyDecoder;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iiO&", kwlist, &sarg, &numpy, &labelled, PyArray_DescrConverter2, &dtype))
    {
        Npy_releaseContext(pyDecoder.npyarr);
        return NULL;
    }

    if (PyUnicode_Check(sarg))
    {
        sarg = PyUnicode_AsUTF8String(sarg);
        if (sarg == NULL)
        {
            //Exception raised above us by codec according to docs
            return NULL;
        }
        decref = 1;
    }
    else
    if (!PyString_Check(sarg))
    {
        PyErr_Format(PyExc_TypeError, "Expected String or Unicode");
        return NULL;
    }

    if (numpy)
    {
        pyDecoder.dtype = dtype;
        decoder->newArray = Object_npyNewArray;
        decoder->endArray = Object_npyEndArray;
        decoder->arrayAddItem = Object_npyArrayAddItem;

        if (labelled)
        {
            decoder->newObject = Object_npyNewObject;
            decoder->endObject = Object_npyEndObject;
            decoder->objectAddKey = Object_npyObjectAddKey;
        }
    }

    decoder->errorStr = NULL;
    decoder->errorOffset = NULL;

    PRINTMARK();
    ret = JSON_DecodeObject(decoder, PyString_AS_STRING(sarg), PyString_GET_SIZE(sarg));
    PRINTMARK();

    if (decref)
    {
        Py_DECREF(sarg);
    }

    if (PyErr_Occurred())
    {
        return NULL;
    }

    if (decoder->errorStr)
    {
        /*FIXME: It's possible to give a much nicer error message here with actual failing element in input etc*/
        PyErr_Format (PyExc_ValueError, "%s", decoder->errorStr);
        Py_XDECREF( (PyObject *) ret);
        Npy_releaseContext(pyDecoder.npyarr);

        return NULL;
    }

    return ret;
}
Exemple #23
0
int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj = (PyObject *) _obj;
  PyObject *itemValue = GET_TC(tc)->itemValue;
  PyObject *itemName = GET_TC(tc)->itemName;
  PyObject* attr;
  PyObject* attrName;
  char* attrStr;

  if (itemValue)
  {
    Py_DECREF(GET_TC(tc)->itemValue);
    GET_TC(tc)->itemValue = itemValue = NULL;
  }

  if (itemName)
  {
    Py_DECREF(GET_TC(tc)->itemName);
    GET_TC(tc)->itemName = itemName = NULL;
  }

  for (; GET_TC(tc)->index  < GET_TC(tc)->size; GET_TC(tc)->index ++)
  {
    attrName = PyList_GET_ITEM(GET_TC(tc)->attrList, GET_TC(tc)->index);
#if PY_MAJOR_VERSION >= 3
    attr = PyUnicode_AsUTF8String(attrName);
#else
    attr = attrName;
    Py_INCREF(attr);
#endif
    attrStr = PyString_AS_STRING(attr);

    if (attrStr[0] == '_')
    {
      PRINTMARK();
      Py_DECREF(attr);
      continue;
    }

    itemValue = PyObject_GetAttr(obj, attrName);
    if (itemValue == NULL)
    {
      PyErr_Clear();
      Py_DECREF(attr);
      PRINTMARK();
      continue;
    }

    if (PyCallable_Check(itemValue))
    {
      Py_DECREF(itemValue);
      Py_DECREF(attr);
      PRINTMARK();
      continue;
    }

    PRINTMARK();
    itemName = attr;
    break;
  }

  if (itemName == NULL)
  {
    GET_TC(tc)->index = GET_TC(tc)->size;
    GET_TC(tc)->itemValue = NULL;
    return 0;
  }

  GET_TC(tc)->itemName = itemName;
  GET_TC(tc)->itemValue = itemValue;
  GET_TC(tc)->index ++;

  PRINTMARK();
  return 1;
}
Exemple #24
0
void *Connection::query(const char *_query, size_t _cbQuery)
{
  m_dbgMethodProgress ++;

  if (m_dbgMethodProgress > 1)
  {
    /*
    NOTE: We don't call setError here because it will close the socket worsening the concurrent access error making it impossible to trace */
    m_errorMessage = "Concurrent access in query method";
    m_errno = 0;
    m_errorType = UME_OTHER;
    m_dbgMethodProgress --;
    return NULL;
  }

  if (m_sockInst == NULL)
  {
    PRINTMARK();
    setError ("Not connected", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;
  }

  size_t len = _cbQuery;

  if (len > m_writer.getSize () - (MYSQL_PACKET_HEADER_SIZE + 1))
  {
    PRINTMARK();
    setError ("Query too big", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;
  }

  m_writer.reset();
  m_writer.writeByte(MC_QUERY);
  m_writer.writeBytes ( (void *) _query, len);
  m_writer.finalize(0);

  if (!sendPacket())
  {
    PRINTMARK();
    m_dbgMethodProgress --;
    return NULL;
  }

  if (!recvPacket())
  {
    PRINTMARK();
    m_dbgMethodProgress --;
    return NULL;
  }

  UINT8 result = m_reader.readByte();

  switch (result)
  {
  case 0x00:
    PRINTMARK();
    m_dbgMethodProgress --;
    return handleOKPacket();

  case 0xff:
    PRINTMARK();
    handleErrorPacket();
    m_dbgMethodProgress --;
    return NULL;

  case 0xfe:
    PRINTMARK();
    setError ("Unexpected EOF when decoding result", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;


  default:
    PRINTMARK();
    m_dbgMethodProgress --;
    return handleResultPacket((int)result);
  }

  PRINTMARK();
  m_dbgMethodProgress --;
  return NULL;
}
Exemple #25
0
char *Dir_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
  PRINTMARK();
  *outLen = PyString_GET_SIZE(GET_TC(tc)->itemName);
  return PyString_AS_STRING(GET_TC(tc)->itemName);
}
Exemple #26
0
PyObject *Connection_query(Connection *self, PyObject *args)
{
  void *ret;
  PyObject *inQuery = NULL;
  PyObject *query = NULL;
  PyObject *iterable = NULL;
  PyObject *escapedQuery = NULL;

  if (!UMConnection_IsConnected(self->conn))
  {
    return PyErr_Format(PyExc_RuntimeError, "Not connected");
  }

  if (!PyArg_ParseTuple (args, "O|O", &inQuery, &iterable))
  {
    return NULL;
  }

  if (iterable)
  {
    PyObject *iterator = PyObject_GetIter(iterable);

    if (iterator == NULL)
    {
      PyErr_Clear();
      return PyErr_Format(PyExc_TypeError, "Expected iterable");
    }

    Py_DECREF(iterator);
  }

  if (!PyString_Check(inQuery))
  {
    if (!PyUnicode_Check(inQuery))
    {
      PRINTMARK();
      return PyErr_Format(PyExc_TypeError, "Query argument must be either String or Unicode");
    }

    query = self->PFN_PyUnicode_Encode(PyUnicode_AS_UNICODE(inQuery), PyUnicode_GET_SIZE(inQuery), NULL);

    if (query == NULL)
    {
      if (!PyErr_Occurred())
      {
        PyErr_SetObject(PyExc_ValueError, query);
        return NULL;
      }

      return NULL;
    }
  }
  else
  {
    query = inQuery;
    Py_INCREF(query);
  }

  if (iterable)
  {
    PRINTMARK();
    escapedQuery = EscapeQueryArguments(self, query, iterable);
    Py_DECREF(query);

    if (escapedQuery == NULL)
    {
      if (!PyErr_Occurred())
      {
        return PyErr_Format(PyExc_RuntimeError, "Exception not set in EscapeQueryArguments chain");
      }

      return NULL;
    }

  }
  else
  {
    escapedQuery = query;
  }

  ret =  UMConnection_Query(self->conn, PyString_AS_STRING(escapedQuery), PyString_GET_SIZE(escapedQuery));

  Py_DECREF(escapedQuery);

  PRINTMARK();
  if (ret == NULL)
  {
    return HandleError(self, "query");
  }

  PRINTMARK();
  return (PyObject *) ret;
}
Exemple #27
0
void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
{
  PyObject *obj, *exc, *toDictFunc;
  TypeContext *pc;
  PRINTMARK();
  if (!_obj) {
    tc->type = JT_INVALID;
    return;
  }

  obj = (PyObject*) _obj;

  tc->prv = PyObject_Malloc(sizeof(TypeContext));
  pc = (TypeContext *) tc->prv;
  if (!pc)
  {
    tc->type = JT_INVALID;
    PyErr_NoMemory();
    return;
  }
  pc->newObj = NULL;
  pc->dictObj = NULL;
  pc->itemValue = NULL;
  pc->itemName = NULL;
  pc->attrList = NULL;
  pc->index = 0;
  pc->size = 0;
  pc->longValue = 0;

  if (PyIter_Check(obj))
  {
    PRINTMARK();
    goto ISITERABLE;
  }

  if (PyBool_Check(obj))
  {
    PRINTMARK();
    tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE;
    return;
  }
  else
  if (PyLong_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyLongToINT64;
    tc->type = JT_LONG;
    GET_TC(tc)->longValue = PyLong_AsLongLong(obj);

    exc = PyErr_Occurred();

    if (exc && PyErr_ExceptionMatches(PyExc_OverflowError))
    {
#if HAS_JSON_HANDLE_BIGINTS
      PyErr_Clear();
      pc->PyTypeToJSON = PyBigIntToSTR;
      tc->type = JT_BIGINT;
      GET_TC(tc)->longValue = 0;
      return;
#endif
      PRINTMARK();
      goto INVALID;
    }

    return;
  }
  else
  if (PyInt_Check(obj))
  {
    PRINTMARK();
#ifdef _LP64
    pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
    pc->PyTypeToJSON = PyIntToINT32; tc->type = JT_INT;
#endif
    return;
  }
  else
  if (PyString_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyStringToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyUnicode_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyUnicodeToUTF8; tc->type = JT_UTF8;
    return;
  }
  else
  if (PyFloat_Check(obj) || (type_decimal && PyObject_IsInstance(obj, type_decimal)))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE;
    return;
  }
  else
  if (PyDateTime_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (PyDate_Check(obj))
  {
    PRINTMARK();
    pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
    return;
  }
  else
  if (obj == Py_None)
  {
    PRINTMARK();
    tc->type = JT_NULL;
    return;
  }

ISITERABLE:
  if (PyDict_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_OBJECT;
    pc->iterBegin = Dict_iterBegin;
    pc->iterEnd = Dict_iterEnd;
    pc->iterNext = Dict_iterNext;
    pc->iterGetValue = Dict_iterGetValue;
    pc->iterGetName = Dict_iterGetName;
    pc->dictObj = obj;
    Py_INCREF(obj);
    return;
  }
  else
  if (PyList_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = List_iterBegin;
    pc->iterEnd = List_iterEnd;
    pc->iterNext = List_iterNext;
    pc->iterGetValue = List_iterGetValue;
    pc->iterGetName = List_iterGetName;
    return;
  }
  else
  if (PyTuple_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = Tuple_iterBegin;
    pc->iterEnd = Tuple_iterEnd;
    pc->iterNext = Tuple_iterNext;
    pc->iterGetValue = Tuple_iterGetValue;
    pc->iterGetName = Tuple_iterGetName;
    return;
  }
  else
  if (PyAnySet_Check(obj))
  {
    PRINTMARK();
    tc->type = JT_ARRAY;
    pc->iterBegin = Iter_iterBegin;
    pc->iterEnd = Iter_iterEnd;
    pc->iterNext = Iter_iterNext;
    pc->iterGetValue = Iter_iterGetValue;
    pc->iterGetName = Iter_iterGetName;
    return;
  }

  toDictFunc = PyObject_GetAttrString(obj, "toDict");

  if (toDictFunc)
  {
    PyObject* tuple = PyTuple_New(0);
    PyObject* toDictResult = PyObject_Call(toDictFunc, tuple, NULL);
    Py_DECREF(tuple);
    Py_DECREF(toDictFunc);

    if (toDictResult == NULL)
    {
      PyErr_Clear();
      tc->type = JT_NULL;
      return;
    }

    if (!PyDict_Check(toDictResult))
    {
      Py_DECREF(toDictResult);
      tc->type = JT_NULL;
      return;
    }

    PRINTMARK();
    tc->type = JT_OBJECT;
    pc->iterBegin = Dict_iterBegin;
    pc->iterEnd = Dict_iterEnd;
    pc->iterNext = Dict_iterNext;
    pc->iterGetValue = Dict_iterGetValue;
    pc->iterGetName = Dict_iterGetName;
    pc->dictObj = toDictResult;
    return;
  }

  PyErr_Clear();

  PRINTMARK();
  // Falling to INVALID case as this type of object(class instance, module,
  // class, function, etc..) can't be serialized.
  PyErr_Format (PyExc_TypeError, "%s", "Object is not JSON serializable");

INVALID:
  tc->type = JT_INVALID;
  PyObject_Free(tc->prv);
  tc->prv = NULL;
  return;
}
Exemple #28
0
void API_resultRowBegin(void *result)
{
  PRINTMARK();
  ((ResultSet *)result)->currRow = PyTuple_New(((ResultSet *)result)->numFields);	
  PRINTMARK();
}
Exemple #29
0
PyObject* objToJSONFile(PyObject* self, PyObject *args, PyObject *kwargs)
{
  PyObject *data;
  PyObject *file;
  PyObject *string;
  PyObject *write;
  PyObject *argtuple;

  PRINTMARK();

  if (!PyArg_ParseTuple (args, "OO", &data, &file))
  {
    return NULL;
  }

  if (!PyObject_HasAttrString (file, "write"))
  {
    PyErr_Format (PyExc_TypeError, "expected file");
    return NULL;
  }

  write = PyObject_GetAttrString (file, "write");

  if (!PyCallable_Check (write))
  {
    Py_XDECREF(write);
    PyErr_Format (PyExc_TypeError, "expected file");
    return NULL;
  }

  argtuple = PyTuple_Pack(1, data);

  string = objToJSON (self, argtuple, kwargs);

  if (string == NULL)
  {
    Py_XDECREF(write);
    Py_XDECREF(argtuple);
    return NULL;
  }

  Py_XDECREF(argtuple);

  argtuple = PyTuple_Pack (1, string);
  if (argtuple == NULL)
  {
    Py_XDECREF(write);
    return NULL;
  }
  if (PyObject_CallObject (write, argtuple) == NULL)
  {
    Py_XDECREF(write);
    Py_XDECREF(argtuple);
    return NULL;
  }

  Py_XDECREF(write);
  Py_DECREF(argtuple);
  Py_XDECREF(string);

  PRINTMARK();

  Py_RETURN_NONE;
}
Exemple #30
0
int API_resultRowValue(void *result, int column, UMTypeInfo *ti, char *value, size_t cbValue)
{
  PyObject *valobj = NULL;

  PRINTMARK();
  //fprintf (stderr, "%s: Got %p (%08x) %08x\n", __FUNCTION__, value, ti->type, cbValue);

  if (value == NULL)
  {
    valobj = Py_None;
    Py_IncRef(valobj);
  }
  else
  {

    switch (ti->type)
    {
      //PyNone:
    case MFTYPE_NULL:
      valobj = Py_None;
      Py_IncRef(valobj);
      break;

      // Use PyLong for "INT UNSIGNED".
    case MFTYPE_LONG:
      if(isUnsigned(ti->flags)){
        // XXX: No overflow detected.
        valobj = PyLong_FromLongLong(parseINT64 (value, ((char *) value) + cbValue));
        break;
      }
      // "INT" only, let it fall through to PyInt.

      //PyInt
    case MFTYPE_TINY:
    case MFTYPE_SHORT:
    case MFTYPE_INT24:
      {
        valobj = PyInt_FromLong(parseINT32 (value, ((char *) value) + cbValue));
        break;
      }

      //PyLong
    case MFTYPE_LONGLONG:
      {
        if(isUnsigned(ti->flags)){
          valobj = PyLong_FromUnsignedLongLong(parseUINT64 (value, ((char *) value) + cbValue));
        }else{
          valobj = PyLong_FromLongLong(parseINT64 (value, ((char *) value) + cbValue));
        }
        break;
      }

      //PyFloat
    case MFTYPE_FLOAT:
    case MFTYPE_DOUBLE:
      {
        //FIXME: Too f*****g slow
        PyObject *sobj = PyString_FromStringAndSize((char *) value, cbValue);
        valobj = PyFloat_FromString (sobj, NULL);
        Py_DECREF(sobj);
        break;
      }

    case MFTYPE_DATE:
      {
        int year;
        int month;
        int day;

        year = parseINT32 (value, value + 4);

        if (year < 1)
        {
          valobj = Py_None;
          Py_IncRef(valobj);
          break;
        }

        value += 5;
        month = parseINT32 (value, value + 2);
        value += 3;
        day = parseINT32 (value, value + 2);
        value += 3;

        valobj = PyDate_FromDate (year, month, day);
        break;
      }

    case MFTYPE_TIMESTAMP:
    case MFTYPE_DATETIME:
      {
        int year;
        int month;
        int day;
        int hour;
        int minute;
        int second;

        //9999-12-31 23:59:59
        char temp[20];
        memcpy (temp, value, cbValue);
        temp[cbValue] = '\0';

        year = parseINT32 (value, value + 4);
        value += 5;
        month = parseINT32 (value, value + 2);
        value += 3;
        day = parseINT32 (value, value + 2);
        value += 3;
        hour = parseINT32 (value, value + 2);
        value += 3;
        minute = parseINT32 (value, value + 2);
        value += 3;
        second = parseINT32 (value, value + 2);
        value += 3;

        if (year < 1)
        {
          valobj = Py_None;
          Py_IncRef(valobj);
          break;
        }


        valobj = PyDateTime_FromDateAndTime (year, month, day, hour, minute, second, 0);
        break;
      }

      // We ignore these

    case MFTYPE_TIME:
    case MFTYPE_YEAR:
    case MFTYPE_NEWDATE:
      // Fall through for string encoding

      //Blob goes as String
    case MFTYPE_TINY_BLOB:
    case MFTYPE_MEDIUM_BLOB:
    case MFTYPE_LONG_BLOB:
    case MFTYPE_BLOB:
      if (ti->flags & MFFLAG_BINARY_FLAG) {
        valobj = PyString_FromStringAndSize( (const char *) value, cbValue);
      } else {
        valobj = DecodeString (ti, value, cbValue);
      }
      break;

      //PyString family
    case MFTYPE_VAR_STRING:
    case MFTYPE_VARCHAR:
    case MFTYPE_STRING:
      valobj = DecodeString (ti, value, cbValue);
      break;

    case MFTYPE_ENUM:
    case MFTYPE_GEOMETRY:
    case MFTYPE_BIT:
    case MFTYPE_NEWDECIMAL:
    case MFTYPE_SET:
    case MFTYPE_DECIMAL:
      // Fall through for string encoding
      valobj = PyString_FromStringAndSize( (const char *) value, cbValue);
      break;

    }
  }

  if (valobj == NULL)
  {
    if (PyErr_Occurred())
    {
      return FALSE;
    }

    PyErr_Format (umysql_Error, "Unable to convert field of type %d", ti->type);
    return FALSE;
  }

  PyTuple_SET_ITEM(((ResultSet *)result)->currRow, column, valobj);
  PRINTMARK();

  return TRUE;
}