Esempio n. 1
0
def show_tables(etcd_client, tree, db):
    """
    Execute SHOW [FULL] TABLES query#

    :param etcd_client: etcd client
    :type etcd_client: pyetcd.client.Client
    :param db: Current database
    :type db: str
    :param tree: Parse tree
    :type tree: SQLTree
    :return: ResultSet instance
    :rtype: ResultSet
    """
    columns = ColumnSet().add(Column('Tables_in_%s' % db))
    if tree.options['full']:
        columns.add(Column('Table_type'))

    result_set = ResultSet(columns)

    try:
        etcd_response = etcd_client.read('/%s' % db)
    except EtcdKeyNotFound:
        raise OperationalError('No database selected')

    try:
        for node in etcd_response.node['nodes']:
            table_name = node['key'].replace('/%s/' % db, '', 1)
            row = (table_name, )
            if tree.options['full']:
                row += ('BASE TABLE', )
            result_set.add_row(Row(row))
    except KeyError:
        pass

    return result_set
def test_eval_identifier():
    cs = ColumnSet()
    cs.add(Column('id'))
    cs.add(Column('name'))

    row = Row((5, 'aaa'))

    assert eval_identifier((cs, row), 'id')[1] == 5
    assert eval_identifier((cs, row), 'name')[1] == 'aaa'
Esempio n. 3
0
def test_insert_duplicate_raises(mock_get_pk_field):
    mock_get_pk_field.return_value = Column('id')

    etcd_client = mock.Mock()
    # etcd_client.read.side_effect =
    tree = SQLTree()

    # {"query_type": "INSERT",
    # "db": null,
    # "query":
    # "insert into bar(id, name) values(1, 'aaa')",
    # "table": "bar",
    # "expressions": [],
    # "success": true,
    # "fields": {"id": "1", "name": "aaa"},
    # "order": {"direction": "ASC", "by": null},
    # "limit": null,
    # "where": null,
    # "options": {}}
    tree.table = 'bar'
    tree.fields = {"id": "1", "name": "aaa"}

    with pytest.raises(IntegrityError):
        # noinspection PyTypeChecker
        insert(etcd_client, tree, 'foo')
Esempio n. 4
0
def eval_identifier(row, identifier):
    """
    Get value of identifier for a given row

    :param row: row
    :type row: tuple(ColumnSet, Row)
    :param identifier: Identifier
    :type identifier: str
    :return: value of identifier
    """
    try:
        identifier_strip = identifier.split('.')[1]
    except IndexError:
        identifier_strip = identifier

    # If row isn't given return column name only
    if row:
        columns = row[0]
        data = row[1]
    else:
        return identifier_strip, None

    try:
        pos = columns.index(Column(identifier_strip))
        return identifier_strip, data[pos]
    except ValueError:
        raise OperationalError('Unknown identifier %s', identifier_strip)
Esempio n. 5
0
def test_show_tables(content, rows):

    response = mock.Mock()
    response.content = content
    etcd_response = EtcdResult(response)

    etcd_client = mock.Mock()
    etcd_client.read.return_value = etcd_response

    cols = ColumnSet()
    cols.add(Column('Tables_in_foo'))

    # print(cols)

    rs = ResultSet(cols, rows)
    tree = SQLTree()
    tree.db = 'foo'
    tree.options['full'] = False
    # noinspection PyTypeChecker
    result = show_tables(etcd_client, tree, tree.db)

    print("Expected: \n%s" % rs)
    print("Actual: \n%s" % result)
    # noinspection PyTypeChecker
    assert result == rs
Esempio n. 6
0
def test_fetch_many(rows, n, result, etcdb_connection):
    cursor = etcdb_connection.cursor()
    rs = ResultSet(ColumnSet().add(Column('Tables')),
                   rows
                   )
    cursor._result_set = rs

    assert cursor.fetchmany(n) == result
Esempio n. 7
0
def test_fetch_all(rows, result, etcdb_connection):
    cursor = etcdb_connection.cursor()
    rs = ResultSet(ColumnSet().add(Column('Tables')),
                   rows
                   )
    cursor._result_set = rs

    # for i in xrange(len(result)):
    assert cursor.fetchall() == result
    assert cursor.fetchall() == ()
Esempio n. 8
0
def test_cursor_fetchone(etcdb_connection):
    cursor = etcdb_connection.cursor()

    columns = ColumnSet().add(Column('VERSION()'))
    rs = ResultSet(columns)
    rs.add_row(Row(('2.3.7', )))
    cursor._result_set = rs

    row = cursor.fetchone()
    assert isinstance(row, tuple)
    assert row == ('2.3.7', )
Esempio n. 9
0
def test_insert(mock_get_pk_field):
    mock_get_pk_field.return_value = Column('id')

    etcd_client = mock.Mock()
    etcd_client.read.side_effect = EtcdKeyNotFound
    tree = SQLTree()
    tree.table = 'bar'
    tree.fields = {"id": "1", "name": "aaa"}
    # noinspection PyTypeChecker
    insert(etcd_client, tree, 'foo')
    etcd_client.write.assert_called_once_with('/foo/bar/1',
                                              json.dumps(tree.fields))
