Example #1
0
static PyObject* GetDataTimestamp(Cursor* cur, Py_ssize_t iCol)
{
    TIMESTAMP_STRUCT value;

    SQLLEN cbFetched = 0;
    SQLRETURN ret;

    Py_BEGIN_ALLOW_THREADS
    ret = SQLGetData(cur->hstmt, (SQLUSMALLINT)(iCol+1), SQL_C_TYPE_TIMESTAMP, &value, sizeof(value), &cbFetched);
    Py_END_ALLOW_THREADS
    if (!SQL_SUCCEEDED(ret))
        return RaiseErrorFromHandle("SQLGetData", cur->cnxn->hdbc, cur->hstmt);

    if (cbFetched == SQL_NULL_DATA)
        Py_RETURN_NONE;

    switch (cur->colinfos[iCol].sql_type)
    {
    case SQL_TYPE_TIME:
    {
        int micros = (int)(value.fraction / 1000); // nanos --> micros
        return PyTime_FromTime(value.hour, value.minute, value.second, micros);
    }

    case SQL_TYPE_DATE:
        return PyDate_FromDate(value.year, value.month, value.day);
    }

    int micros = (int)(value.fraction / 1000); // nanos --> micros
    return PyDateTime_FromDateAndTime(value.year, value.month, value.day, value.hour, value.minute, value.second, micros);
}
Example #2
0
PyObject* MI2Py(const MI_Value& value, MI_Type valueType, MI_Uint32 flags)
{
    if (flags & MI_FLAG_NULL)
        Py_RETURN_NONE;

    if (valueType & MI_ARRAY)
    {
        return MIArray2PyTuple(value, (MI_Type)(valueType ^ MI_ARRAY));
    }

    switch (valueType)
    {
    case MI_BOOLEAN:
        return PyBool_FromLong(value.boolean);
    case MI_SINT8:
        return PyLong_FromLong(value.sint8);
    case MI_UINT8:
        return PyLong_FromUnsignedLong(value.uint8);
    case MI_SINT16:
        return PyLong_FromLong(value.sint16);
    case MI_UINT16:
        return PyLong_FromUnsignedLong(value.uint16);
    case MI_SINT32:
        return PyLong_FromLong(value.sint32);
    case MI_UINT32:
        return PyLong_FromUnsignedLong(value.uint32);
    case MI_SINT64:
        return PyLong_FromLongLong(value.sint64);
    case MI_UINT64:
        return PyLong_FromUnsignedLongLong(value.uint64);
    case MI_REAL32:
        return PyFloat_FromDouble(value.real32);
    case MI_REAL64:
        return PyFloat_FromDouble(value.real64);
    case MI_CHAR16:
        return PyLong_FromLong(value.char16);
    case MI_DATETIME:
        // TODO: understand where this import needs to be called
        PyDateTime_IMPORT;
        if (value.datetime.isTimestamp)
        {
            const MI_Timestamp& ts = value.datetime.u.timestamp;
            // TODO: Add timezone support!
            return PyDateTime_FromDateAndTime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, ts.microseconds);
        }
        else
        {
            return PyDeltaFromMIInterval(value.datetime.u.interval);
        }
        break;
    case MI_STRING:
        return PyUnicode_FromWideChar(value.string, wcslen(value.string));
    case MI_INSTANCE:
        return (PyObject*)Instance_New(std::make_shared<MI::Instance>(value.instance, false));
    case MI_REFERENCE:
        return (PyObject*)Instance_New(std::make_shared<MI::Instance>(value.reference, false));
    default:
        throw MI::TypeConversionException();
    }
}
static PyObject *meth_QDateTime_toPyDateTime(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        QDateTime *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QDateTime, &sipCpp))
        {
            PyObject * sipRes = 0;

#line 484 "/home/tsheasha/GUC/Bachelors/android-python27/python-build/PyQt-x11-gpl-4.8/sip/QtCore/qdatetime.sip"
        if (!PyDateTimeAPI)
            PyDateTime_IMPORT;
        
        // Convert to a Python datetime object.
        QDate qd = sipCpp->date();
        QTime qt = sipCpp->time();
        
        sipRes = PyDateTime_FromDateAndTime(qd.year(), qd.month(), qd.day(),
                                            qt.hour(), qt.minute(), qt.second(), qt.msec() * 1000);
#line 84 "sipQtCoreQDateTime.cpp"

            return sipRes;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QDateTime, sipName_toPyDateTime, NULL);

    return NULL;
}
Example #4
0
static PyObject *
str_to_datetime(PyObject *self, PyObject *arg)
{
    const char *str;
    unsigned int year, month, day, hour, minute, second, microsecond = 0;

    if (arg == Py_None)
        Py_RETURN_NONE;

    str = PyString_AsString(arg);
    if (str == NULL)
        return NULL;

    /* microseconds are optional */
    /*
    TODO: this is slightly less picky than the Python version which would
    not accept "2000-01-01 00:00:00.". I don't know which is better, but they
    should be coherent.
    */
    if (sscanf(str, "%4u-%2u-%2u %2u:%2u:%2u.%6u", &year, &month, &day,
               &hour, &minute, &second, &microsecond) < 6) {
        PyErr_SetString(PyExc_ValueError, "Couldn't parse datetime string.");
        return NULL;
    }
    return PyDateTime_FromDateAndTime(year, month, day,
                                      hour, minute, second, microsecond);
}
PyObject* Python::BrokenDateTimeToPy(const BrokenDateTime &datetime) {
  PyDateTime_IMPORT;

  return PyDateTime_FromDateAndTime(
    datetime.year, datetime.month, datetime.day,
    datetime.hour, datetime.minute, datetime.second,
    0);
};
Example #6
0
 PyObject *Device::getDateTimeFromTimeval(const struct timeval &time) {
   const time_t seconds = time.tv_sec;
   struct tm* t = gmtime ( &seconds );
   if (t) {
     return PyDateTime_FromDateAndTime(t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, time.tv_usec);
   }
   return NULL;
 }
