cursor.py 7.0 KB
Newer Older
S
slguan 已提交
1 2
from .cinterface import CTaosInterface
from .error import *
3 4
from .constants import FieldType

S
slguan 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

class TDengineCursor(object):
    """Database cursor which is used to manage the context of a fetch operation.

    Attributes:
        .description: Read-only attribute consists of 7-item sequences:

            > name (mondatory)
            > type_code (mondatory)
            > display_size
            > internal_size
            > precision
            > scale
            > null_ok

            This attribute will be None for operations that do not return rows or
            if the cursor has not had an operation invoked via the .execute*() method yet.

        .rowcount:This read-only attribute specifies the number of rows that the last
24
            .execute*() produced (for DQL statements like SELECT) or affected
S
slguan 已提交
25 26 27 28 29 30 31 32 33 34 35
    """

    def __init__(self, connection=None):
        self._description = None
        self._rowcount = -1
        self._connection = None
        self._result = None
        self._fields = None
        self._block = None
        self._block_rows = -1
        self._block_iter = 0
36
        self._affected_rows = 0
S
slguan 已提交
37 38 39 40 41 42 43 44 45 46 47 48

        if connection is not None:
            self._connection = connection

    def __iter__(self):
        return self

    def next(self):
        if self._result is None or self._fields is None:
            raise OperationalError("Invalid use of fetch iterator")

        if self._block_rows <= self._block_iter:
49 50
            block, self._block_rows = CTaosInterface.fetchBlock(
                self._result, self._fields)
S
slguan 已提交
51 52 53 54 55
            if self._block_rows == 0:
                raise StopIteration
            self._block = list(map(tuple, zip(*block)))
            self._block_iter = 0

56
        data = self._block[self._block_iter]
S
slguan 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        self._block_iter += 1

        return data

    @property
    def description(self):
        """Return the description of the object.
        """
        return self._description

    @property
    def rowcount(self):
        """Return the rowcount of the object
        """
        return self._rowcount

73 74 75 76 77 78
    @property
    def affected_rows(self):
        """Return the affected_rows of the object
        """
        return self._affected_rows

S
slguan 已提交
79 80 81 82 83 84 85 86 87 88 89 90
    def callproc(self, procname, *args):
        """Call a stored database procedure with the given name.

        Void functionality since no stored procedures.
        """
        pass

    def close(self):
        """Close the cursor.
        """
        if self._connection is None:
            return False
91

S
slguan 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        self._connection.clear_result_set()
        self._reset_result()
        self._connection = None

        return True

    def execute(self, operation, params=None):
        """Prepare and execute a database operation (query or command).
        """
        if not operation:
            return None

        if not self._connection:
            # TODO : change the exception raised here
            raise ProgrammingError("Cursor is not connected")
107

S
slguan 已提交
108 109 110 111 112 113
        self._connection.clear_result_set()
        self._reset_result()

        stmt = operation
        if params is not None:
            pass
114

S
slguan 已提交
115 116 117
        res = CTaosInterface.query(self._connection._conn, stmt)
        if res == 0:
            if CTaosInterface.fieldsCount(self._connection._conn) == 0:
118 119
                self._affected_rows += CTaosInterface.affectedRows(
                    self._connection._conn)
S
slguan 已提交
120 121
                return CTaosInterface.affectedRows(self._connection._conn)
            else:
122 123
                self._result, self._fields = CTaosInterface.useResult(
                    self._connection._conn)
S
slguan 已提交
124 125
                return self._handle_result()
        else:
126 127 128
            raise ProgrammingError(
                CTaosInterface.errStr(
                    self._connection._conn))
S
slguan 已提交
129 130 131 132 133 134 135 136 137 138 139

    def executemany(self, operation, seq_of_parameters):
        """Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
        """
        pass

    def fetchone(self):
        """Fetch the next row of a query result set, returning a single sequence, or None when no more data is available.
        """
        pass

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    def istype(self, col, dataType):
        if (dataType.upper() == "BOOL"):
            if (self._description[col][1] == FieldType.C_BOOL):
                return True
        if (dataType.upper() == "TINYINT"):
            if (self._description[col][1] == FieldType.C_TINYINT):
                return True
        if (dataType.upper() == "INT"):
            if (self._description[col][1] == FieldType.C_INT):
                return True
        if (dataType.upper() == "BIGINT"):
            if (self._description[col][1] == FieldType.C_INT):
                return True
        if (dataType.upper() == "FLOAT"):
            if (self._description[col][1] == FieldType.C_FLOAT):
                return True
        if (dataType.upper() == "DOUBLE"):
            if (self._description[col][1] == FieldType.C_DOUBLE):
                return True
        if (dataType.upper() == "BINARY"):
            if (self._description[col][1] == FieldType.C_BINARY):
                return True
        if (dataType.upper() == "TIMESTAMP"):
            if (self._description[col][1] == FieldType.C_TIMESTAMP):
                return True
        if (dataType.upper() == "NCHAR"):
            if (self._description[col][1] == FieldType.C_NCHAR):
                return True

        return False

S
slguan 已提交
171 172 173 174 175 176 177 178
    def fetchmany(self):
        pass

    def fetchall(self):
        """Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation.
        """
        if self._result is None or self._fields is None:
            raise OperationalError("Invalid use of fetchall")
179

S
slguan 已提交
180 181 182
        buffer = [[] for i in range(len(self._fields))]
        self._rowcount = 0
        while True:
183 184 185 186
            block, num_of_fields = CTaosInterface.fetchBlock(
                self._result, self._fields)
            if num_of_fields == 0:
                break
S
slguan 已提交
187 188 189 190 191 192
            self._rowcount += num_of_fields
            for i in range(len(self._fields)):
                buffer[i].extend(block[i])

        self._connection.clear_result_set()

193
        return list(map(tuple, zip(*buffer)))
S
slguan 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

    def nextset(self):
        """
        """
        pass

    def setinputsize(self, sizes):
        pass

    def setutputsize(self, size, column=None):
        pass

    def _reset_result(self):
        """Reset the result to unused version.
        """
        self._description = None
        self._rowcount = -1
        self._result = None
        self._fields = None
        self._block = None
        self._block_rows = -1
        self._block_iter = 0
216
        self._affected_rows = 0
217

S
slguan 已提交
218 219 220 221 222
    def _handle_result(self):
        """Handle the return result from query.
        """
        self._description = []
        for ele in self._fields:
223 224 225
            self._description.append(
                (ele['name'], ele['type'], None, None, None, None, False))

226
        return self._result