Python cx_Oracle.TIMESTAMP Examples

The following are 7 code examples of cx_Oracle.TIMESTAMP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cx_Oracle , or try the search function .
Example #1
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def __init__(self, param, cursor, strings_only=False):
        # With raw SQL queries, datetimes can reach this function
        # without being converted by DateTimeField.get_db_prep_value.
        if settings.USE_TZ and (isinstance(param, datetime.datetime) and
                                not isinstance(param, Oracle_datetime)):
            param = Oracle_datetime.from_datetime(param)

        string_size = 0
        # Oracle doesn't recognize True and False correctly.
        if param is True:
            param = 1
        elif param is False:
            param = 0
        if hasattr(param, 'bind_parameter'):
            self.force_bytes = param.bind_parameter(cursor)
        elif isinstance(param, (Database.Binary, datetime.timedelta)):
            self.force_bytes = param
        else:
            # To transmit to the database, we need Unicode if supported
            # To get size right, we must consider bytes.
            self.force_bytes = force_text(param, cursor.charset, strings_only)
            if isinstance(self.force_bytes, str):
                # We could optimize by only converting up to 4000 bytes here
                string_size = len(force_bytes(param, cursor.charset, strings_only))
        if hasattr(param, 'input_size'):
            # If parameter has `input_size` attribute, use that.
            self.input_size = param.input_size
        elif string_size > 4000:
            # Mark any string param greater than 4000 characters as a CLOB.
            self.input_size = Database.CLOB
        elif isinstance(param, datetime.datetime):
            self.input_size = Database.TIMESTAMP
        else:
            self.input_size = None 
Example #2
Source File: syntax.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def preQuery(self, cursor):
        typeMap = {"integer": cx_Oracle.NUMBER,
                   "text": cx_Oracle.NCLOB,
                   "varchar": cx_Oracle.STRING,
                   "timestamp": cx_Oracle.TIMESTAMP}
        self.var = cursor.var(typeMap[self.typeID])
        return self.var 
Example #3
Source File: dbapiclient.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def mapArgs(self, args):
        realArgs = []
        for arg in args:
            if isinstance(arg, str):
                # We use NCLOB everywhere, so cx_Oracle requires a unicode-type
                # input.  But we mostly pass around utf-8 encoded bytes at the
                # application layer as they consume less memory, so do the
                # conversion here.
                arg = arg.decode('utf-8')

            if isinstance(arg, unicode) and len(arg) > 1024:
                # This *may* cause a type mismatch, but none of the non-CLOB
                # strings that we're passing would allow a value this large
                # anyway.  Smaller strings will be automatically converted by
                # the bindings; larger ones will generate an error.  I'm not
                # sure why cx_Oracle itself doesn't just do the following hack
                # automatically and internally for larger values too, but, here
                # it is:
                v = self.var(cx_Oracle.NCLOB, len(arg) + 1)
                v.setvalue(0, arg)

            elif isinstance(arg, datetime.datetime):
                # By default when cx_Oracle is passed a datetime object it maps it to a
                # cx_Oracle.DATETIME variable which does not serialize fraction seconds
                # into the query, or call, arguments. However, for high volume systems,
                # we really want sub-second resolution for things like the job queue,
                # so we want to serialize datetime as cx_Oracle.TIMESTAMP.
                v = self.var(cx_Oracle.TIMESTAMP)
                v.setvalue(0, arg)

            else:
                v = arg

            realArgs.append(v)

        return realArgs 
Example #4
Source File: base.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def convert_values(self, value, field):
        if isinstance(value, Database.LOB):
            value = value.read()
            if field and field.get_internal_type() == 'TextField':
                value = force_text(value)

        # Oracle stores empty strings as null. We need to undo this in
        # order to adhere to the Django convention of using the empty
        # string instead of null, but only if the field accepts the
        # empty string.
        if value is None and field and field.empty_strings_allowed:
            value = ''
        # Convert 1 or 0 to True or False
        elif value in (1, 0) and field and field.get_internal_type() in ('BooleanField', 'NullBooleanField'):
            value = bool(value)
        # Force floats to the correct type
        elif value is not None and field and field.get_internal_type() == 'FloatField':
            value = float(value)
        # Convert floats to decimals
        elif value is not None and field and field.get_internal_type() == 'DecimalField':
            value = util.typecast_decimal(field.format_number(value))
        # cx_Oracle always returns datetime.datetime objects for
        # DATE and TIMESTAMP columns, but Django wants to see a
        # python datetime.date, .time, or .datetime.  We use the type
        # of the Field to determine which to cast to, but it's not
        # always available.
        # As a workaround, we cast to date if all the time-related
        # values are 0, or to time if the date is 1/1/1900.
        # This could be cleaned a bit by adding a method to the Field
        # classes to normalize values from the database (the to_python
        # method is used for validation and isn't what we want here).
        elif isinstance(value, Database.Timestamp):
            if field and field.get_internal_type() == 'DateTimeField':
                pass
            elif field and field.get_internal_type() == 'DateField':
                value = value.date()
            elif field and field.get_internal_type() == 'TimeField' or (value.year == 1900 and value.month == value.day == 1):
                value = value.time()
            elif value.hour == value.minute == value.second == value.microsecond == 0:
                value = value.date()
        return value 
