Пример #1
0
static PyObject* MakeConnectionString(PyObject* existing, PyObject* parts)
{
    // Creates a connection string from an optional existing connection string plus a dictionary of keyword value
    // pairs.
    //
    // existing
    //   Optional Unicode connection string we will be appending to.  Used when a partial connection string is passed
    //   in, followed by keyword parameters:
    //
    //   connect("driver={x};database={y}", user='******')
    //
    // parts
    //   A dictionary of text keywords and text values that will be appended.

    I(PyUnicode_Check(existing));

    Py_ssize_t length = 0;      // length in *characters*
    if (existing)
        length = Text_Size(existing) + 1; // + 1 to add a trailing semicolon

    Py_ssize_t pos = 0;
    PyObject* key = 0;
    PyObject* value = 0;

    while (PyDict_Next(parts, &pos, &key, &value))
    {
        length += Text_Size(key) + 1 + Text_Size(value) + 1; // key=value;
    }

    PyObject* result = PyUnicode_FromUnicode(0, length);
    if (!result)
        return 0;

    Py_UNICODE* buffer = PyUnicode_AS_UNICODE(result);
    Py_ssize_t offset = 0;

    if (existing)
    {
        offset += TextCopyToUnicode(&buffer[offset], existing);
        buffer[offset++] = (Py_UNICODE)';';
    }

    pos = 0;
    while (PyDict_Next(parts, &pos, &key, &value))
    {
        offset += TextCopyToUnicode(&buffer[offset], key);
        buffer[offset++] = (Py_UNICODE)'=';

        offset += TextCopyToUnicode(&buffer[offset], value);
        buffer[offset++] = (Py_UNICODE)';';
    }

    I(offset == length);

    return result;
}
Пример #2
0
static PyObject* Row_repr(PyObject* o)
{
    Row* self = (Row*)o;

    if (self->cValues == 0)
        return PyString_FromString("()");

    Object pieces(PyTuple_New(self->cValues));
    if (!pieces)
        return 0;

    Py_ssize_t length = 2 + (2 * (self->cValues-1)); // parens + ', ' separators

    for (Py_ssize_t i = 0; i < self->cValues; i++)
    {
        PyObject* piece = PyObject_Repr(self->apValues[i]);
        if (!piece)
            return 0;

        length += Text_Size(piece);

        PyTuple_SET_ITEM(pieces.Get(), i, piece);
    }

    if (self->cValues == 1)
    {
        // Need a trailing comma: (value,)
        length += 2;
    }

    PyObject* result = Text_New(length);
    if (!result)
        return 0;
    TEXT_T* buffer = Text_Buffer(result);
    Py_ssize_t offset = 0;
    buffer[offset++] = '(';
    for (Py_ssize_t i = 0; i < self->cValues; i++)
    {
        PyObject* item = PyTuple_GET_ITEM(pieces.Get(), i);
        memcpy(&buffer[offset], Text_Buffer(item), Text_Size(item) * sizeof(TEXT_T));
        offset += Text_Size(item);

        if (i != self->cValues-1 || self->cValues == 1)
        {
            buffer[offset++] = ',';
            buffer[offset++] = ' ';
        }
    }
    buffer[offset++] = ')';

    I(offset == length);

    return result;
}