Example #7
0
//-----------------------------------------------------------------------------
// TimestampVar_GetValue()
//   Returns the value stored at the given array position.
//-----------------------------------------------------------------------------
static PyObject *TimestampVar_GetValue(
    udt_TimestampVar *var,              // variable to determine value for
    unsigned pos)                       // array position
{
    TIMESTAMP_STRUCT *sqlValue;

    sqlValue = &var->data[pos];
    return PyDateTime_FromDateAndTime(sqlValue->year, sqlValue->month,
            sqlValue->day, sqlValue->hour, sqlValue->minute, sqlValue->second,
            sqlValue->fraction / 1000);
}
Example #8
0
static 
PyObject* from_timestamp_kobject(K x){
     PyDateTime_IMPORT;
     PyObject* result ;
     Py_ssize_t i, length ;
     length = (Py_ssize_t)(x->n);
     int year, month, day, hour, minute, second, usecond;

     if(scalar(x)) {
	  double value = x->j / 1e9;
	  timestamp_helper(value, &year, &month, &day, &hour, &minute, &second, &usecond);
	  result = PyDateTime_FromDateAndTime(year, month, day, hour, minute, second, usecond);
     }
     else {
	  result = PyList_New(length);
	  for(i = 0 ; i != length; ++i) {
	       double value = xJ[i] / 1e9;
	       timestamp_helper(value, &year, &month, &day, &hour, &minute, &second, &usecond);
	       PyList_SetItem(result, i, PyDateTime_FromDateAndTime(year, month, day, hour, minute, second, usecond));
	  }
     }
     return result;
}
/* Date stuff */
static PyObject* datetime_from_millis(long long millis) {
    int microseconds = (millis % 1000) * 1000;
    Time64_T seconds = millis / 1000;
    struct TM timeinfo;
    gmtime64_r(&seconds, &timeinfo);

    return PyDateTime_FromDateAndTime(timeinfo.tm_year + 1900,
                                      timeinfo.tm_mon + 1,
                                      timeinfo.tm_mday,
                                      timeinfo.tm_hour,
                                      timeinfo.tm_min,
                                      timeinfo.tm_sec,
                                      microseconds);
}
Example #10
0
/**
 * PyRRD_DateTime_FromTS: convert UNIX timestamp (time_t)
 * to Python datetime object.
 *
 * @param ts UNIX timestamp (time_t)
 * @return Pointer to new PyObject (New Reference)
 */
static PyObject *
PyRRD_DateTime_FromTS(time_t ts)
{
    PyObject *ret;
    struct tm lt;

    localtime_r(&ts, &lt);

    ret = PyDateTime_FromDateAndTime(
        lt.tm_year + 1900,
        lt.tm_mon + 1,
        lt.tm_mday,
        lt.tm_hour,
        lt.tm_min,
        lt.tm_sec,
        0);

    return ret;
}
	static PyObject *convert( const posix_time::ptime &t )
	{
		if ( t.is_special() )
		{
			PyErr_SetString(PyExc_ValueError, "Cannot convert out-of-range ptime to datetime");
			throw_error_already_set();
		}

		gregorian::date date = t.date();
		posix_time::time_duration dur = t.time_of_day();
		return PyDateTime_FromDateAndTime(
			static_cast<int>( date.year() ),
			static_cast<int>( date.month() ),
			static_cast<int>( date.day() ),
			static_cast<int>( dur.hours() ),
			static_cast<int>( dur.minutes() ),
			static_cast<int>( dur.seconds() ),
			getMicroseconds( dur )
		);
	}