Esempio n. 10
0
def show_databases(etcd_client):
    """
    Execute SHOW [FULL] TABLES query

    :param etcd_client: etcd client
    :type etcd_client: pyetcd.client.Client
    :return: ResultSet instance
    :rtype: ResultSet
    """
    etcd_response = etcd_client.read('/')
    columns = ColumnSet().add(Column('Database'))
    result_set = ResultSet(columns)
    try:
        for node in etcd_response.node['nodes']:
            val = node['key'].lstrip('/')
            result_set.add_row(Row((val, )))

    except KeyError:
        pass
    return result_set
Esempio n. 11
0
def prepare_columns(tree):
    """
    Generate ColumnSet for query result. ColumnsSet doesn't include
    a grouping function.

    :return: Columns of the query result.
    :rtype: ColumnSet
    """
    columns = ColumnSet()
    for select_item in tree.expressions:

        expr, alias = select_item

        colname, _ = eval_expr(None, tree=expr)
        if alias:
            colname = alias

        columns.add(Column(colname))

    return columns
Esempio n. 12
0
def test_show_databases(content, rows):

    response = mock.Mock()
    response.content = content
    etcd_response = EtcdResult(response)

    etcd_client = mock.Mock()
    etcd_client.read.return_value = etcd_response

    cols = ColumnSet()
    cols.add(Column('Database'))

    # print(cols)

    rs = ResultSet(cols, rows)
    # noinspection PyTypeChecker
    result = show_databases(etcd_client)

    print("Expected: \n%s" % rs)
    print("Actual: \n%s" % result)
    # noinspection PyTypeChecker
    assert result == rs
Esempio n. 13
0
def test_get_pk_field():
    mock_response = mock.Mock()
    content = {
        "action": "get",
        "node": {
            "key":
            "/foo/bar/_fields",
            "value":
            '{"id": {"type": "INT", '
            '"options": {"primary": true, "nullable": false}}, '
            '"name": {"type": "VARCHAR", '
            '"options": {"nullable": true}}}',
            "modifiedIndex":
            2218,
            "createdIndex":
            2218
        }
    }
    mock_response.content = json.dumps(content)
    etcd_response = EtcdResult(mock_response)

    etcd_client = mock.Mock()
    etcd_client.read.return_value = etcd_response
    assert get_pk_field(etcd_client, 'foo', 'bar') == Column('id')
Esempio n. 14
0
              ),
             None),
         (
             ('bool_primary',
              ('predicate',
               ('bit_expr',
                ('simple_expr',
                 ('IDENTIFIER', 'name')
                 )
                )
               )
              ),
             None
         )
     ],
     ColumnSet().add(Column('id')).add(Column('name'))
 ),
 (
     [
         (
             ('bool_primary',
              ('predicate',
               ('bit_expr',
                ('simple_expr',
                 ('IDENTIFIER', 'id')
                 )
                )
               )
              ),
             None),
         (
Esempio n. 15
0
def desc_table(etcd_client, tree, db):
    """
    Execute DESC table query#

    :param etcd_client: etcd client
    :type etcd_client: pyetcd.client.Client
    :param tree: Parse tree
    :type tree: SQLTree
    :param db: Current database
    :type db: str
    :return: ResultSet instance
    :rtype: ResultSet
    """
    key = '/{db}/{table}/_fields'.format(db=db, table=tree.table)
    try:
        etcd_result = etcd_client.read(key)
    except EtcdKeyNotFound:
        raise ProgrammingError('Table `{db}`.`{table}` '
                               'doesn\'t exist'.format(db=db,
                                                       table=tree.table))
    columns = ColumnSet()
    columns.add(Column('Field'))
    columns.add(Column('Type'))
    columns.add(Column('Null'))
    columns.add(Column('Key'))
    columns.add(Column('Default'))
    columns.add(Column('Extra'))

    result_set = ResultSet(columns)

    fields = json.loads(etcd_result.node['value'])

    for key, value in fields.iteritems():
        field_type = value['type']

        if value['options']['nullable']:
            nullable = 'YES'
        else:
            nullable = 'NO'

        indexes = ''
        if 'primary' in value['options'] and value['options']['primary']:
            indexes = 'PRI'

        if 'unique' in value['options'] and value['options']['unique']:
            indexes = 'UNI'

        try:
            default_value = value['options']['default']
        except KeyError:
            default_value = ''

        extra = ''
        if 'auto_increment' in value['options'] \
                and value['options']['auto_increment']:
            extra = 'auto_increment'

        result_set.add_row(
            Row((key, field_type, nullable, indexes, default_value, extra)))

    return result_set
Esempio n. 16
0
def test_n_rows(cursor):
    rs = ResultSet(ColumnSet().add(Column('foo')))
    cursor._result_set = rs
    assert cursor.n_rows == 0
Esempio n. 17
0
def test_etcdb_count(rows, count):
    cs = ColumnSet().add(Column('id'))
    rs = ResultSet(cs, rows)
    assert etcdb_count(rs) == count