Example #5
Source File: base.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def _rowfactory(row, cursor):
    # Cast numeric values as the appropriate Python type based upon the
    # cursor description, and convert strings to unicode.
    casted = []
    for value, desc in zip(row, cursor.description):
        if value is not None and desc[1] is Database.NUMBER:
            precision, scale = desc[4:6]
            if scale == -127:
                if precision == 0:
                    # NUMBER column: decimal-precision floating point
                    # This will normally be an integer from a sequence,
                    # but it could be a decimal value.
                    if '.' in value:
                        value = decimal.Decimal(value)
                    else:
                        value = int(value)
                else:
                    # FLOAT column: binary-precision floating point.
                    # This comes from FloatField columns.
                    value = float(value)
            elif precision > 0:
                # NUMBER(p,s) column: decimal-precision fixed point.
                # This comes from IntField and DecimalField columns.
                if scale == 0:
                    value = int(value)
                else:
                    value = decimal.Decimal(value)
            elif '.' in value:
                # No type information. This normally comes from a
                # mathematical expression in the SELECT list. Guess int
                # or Decimal based on whether it has a decimal point.
                value = decimal.Decimal(value)
            else:
                value = int(value)
        # datetimes are returned as TIMESTAMP, except the results
        # of "dates" queries, which are returned as DATETIME.
        elif desc[1] in (Database.TIMESTAMP, Database.DATETIME):
            # Confirm that dt is naive before overwriting its tzinfo.
            if settings.USE_TZ and value is not None and timezone.is_naive(value):
                value = value.replace(tzinfo=timezone.utc)
        elif desc[1] in (Database.STRING, Database.FIXED_CHAR,
                         Database.LONG_STRING):
            value = to_unicode(value)
        casted.append(value)
    return tuple(casted) 
Example #6
Source File: base.py    From luscan-devel with GNU General Public License v2.0 4 votes vote down vote up
def _rowfactory(row, cursor):
    # Cast numeric values as the appropriate Python type based upon the
    # cursor description, and convert strings to unicode.
    casted = []
    for value, desc in zip(row, cursor.description):
        if value is not None and desc[1] is Database.NUMBER:
            precision, scale = desc[4:6]
            if scale == -127:
                if precision == 0:
                    # NUMBER column: decimal-precision floating point
                    # This will normally be an integer from a sequence,
                    # but it could be a decimal value.
                    if '.' in value:
                        value = decimal.Decimal(value)
                    else:
                        value = int(value)
                else:
                    # FLOAT column: binary-precision floating point.
                    # This comes from FloatField columns.
                    value = float(value)
            elif precision > 0:
                # NUMBER(p,s) column: decimal-precision fixed point.
                # This comes from IntField and DecimalField columns.
                if scale == 0:
                    value = int(value)
                else:
                    value = decimal.Decimal(value)
            elif '.' in value:
                # No type information. This normally comes from a
                # mathematical expression in the SELECT list. Guess int
                # or Decimal based on whether it has a decimal point.
                value = decimal.Decimal(value)
            else:
                value = int(value)
        # datetimes are returned as TIMESTAMP, except the results
        # of "dates" queries, which are returned as DATETIME.
        elif desc[1] in (Database.TIMESTAMP, Database.DATETIME):
            # Confirm that dt is naive before overwriting its tzinfo.
            if settings.USE_TZ and value is not None and timezone.is_naive(value):
                value = value.replace(tzinfo=timezone.utc)
        elif desc[1] in (Database.STRING, Database.FIXED_CHAR,
                         Database.LONG_STRING):
            value = to_unicode(value)
        casted.append(value)
    return tuple(casted) 
Example #7
Source File: cx_oracle.py    From android_universal with MIT License 4 votes vote down vote up
def __init__(self,
                 auto_convert_lobs=True,
                 threaded=True,
                 coerce_to_unicode=False,
                 coerce_to_decimal=True,
                 arraysize=50,
                 **kwargs):

        self._pop_deprecated_kwargs(kwargs)

        OracleDialect.__init__(self, **kwargs)
        self.threaded = threaded
        self.arraysize = arraysize
        self.auto_convert_lobs = auto_convert_lobs
        self.coerce_to_unicode = coerce_to_unicode
        self.coerce_to_decimal = coerce_to_decimal

        cx_Oracle = self.dbapi

        if cx_Oracle is None:
            self._include_setinputsizes = {}
            self.cx_oracle_ver = (0, 0, 0)
        else:
            self.cx_oracle_ver = self._parse_cx_oracle_ver(cx_Oracle.version)
            if self.cx_oracle_ver < (5, 2) and self.cx_oracle_ver > (0, 0, 0):
                raise exc.InvalidRequestError(
                    "cx_Oracle version 5.2 and above are supported")

            self._has_native_int = hasattr(cx_Oracle, "NATIVE_INT")

            self._include_setinputsizes = {
                cx_Oracle.NCLOB, cx_Oracle.CLOB, cx_Oracle.LOB,
                cx_Oracle.NCHAR, cx_Oracle.FIXED_NCHAR,
                cx_Oracle.BLOB, cx_Oracle.FIXED_CHAR, cx_Oracle.TIMESTAMP,
                _OracleInteger, _OracleBINARY_FLOAT, _OracleBINARY_DOUBLE
            }

            self._paramval = lambda value: value.getvalue()

            # https://github.com/oracle/python-cx_Oracle/issues/176#issuecomment-386821291
            # https://github.com/oracle/python-cx_Oracle/issues/224
            self._values_are_lists = self.cx_oracle_ver >= (6, 3)
            if self._values_are_lists:
                cx_Oracle.__future__.dml_ret_array_val = True

                def _returningval(value):
                    try:
                        return value.values[0][0]
                    except IndexError:
                        return None

                self._returningval = _returningval
            else:
                self._returningval = self._paramval

        self._is_cx_oracle_6 = self.cx_oracle_ver >= (6, )