Example #12
0
static PyObject *to_python_datetime(JSContext *context, JSObject *obj) {
    jsval year, month, day, hour, minute, second;
    if (!JS_CallFunctionName(context, obj, "getFullYear", 0, NULL, &year)) {
        return NULL;
    }
    if (!JS_CallFunctionName(context, obj, "getMonth", 0, NULL, &month)) {
        return NULL;
    }
    if (!JS_CallFunctionName(context, obj, "getDate", 0, NULL, &day)) {
        return NULL;
    }
    if (!JS_CallFunctionName(context, obj, "getHours", 0, NULL, &hour)) {
        return NULL;
    }
    if (!JS_CallFunctionName(context, obj, "getMinutes", 0, NULL, &minute)) {
        return NULL;
    }
    if (!JS_CallFunctionName(context, obj, "getSeconds", 0, NULL, &second)) {
        return NULL;
    }
    return PyDateTime_FromDateAndTime(JSVAL_TO_INT(year), JSVAL_TO_INT(month) + 1,
        JSVAL_TO_INT(day), JSVAL_TO_INT(hour), JSVAL_TO_INT(minute),
        JSVAL_TO_INT(second), 0);
}
Example #13
0
static PyObject *
str_to_datetime(PyObject *self, PyObject *arg)
{
#if PY_MAJOR_VERSION >= 3
    PyObject *bytes;
    PyObject *err_bytes;
#endif
    const char *str;
    int numparsed;
    unsigned int year, month, day, hour, minute, second, microsecond = 0;
    PyObject *err_repr;

    if (arg == Py_None)
        Py_RETURN_NONE;

#if PY_MAJOR_VERSION >= 3
    bytes = PyUnicode_AsASCIIString(arg);
    if (bytes == NULL)
        str = NULL;
    else
        str = PyBytes_AS_STRING(bytes);
#else
    str = PyString_AsString(arg);
#endif
    if (str == NULL) {
        err_repr = PyObject_Repr(arg);
        if (err_repr == NULL)
            return NULL;
#if PY_MAJOR_VERSION >= 3
        err_bytes = PyUnicode_AsASCIIString(err_repr);
        if (err_bytes == NULL)
            return NULL;
        PyErr_Format(
                PyExc_ValueError,
                "Couldn't parse datetime string '%.200s' "
                "- value is not a string.",
                PyBytes_AS_STRING(err_bytes));
        Py_DECREF(err_bytes);
#else
        PyErr_Format(
                PyExc_ValueError,
                "Couldn't parse datetime string '%.200s' "
                "- value is not a string.",
                PyString_AsString(err_repr));
#endif
        Py_DECREF(err_repr);
        return NULL;
    }

    /* microseconds are optional */
    /*
    TODO: this is slightly less picky than the Python version which would
    not accept "2000-01-01 00:00:00.". I don't know which is better, but they
    should be coherent.
    */
    numparsed = sscanf(str, "%4u-%2u-%2u %2u:%2u:%2u.%6u", &year, &month, &day,
                       &hour, &minute, &second, &microsecond);
#if PY_MAJOR_VERSION >= 3
    Py_DECREF(bytes);
#endif
    if (numparsed < 6) {
        err_repr = PyObject_Repr(arg);
        if (err_repr == NULL)
            return NULL;
#if PY_MAJOR_VERSION >= 3
        err_bytes = PyUnicode_AsASCIIString(err_repr);
        if (err_bytes == NULL)
            return NULL;
        PyErr_Format(
                PyExc_ValueError,
                "Couldn't parse datetime string: %.200s",
                PyBytes_AS_STRING(err_bytes));
        Py_DECREF(err_bytes);
#else
        PyErr_Format(
                PyExc_ValueError,
                "Couldn't parse datetime string: %.200s",
                PyString_AsString(err_repr));
#endif
        Py_DECREF(err_repr);
        return NULL;
    }
    return PyDateTime_FromDateAndTime(year, month, day,
                                      hour, minute, second, microsecond);
}
/**
  Convert a DATETIME MySQL value to Python datetime.datetime.

  Convert a DATETIME MySQL value to Python datetime.datetime. The
  fractional part is supported.

  @param    data        string to be converted
  @param    length      length of data

  @return   datetime.datetime object.
    @retval PyDateTime OK
*/
PyObject*
mytopy_datetime(const char *data, const unsigned long length)
{
	int year= 0, month= 0, day= 0;
	int hours= 0, mins= 0, secs= 0, usecs= 0;
    int value= 0;
    int parts[7]= {0};
    int part= 0;
    const char *end= data + length;

    PyDateTime_IMPORT;

    /* Parse year, month, days, hours, minutes and seconds */
    for (;;)
    {
        for (value= 0; data != end && isdigit(*data) ; data++)
        {
            value= (value * 10) + (unsigned int)(*data - '0');
        }
        parts[part++]= (unsigned int)value;
        if (part == 8 || (end-data) < 2
            || (*data != '-' && *data != ':' && *data != ' ')
            || !isdigit(data[1]))
        {
            break;
        }
        data++;  // skip separators '-' and ':'
    }

    if (data != end && end - data >= 2 && *data == '.')
    {
        // Fractional part
        int field_length= 6;   // max fractional - 1
        data++;
        value= (unsigned int)(*data - '0');
        while (data++ != end && isdigit(*data))
        {
            if (field_length-- > 0)
            {
                value= (value * 10) + (unsigned int)(*data - '0');
            }
        }
        parts[6]= value;
    }

    year= parts[0];
    month= parts[1];
    day= parts[2];
    hours= parts[3];
    mins= parts[4];
    secs= parts[5];
    usecs= parts[6];

    if (!is_valid_date(year, month, day))
    {
        Py_RETURN_NONE;
    }

    if (!is_valid_time(hours, mins, secs, usecs))
    {
        Py_RETURN_NONE;
    }

    return PyDateTime_FromDateAndTime(year, month, day,
                                      hours, mins, secs, usecs);
}
Example #15
0
/* Creates a new datetime object from a FAT date time
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_datetime_new_from_fat_date_time(
           uint32_t fat_date_time )
{
	static char *function      = "pyewf_datetime_new_from_fat_date_time";
	PyObject *date_time_object = NULL;
	uint16_t year              = 0;
	uint8_t days_in_month      = 0;
	uint8_t day_of_month       = 0;
	uint8_t hours              = 0;
	uint8_t minutes            = 0;
	uint8_t month              = 0;
	uint8_t seconds            = 0;

	/* The day of month is stored in the next 5 bits
	 */
	day_of_month    = fat_date_time & 0x1f;
	fat_date_time >>= 5;

	/* The month is stored in the next 4 bits
	 */
	month           = fat_date_time & 0x0f;
	fat_date_time >>= 4;

	/* The year is stored in the next 7 bits starting at 1980
	 */
	year            = 1980 + ( fat_date_time & 0x7f );
	fat_date_time >>= 7;

	/* The number of seconds are stored in the lower 5 bits
	 * in intervals of 2 seconds
	 */
	seconds         = ( fat_date_time & 0x1f ) * 2;
	fat_date_time >>= 5;

	/* The number of minutes are stored in the next 6 bits
	 */
	minutes         = fat_date_time & 0x3f;
	fat_date_time >>= 6;

	/* The number of hours are stored in the next 5 bits
	 */
	hours = fat_date_time & 0x1f;

	/* February (2)
	 */
	if( month == 2 )
	{
		if( ( ( ( year % 4 ) == 0 )
		  &&  ( ( year % 100 ) != 0 ) )
		 || ( ( year % 400 ) == 0 ) )
		{
			days_in_month = 29;
		}
		else
		{
			days_in_month = 28;
		}
	}
	/* April (4), June (6), September (9), November (11)
	 */
	else if( ( month == 4 )
	      || ( month == 6 )
	      || ( month == 9 )
	      || ( month == 11 ) )
	{
		days_in_month = 30;
	}
	/* Januari (1), March (3), May (5), July (7), August (8), October (10), December (12)
	 */
	else if( ( month == 1 )
	      || ( month == 3 )
	      || ( month == 5 )
	      || ( month == 7 )
	      || ( month == 8 )
	      || ( month == 10 )
	      || ( month == 12 ) )
	{
		days_in_month = 31;
	}
	else
	{
		PyErr_Format(
		 PyExc_IOError,
		 "%s: unsupported month: %" PRIu8 ".",
		 function,
		 month );

		return( NULL );
	}
	if( ( day_of_month == 0 )
	 || ( day_of_month > days_in_month ) )
	{
		PyErr_Format(
		 PyExc_IOError,
		 "%s: unsupported day of month: %" PRIu8 ".",
		 function,
		 day_of_month );

		return( NULL );
	}
	PyDateTime_IMPORT;

	date_time_object = (PyObject *) PyDateTime_FromDateAndTime(
	                                 (int) year,
	                                 (int) month,
	                                 (int) day_of_month,
	                                 (int) hours,
	                                 (int) minutes,
	                                 (int) seconds,
	                                 0 );

	return( date_time_object );
}
Example #16
0
/* Creates a new datetime object from a POSIX time
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_datetime_new_from_posix_time(
           uint32_t posix_time )
{
	static char *function      = "pyewf_datetime_new_from_posix_time";
	PyObject *date_time_object = NULL;
	uint16_t days_in_year      = 0;
	uint16_t year              = 0;
	uint8_t day_of_month       = 0;
	uint8_t days_in_month      = 0;
	uint8_t hours              = 0;
	uint8_t minutes            = 0;
	uint8_t month              = 0;
	uint8_t seconds            = 0;

	/* There are 60 seconds in a minute correct the value to minutes
	 */
	seconds     = posix_time % 60;
	posix_time /= 60;

	/* There are 60 minutes in an hour correct the value to hours
	 */
	minutes     = posix_time % 60;
	posix_time /= 60;

	/* There are 24 hours in a day correct the value to days
	 */
	hours       = posix_time % 24;
	posix_time /= 24;

	/* Add 1 day to compensate that Jan 1 1601 is represented as 0
	 */
	posix_time += 1;

	/* Determine the number of years starting at '1 Jan 1970 00:00:00'
	 * correct the value to days within the year
	 */
	year = 1970;

	if( posix_time >= 10957 )
	{
		year = 2000;

		posix_time -= 10957;
	}
	while( posix_time > 0 )
	{
		/* Check for a leap year
		 * The year is ( ( dividable by 4 ) and ( not dividable by 100 ) ) or ( dividable by 400 )
		 */
		if( ( ( ( year % 4 ) == 0 )
		  &&  ( ( year % 100 ) != 0 ) )
		 || ( ( year % 400 ) == 0 ) )
		{
			days_in_year = 366;
		}
		else
		{
			days_in_year = 365;
		}
		if( posix_time <= days_in_year )
		{
			break;
		}
		posix_time -= days_in_year;

		year += 1;
	}
	/* Determine the month correct the value to days within the month
	 */
	month = 1;

	while( posix_time > 0 )
	{
		/* February (2)
		 */
		if( month == 2 )
		{
			if( ( ( ( year % 4 ) == 0 )
			  &&  ( ( year % 100 ) != 0 ) )
			 || ( ( year % 400 ) == 0 ) )
			{
				days_in_month = 29;
			}
			else
			{
				days_in_month = 28;
			}
		}
		/* April (4), June (6), September (9), November (11)
		 */
		else if( ( month == 4 )
		      || ( month == 6 )
		      || ( month == 9 )
		      || ( month == 11 ) )
		{
			days_in_month = 30;
		}
		/* Januari (1), March (3), May (5), July (7), August (8), October (10), December (12)
		 */
		else if( ( month == 1 )
		      || ( month == 3 )
		      || ( month == 5 )
		      || ( month == 7 )
		      || ( month == 8 )
		      || ( month == 10 )
		      || ( month == 12 ) )
		{
			days_in_month = 31;
		}
		/* This should never happen, but just in case
		 */
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unsupported month: %" PRIu8 ".",
			 function,
			 month );

			return( NULL );
		}
		if( posix_time <= days_in_month )
		{
			break;
		}
		posix_time -= days_in_month;

		month += 1;
	}
	/* Determine the day
	 */
	day_of_month = (uint8_t) posix_time;

	PyDateTime_IMPORT;

	date_time_object = (PyObject *) PyDateTime_FromDateAndTime(
	                                 (int) year,
	                                 (int) month,
	                                 (int) day_of_month,
	                                 (int) hours,
	                                 (int) minutes,
	                                 (int) seconds,
	                                 0 );

	return( date_time_object );
}
Example #17
0
PyObject *
to_python(pgctx_t *ctx, dbtype_t db, int flags)
{
    dbtag_t type;
    dbval_t *dv = NULL;
    PyObject *ob = NULL;
    PyObject *k, *v;
    epstr_t ea;
    epfloat_t fa;
    char *ma = NULL;
    uint32_t len = 0;
    _list_t *list;
    _obj_t *obj;
    struct tm tm;
    time_t time;
    long usec;
    int i;
    int64_t ival;
    tphelper_t h;

    if (db.all == 0)
        Py_RETURN_NONE;

    type = db.type;
    if (type == ByteBuffer || type == String) {
        ea.all = db.all;
        len = ea.len;
        ea.val[len] = 0;
        ma = (char*)ea.val;
    } else if (isPtr(type)) {
        dv = dbptr(ctx, db);
        type = dv->type;
        if (type == ByteBuffer || type == String) {
            len = dv->len;
            ma = (char*)dv->sval;
        }
    }


    switch(type) {
        case Boolean:
            ob = db.val ? Py_True : Py_False;
            Py_INCREF(ob);
            break;
        case Int:
            ival = db.val;
            if (ival < LONG_MIN || ival > LONG_MAX) {
                ob = PyLong_FromLongLong(ival);
            } else {
                ob = PyInt_FromLong((long)ival);
            }
            break;
        case Float:
            fa.ival = (int64_t)db.val << 4;
            ob = PyFloat_FromDouble(fa.fval);
            break;
#ifdef WANT_UUID_TYPE
        case Uuid:
            ob = PyObject_CallFunction(uuid_constructor, "Os#", Py_None, dv->uuval, 16);
            break;
#endif
        case ByteBuffer:
            ob = PyString_FromStringAndSize(ma, len);
            break;
        case String:
            ob = PyUnicode_FromStringAndSize(ma, len);
            break;
        case Datetime:
            time = db.val / 1000000LL;
            usec = db.val % 1000000LL;
#ifdef WIN32
            memcpy(&tm, gmtime(&time), sizeof(tm));
#else
            gmtime_r(&time, &tm);
#endif
            ob = PyDateTime_FromDateAndTime(
                    tm.tm_year+1900, tm.tm_mon, tm.tm_mday,
                    tm.tm_hour, tm.tm_min, tm.tm_sec, usec);
            break;
        case List:
            if (flags & TP_PROXY) {
                ob = PongoList_Proxy(ctx, db);
                pidcache_put(ctx, ob, db);
            } else {
                if (flags & TP_PROXYCHLD) flags = (flags & ~TP_PROXYCHLD) | TP_PROXY;
                list = dbptr(ctx, dv->list);
                ob = PyList_New(list->len);
                for(i=0; i<list->len; i++) {
                    v = to_python(ctx, list->item[i], flags);
                    PyList_SET_ITEM(ob, i, v);
                    // Don't need to decref v since SET_ITEM steals the reference
                }
            }
            break;
        case Object:
            if (flags & TP_PROXY) {
                ob = PongoDict_Proxy(ctx, db);
                pidcache_put(ctx, ob, db);
            } else {
                if (flags & TP_PROXYCHLD) flags = (flags & ~TP_PROXYCHLD) | TP_PROXY;
                obj = dbptr(ctx, dv->obj);
                ob = PyDict_New();
                for(i=0; i<obj->len; i++) {
                    k = to_python(ctx, obj->item[i].key, flags);
                    v = to_python(ctx, obj->item[i].value, flags);
                    PyDict_SetItem(ob, k, v);
                    Py_DECREF(k); Py_DECREF(v);
                }
            }
            break;
        case Cache:
            // The cache is a collection
        case Collection:
        case MultiCollection:
            if (flags & TP_PROXY) {
                ob = PongoCollection_Proxy(ctx, db);
                pidcache_put(ctx, ob, db);
            } else {
                if (flags & TP_PROXYCHLD) flags = (flags & ~TP_PROXYCHLD) | TP_PROXY;
                h.flags = flags | (TP_NODEKEY|TP_NODEVAL);
                h.type = Collection;
                h.ob = ob = PyDict_New();
                bonsai_foreach(ctx, dv->obj, to_python_helper, &h);
            }
            break;

        case _BonsaiNode:
        case _BonsaiMultiNode:
            k = v = NULL;
            if (flags & TP_NODEKEY) {
                k = to_python(ctx, dv->key, flags & ~(TP_NODEKEY|TP_NODEVAL));
                ob = k;
            }
            if (flags & TP_NODEVAL) {
                if (type == _BonsaiMultiNode) {
                    v = PyTuple_New(dv->nvalue);
                    for(i=0; i<dv->nvalue; i++) {
                        ob = to_python(ctx, dv->values[i], flags & ~(TP_NODEKEY|TP_NODEVAL));
                        PyTuple_SET_ITEM(v, i, ob);
                        // Don't need to decref ob since SET_ITEM steals the reference
                    }
                } else {
                    v = to_python(ctx, dv->value, flags & ~(TP_NODEKEY|TP_NODEVAL));
                }
                ob = v;
            }
            if (k && v) {
                ob = PyTuple_Pack(2, k, v);
                Py_DECREF(k); Py_DECREF(v);
            }
            if (!k && !v) {
                ob = PongoPointer_Proxy(ctx, db);
            }
            break;
        case _InternalList:
        case _InternalObj:
                ob = PongoPointer_Proxy(ctx, db);
                break;
        default:
            PyErr_Format(PyExc_Exception, "Cannot handle dbtype %d", type);
    }
    return ob;
}
Example #18
0
/* Creates a new datetime object from a floatingtime
 * Returns a Python object if successful or NULL on error
 */
PyObject *pymsiecf_datetime_new_from_floatingtime(
           uint64_t floatingtime )
{
	byte_stream_float64_t timestamp;

	PyObject *datetime_object = NULL;
	static char *function     = "pymsiecf_datetime_new_from_floatingtime";
	uint32_t days_in_century  = 0;
	uint32_t micro_seconds    = 0;
	uint16_t days_in_year     = 0;
	uint16_t year             = 0;
	uint8_t day_of_month      = 0;
	uint8_t days_in_month     = 0;
	uint8_t hours             = 0;
	uint8_t minutes           = 0;
	uint8_t month             = 0;
	uint8_t seconds           = 0;

	timestamp.integer = floatingtime;

	/* Determine the number of years starting at '30 Dec 1899 00:00:00'
	 * correct the value to days within the year
	 */
	year = 1899;

	if( timestamp.floating_point >= 2 )
	{
		year = 1900;

		timestamp.floating_point -= 2;
	}
	while( timestamp.floating_point > 0 )
	{
		if( ( year % 400 ) == 0 )
		{
			days_in_century = 36525;
		}
		else
		{
			days_in_century = 36524;
		}
		if( timestamp.floating_point <= days_in_century )
		{
			break;
		}
		timestamp.floating_point -= days_in_century;

		year += 100;
	}
	while( timestamp.floating_point > 0 )
	{
		/* Check for a leap year
		 * The year is ( ( dividable by 4 ) and ( not dividable by 100 ) ) or ( dividable by 400 )
		 */
		if( ( ( ( year % 4 ) == 0 )
		  &&  ( ( year % 100 ) != 0 ) )
		 || ( ( year % 400 ) == 0 ) )
		{
			days_in_year = 366;
		}
		else
		{
			days_in_year = 365;
		}
		if( timestamp.floating_point <= days_in_year )
		{
			break;
		}
		timestamp.floating_point -= days_in_year;

		year += 1;
	}
	/* Determine the month correct the value to days within the month
	 */
	month = 1;

	while( timestamp.floating_point > 0 )
	{
		/* February (2)
		 */
		if( month == 2 )
		{
			if( ( ( ( year % 4 ) == 0 )
			  &&  ( ( year % 100 ) != 0 ) )
			 || ( ( year % 400 ) == 0 ) )
			{
				days_in_month = 29;
			}
			else
			{
				days_in_month = 28;
			}
		}
		/* April (4), June (6), September (9), November (11)
		 */
		else if( ( month == 4 )
		      || ( month == 6 )
		      || ( month == 9 )
		      || ( month == 11 ) )
		{
			days_in_month = 30;
		}
		/* Januari (1), March (3), May (5), July (7), August (8), October (10), December (12)
		 */
		else if( ( month == 1 )
		      || ( month == 3 )
		      || ( month == 5 )
		      || ( month == 7 )
		      || ( month == 8 )
		      || ( month == 10 )
		      || ( month == 12 ) )
		{
			days_in_month = 31;
		}
		/* This should never happen, but just in case
		 */
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unsupported month: %" PRIu8 ".",
			 function,
			 month );

			return( NULL );
		}
		if( timestamp.floating_point <= days_in_month )
		{
			break;
		}
		timestamp.floating_point -= days_in_month;

		month += 1;
	}
	/* Determine the day
	 */
	day_of_month              = (uint8_t) timestamp.floating_point;
	timestamp.floating_point -= day_of_month;

	/* There are 24 hours in a day correct the value to hours
	 */
	timestamp.floating_point *= 24;
	hours                     = (uint8_t) timestamp.floating_point;
	timestamp.floating_point -= hours;

	/* There are 60 minutes in an hour correct the value to minutes
	 */
	timestamp.floating_point *= 60;
	minutes                   = (uint8_t) timestamp.floating_point;
	timestamp.floating_point -= minutes;

	/* There are 60 seconds in a minute correct the value to seconds
	 */
	timestamp.floating_point *= 60;
	seconds                   = (uint8_t) timestamp.floating_point;
	timestamp.floating_point -= seconds;

	/* There are 1000 micro seconds in a seconds correct the value to micro seconds
	 */
	timestamp.floating_point *= 1000000;
	micro_seconds             = (uint8_t) timestamp.floating_point;
	timestamp.floating_point -= micro_seconds;

	PyDateTime_IMPORT;

	datetime_object = (PyObject *) PyDateTime_FromDateAndTime(
	                                (int) year,
	                                (int) month,
	                                (int) day_of_month,
	                                (int) hours,
	                                (int) minutes,
	                                (int) seconds,
	                                (int) micro_seconds );

	return( datetime_object );
}
Example #19
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;
}
Example #20
0
static PyObject *
ETContext_ctrl_get(ETContextObject* self, PyObject *args)
{
    DWORD ctrlcode=0,dwRet;
    BYTE  bFileId[5]={0};
    WORD  wFileId=0;
    DWORD fileIdLen=0,i;
    BYTE  outBuffer[256]={0},*pTmp;
    DWORD bytesReturned=0;
    PET_MANUFACTURE_DATE pManuDate=NULL;
    PEFINFO pFileInfo=NULL;
    PyObject *pyRet=NULL;
    if (!PyArg_ParseTuple(args, "i|H", &ctrlcode,&wFileId)) {
      return NULL;
    }

    switch(ctrlcode){
        case ET_GET_DEVICE_TYPE:
            dwRet = ETControl(&self->context,ET_GET_DEVICE_TYPE,NULL,0,outBuffer,1,&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0] as ?
            pyRet = Py_BuildValue("i",outBuffer[0]);
            break;
        case ET_GET_SERIAL_NUMBER:
            dwRet = ETControl(&self->context,ET_GET_SERIAL_NUMBER,NULL,0,outBuffer,9,&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0-7] as String
            return Py_BuildValue("z#",outBuffer,8);
            break;
        case ET_GET_DEVICE_USABLE_SPACE:
            dwRet = ETControl(&self->context,ET_GET_DEVICE_USABLE_SPACE,NULL,0,outBuffer,sizeof(DWORD),&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0-3] as DWORD
            pyRet = Py_BuildValue("i",*(DWORD*)outBuffer);
            break;
        case ET_GET_DEVICE_ATR:
            dwRet = ETControl(&self->context,ET_GET_DEVICE_ATR,NULL,0,outBuffer,17,&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0-15] as String
            pyRet = Py_BuildValue("z#",outBuffer,16);
            break;
        case ET_GET_CUSTOMER_NAME:
            dwRet = ETControl(&self->context,ET_GET_CUSTOMER_NAME,NULL,0,outBuffer,sizeof(DWORD),&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0-3] as DWORD
            pyRet = Py_BuildValue("I",*(DWORD*)outBuffer);
            break;
        case ET_GET_MANUFACTURE_DATE:
            pManuDate=(PET_MANUFACTURE_DATE)outBuffer;
            dwRet = ETControl(&self->context,ET_GET_MANUFACTURE_DATE,NULL,0,outBuffer,sizeof(ET_MANUFACTURE_DATE),&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return pManuDate as DateTime
            #if 1
            pyRet = Py_BuildValue("(iiiiii)",2000+pManuDate->byYear,
                                              pManuDate->byMonth,
                                              pManuDate->byDay,
                                              pManuDate->byHour,
                                              pManuDate->byMinute,
                                              pManuDate->bySecond);
            #else //PyDateTime_FromDateAndTime cause a segmentation fault... WHY??
            Py_XINCREF()
            pyRet = PyDateTime_FromDateAndTime(2000+pManuDate->byYear,
                                              pManuDate->byMonth,
                                              pManuDate->byDay,
                                              pManuDate->byHour,
                                              pManuDate->byMinute,
                                              pManuDate->bySecond,
                                              0);
            #endif
            break;
        case ET_GET_DF_AVAILABLE_SPACE:
            dwRet = ETControl(&self->context,ET_GET_DF_AVAILABLE_SPACE,NULL,0,outBuffer,sizeof(DWORD),&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0-1] as WORD
            pyRet = Py_BuildValue("I",*(DWORD*)outBuffer);
            break;
        case ET_GET_EF_INFO:
            pFileInfo=(PEFINFO)outBuffer;
            if(bFileId==0){
                INVALID_PARAMS("An valid File Id should provide!",NULL);
            }
            sprintf(bFileId,"%04x",wFileId);
            dwRet = ETControl(&self->context,ET_GET_EF_INFO,bFileId,4,outBuffer,sizeof(EFINFO),&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return pFileInfo as Dict
            pyRet = Py_BuildValue("{sHsbsI}",
                                    "wFileID",pFileInfo->wFileID,
                                    "bFileType",pFileInfo->bFileType,
                                    "wFileSize",pFileInfo->wFileSize);
            break;
        case ET_GET_COS_VERSION:
            dwRet = ETControl(&self->context,ET_GET_COS_VERSION,NULL,0,outBuffer,sizeof(WORD),&bytesReturned);
            DWRET_VALIDATE(dwRet,NULL);
            //Return outBuffer[0-1] as WORD
            pyRet = Py_BuildValue("H",*(WORD*)outBuffer);
            break;
        default:
            INVALID_PARAMS("param must between ET_GET_DEVICE_TYPE - ET_GET_COS_VERSION!",NULL);
            break;
    }
    Py_XINCREF(pyRet);
    return pyRet;
}
Example #21
0
static PyObject*
decode_datetime(JSONData *jsondata)
{

    PyObject *object;
    char c = 0;
    int n = 0;
    
    char *ptr = NULL,
         *tinfo_str = NULL;

    int year = 0,
        month = 0,
        day = 0,

        hour = 0,
        minute = 0,
        second = 0,
        usecond = 0;

    int is_tdelta = False,
        tinfo_len;

    // look for the closing quote
    ptr = jsondata->ptr + 2; // Skip the type hint and the opening quote

    while (True) {
        c = *ptr;
        if (c == 0) {
            PyErr_Format(JSON_DecodeError,
                "unterminated datetime string starting at position " SSIZE_T_F,
                (Py_ssize_t)(jsondata->ptr - jsondata->str));
            goto failure;
        }
        if (c == '"') {
            break;
        }
        if (ptr - jsondata->ptr - 2 == 0 ) { // first character
            switch (c) {
                case '-':
                case '+':
                    is_tdelta = True;
            }
        }

        ptr++;
    }

    // get only the actual datetime information
    skipSpaces(jsondata);
    tinfo_len = ptr - (jsondata->ptr + 2);
    if (tinfo_len) {
        tinfo_str = (char*) malloc(tinfo_len);
        strncpy(tinfo_str, jsondata->ptr + 2, tinfo_len);
    }

    if (is_tdelta) {
        n = sscanf(tinfo_str, "%d:%u:%u:%u.%u", &day, &hour, &minute, &second, &usecond);
        if (n != 3) {
            PyErr_Format(JSON_DecodeError, "bad timedelta format at position " SSIZE_T_F ": %s",
                (Py_ssize_t)(jsondata->ptr - jsondata->str),
                tinfo_str);
                goto failure;
        } else {
            second += minute * 60;
            second += hour * 60 * 60;
            object = PyDelta_FromDSU(day, second, usecond);
        }
    } else {
        char* is_datetime = strchr(tinfo_str, ' ');

        if (is_datetime == NULL) {
            switch (tinfo_len) {
                case 10:
                    n = sscanf(tinfo_str, "%u-%u-%u", &year, &month, &day);
                    object = PyDate_FromDate(year, month, day);
                    break;
                case 8:
                    n = sscanf(tinfo_str, "%u:%u:%u", &hour, &minute, &second);
                    object = PyTime_FromTime(hour, minute, second, 0);
                    break;
                case 15:
                    n = sscanf(tinfo_str, "%u:%u:%u.%u", &hour, &minute, &second, &usecond);
                    object = PyTime_FromTime(hour, minute, second, usecond);
                    break;
            }
        } else {
            switch (tinfo_len) {
                case 19:
                    n = sscanf(tinfo_str, "%u-%u-%u %u:%u:%u", &year, &month, &day, &hour, &minute, &second);
                    object = PyDateTime_FromDateAndTime(year, month, day, hour, minute, second, 0);
                    break;
                case 26:
                    n = sscanf(tinfo_str, "%u-%u-%u %u:%u:%u.%u", &year, &month, &day, &hour, &minute, &second, &usecond);
                    object = PyDateTime_FromDateAndTime(year, month, day, hour, minute, second, usecond);
                    break;
            }
        }
    }

    if (object == NULL) {
        PyErr_Format(JSON_DecodeError, "bad format for time, date, or datetime at position " SSIZE_T_F ": %s",
            (Py_ssize_t)(jsondata->ptr - jsondata->str),
            tinfo_str);
        goto failure;
    }

    jsondata->ptr = jsondata->ptr + tinfo_len + 3;

    return object;

failure:
    free(tinfo_str);
    Py_XDECREF(object);
    return NULL;

}