Ejemplo n.º 1
0
    def test_link(self):
        """
        Link to any node
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            result = db.execute(text(fetch_query_string('select_link_node_from_node.sql')), node_id=a_id)
            result = [x['node_id'] for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = db.execute(text(fetch_query_string('select_link_node_from_node.sql')), node_id=b_id)
            result = [x['node_id'] for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result
Ejemplo n.º 2
0
    def test_delete_one_node(self):
        """
        Delete a node
        """
        with self.app.app_context():
            init_db()
            result = db.execute(text(fetch_query_string('insert_node.sql')),
                                name='a',
                                value='apple')
            a = result.lastrowid

            result = db.execute(text(
                fetch_query_string('select_node_from_id.sql')),
                                node_id=a).fetchall()
            assert len(result) == 1
            r = result[0]
            assert a == r['node_id']
            assert 'a' == r['name']
            assert 'apple' == r['value']

            # now delete
            delete_node(node_id=a)

            result = db.execute(text(
                fetch_query_string('select_node_from_id.sql')),
                                node_id=a).fetchall()
            assert len(result) == 0
Ejemplo n.º 3
0
    def test_delete_one_node(self):
        """
        Delete a node
        """
        with self.app.app_context():
            init_db()
            c = db.cursor()
            c.execute(fetch_query_string('insert_node.sql'), {'name': 'a', 'value':'apple'})
            a = c.lastrowid
            db.commit()

            result = c.execute(fetch_query_string('select_node_from_id.sql'), {'node_id': a}).fetchall()
            (result, col_names) = rowify(result, c.description)
            assert len(result) == 1
            r = result.pop()
            assert a == r.get('node_id')
            assert 'a' == r.get('name')
            assert 'apple' == r.get('value')

            # now delete
            c = db.cursor()
            delete_node(node_id=a)

            result = c.execute(fetch_query_string('select_node_from_id.sql'), {'node_id': a}).fetchall()
            (result, col_names) = rowify(result, c.description)
            assert len(result) == 0
Ejemplo n.º 4
0
    def test_link(self):
        """
        Link to any node
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            result = db.query(
                fetch_query_string('select_link_node_from_node.sql'),
                fetchall=True,
                **{'node_id': a_id})
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = db.query(
                fetch_query_string('select_link_node_from_node.sql'),
                fetchall=True,
                **{'node_id': b_id})
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result
Ejemplo n.º 5
0
    def test_link(self):
        """
        Link to any node
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            c = db.cursor()
            result = c.execute(fetch_query_string('select_link_node_from_node.sql'), {'node_id': a_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = c.execute(fetch_query_string('select_link_node_from_node.sql'), {'node_id': b_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result
Ejemplo n.º 6
0
    def test_delete_one_node(self):
        """
        Delete a node
        """
        with self.app.app_context():
            init_db()
            trans = db.transaction()
            result = db.db.execute(fetch_query_string('insert_node.sql'), {
                'name': 'a',
                'value': 'apple'
            })
            a = result.lastrowid
            trans.commit()

            result = db.query(fetch_query_string('select_node_from_id.sql'),
                              fetchall=True,
                              **{'node_id': a})
            assert len(result) == 1
            r = result.first()
            assert a == r.get('node_id')
            assert 'a' == r.get('name')
            assert 'apple' == r.get('value')

            # now delete
            delete_node(node_id=a)

            result = db.query(fetch_query_string('select_node_from_id.sql'),
                              fetchall=True,
                              **{'node_id': a})
            assert len(result) == 0
Ejemplo n.º 7
0
def existing_node_input():
    """
    Get an existing node id by name or id.

    Return -1 if invalid
    """
    input_from_user = raw_input("Existing node name or id: ")
    node_id = INVALID_NODE

    if not input_from_user:
        return node_id

    # int or str?
    try:
        parsed_input = int(input_from_user)
    except ValueError:
        parsed_input = input_from_user

    if isinstance(parsed_input, int):
        result = db.execute(text(fetch_query_string('select_node_from_id.sql')),
                node_id=parsed_input).fetchall()
        if result:
            node_id = int(result[0]['node_id'])
    else:
        result = db.execute(text(fetch_query_string('select_node_from_name.sql')),
                node_name=parsed_input).fetchall()
        if result:
            if len(result) == 1:
                print 'Node id: {node_id}\nNode name: {name}'.format(**result[0])
                print '-------------'
                node_id = result[0]['node_id']
            else:
                print 'Multiple nodes found with the name: {0}'.format(parsed_input)
                for item in result:
                    print '{node_id}: {name} = {value}'.format(**item)
                node_selection = raw_input('Enter a node id from this list or enter "?" to render all or "?<node>" for a specific one.')
                if node_selection:
                    node_selection_match = re.match(r"\?(\d)*", node_selection)
                    if node_selection_match:
                        if node_selection_match.groups()[0]:
                            value = render_node(int(node_selection_match.groups()[0]), noderequest={'_no_template':True}, **result[0])
                            print safe_dump(value, default_flow_style=False)
                        else:
                            for item in result:
                                value = render_node(item['node_id'], noderequest={'_no_template':True}, **item)
                                print 'Node id: {0}'.format(item['node_id'])
                                print safe_dump(value, default_flow_style=False)
                                print '---'
                        node_id = node_input()
                    else:
                        try:
                            node_id = int(node_selection)
                        except ValueError:
                            node_id = INVALID_NODE
                            print 'invalid node id: %s' % node

    return node_id
Ejemplo n.º 8
0
    def test_template(self):
        with self.app.app_context():
            init_db()

            a = insert_node(name='a', value=None)
            add_template_for_node('template_a.html', a)
            aa = insert_node(name='aa', value=None)
            add_template_for_node('template_a.html', aa)
            b = insert_node(name='b', value=None)
            add_template_for_node('template_b.html', b)
            c = insert_node(name='c', value=None)
            add_template_for_node('template_c.html', c)

            result = db.query(
                fetch_query_string('select_template_from_node.sql'),
                fetchall=True,
                **{'node_id': a})
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'

            # another node that uses the same template
            result = db.query(
                fetch_query_string('select_template_from_node.sql'),
                fetchall=True,
                **{'node_id': aa})
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'

            # can overwrite what node is tied to what template
            add_template_for_node('template_over_a.html', a)

            result = db.query(
                fetch_query_string('select_template_from_node.sql'),
                fetchall=True,
                **{'node_id': a})
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_over_a.html'

            # this one still uses the other template
            result = db.query(
                fetch_query_string('select_template_from_node.sql'),
                fetchall=True,
                **{'node_id': aa})
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'
Ejemplo n.º 9
0
    def uri_index():
        def cleanup_url(url):
            url = url.strip()
            if url.startswith('/'):
                if url.endswith('/index.html'):
                    return url
                elif url.endswith('/'):
                    url = url.strip('/')
                    if len(url) == 0:
                        return ('public.index', {})
                    return ('public.uri_index', {'uri': url})

        try:
            result = db.execute(text(fetch_query_string('select_paths_to_freeze.sql'))).fetchall()
        except (DatabaseError, StatementError) as err:
            app.logger.error("DatabaseError: %s", err)
            return []
        urls = filter(None, map(lambda x:cleanup_url(x[0]), result))

        urls_file = app.config.get('URLS_FILE', None)
        if urls_file:
            urls_file = urls_file if urls_file[0] == os.sep else os.path.join(os.getcwd(), urls_file)
            f = open(urls_file, 'r')
            urls.extend(filter(None, map(cleanup_url, f.readlines())))
            f.close()

        return urls
Ejemplo n.º 10
0
    def test_template(self):
        with self.app.app_context():
            init_db()

            a = insert_node(name='a', value=None)
            add_template_for_node('template_a.html', a)
            aa = insert_node(name='aa', value=None)
            add_template_for_node('template_a.html', aa)
            b = insert_node(name='b', value=None)
            add_template_for_node('template_b.html', b)
            c = insert_node(name='c', value=None)
            add_template_for_node('template_c.html', c)

            c = db.cursor()
            result = c.execute(fetch_query_string('select_template_from_node.sql'), {'node_id': a}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'

            # another node that uses the same template
            c = db.cursor()
            result = c.execute(fetch_query_string('select_template_from_node.sql'), {'node_id': aa}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'

            # can overwrite what node is tied to what template
            add_template_for_node('template_over_a.html', a)

            c = db.cursor()
            result = c.execute(fetch_query_string('select_template_from_node.sql'), {'node_id': a}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_over_a.html'

            # this one still uses the other template
            c = db.cursor()
            result = c.execute(fetch_query_string('select_template_from_node.sql'), {'node_id': aa}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('name', None) for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'
Ejemplo n.º 11
0
    def test_delete_one_node(self):
        """
        Delete a node
        """
        with self.app.app_context():
            init_db()
            result = db.execute(text(fetch_query_string('insert_node.sql')), name='a', value='apple')
            a = result.lastrowid

            result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=a).fetchall()
            assert len(result) == 1
            r = result[0]
            assert a == r['node_id']
            assert 'a' == r['name']
            assert 'apple' == r['value']

            # now delete
            delete_node(node_id=a)

            result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=a).fetchall()
            assert len(result) == 0
Ejemplo n.º 12
0
    def test_template(self):
        with self.app.app_context():
            init_db()

            a = insert_node(name='a', value=None)
            add_template_for_node('template_a.html', a)
            aa = insert_node(name='aa', value=None)
            add_template_for_node('template_a.html', aa)
            b = insert_node(name='b', value=None)
            add_template_for_node('template_b.html', b)
            c = insert_node(name='c', value=None)
            add_template_for_node('template_c.html', c)

            result = db.execute(text(fetch_query_string('select_template_from_node.sql')), node_id=a)
            result = [x['name'] for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'

            # another node that uses the same template
            result = db.execute(text(fetch_query_string('select_template_from_node.sql')), node_id=aa)
            result = [x['name'] for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'

            # can overwrite what node is tied to what template
            add_template_for_node('template_over_a.html', a)

            result = db.execute(text(fetch_query_string('select_template_from_node.sql')), node_id=a)
            result = [x['name'] for x in result]
            assert len(result) == 1
            assert result[0] == 'template_over_a.html'

            # this one still uses the other template
            result = db.execute(text(fetch_query_string('select_template_from_node.sql')), node_id=aa)
            result = [x['name'] for x in result]
            assert len(result) == 1
            assert result[0] == 'template_a.html'
Ejemplo n.º 13
0
    def test_delete_node_with_link(self):
        """
        Delete a node also will delete from link
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            result = db.query(
                fetch_query_string('select_link_node_from_node.sql'),
                fetchall=True,
                **{'node_id': a_id})
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = db.query(
                fetch_query_string('select_link_node_from_node.sql'),
                fetchall=True,
                **{'node_id': b_id})
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result

            # now delete (should use the 'on delete cascade' sql bit)
            trans = db.transaction()
            db.query(fetch_query_string('delete_node_for_id.sql'),
                     **{'node_id': a_id})
            trans.commit()

            result = db.query(fetch_query_string('select_node_from_id.sql'),
                              fetchall=True,
                              **{'node_id': a_id})
            assert len(result) == 0

            result = db.query(
                fetch_query_string('select_link_node_from_node.sql'),
                fetchall=True,
                **{'node_id': a_id})
            assert len(result) == 0

            result = db.query(
                fetch_query_string('select_node_node_from_node_id.sql'),
                fetchall=True,
                **{'node_id': a_id})
            assert len(result) == 0
Ejemplo n.º 14
0
    def test_insert_one_node_with_unicode(self):
        """
        Add a node with a unicode value
        """
        with self.app.app_context():
            init_db()
            result = db.execute(text(fetch_query_string('insert_node.sql')), name='a', value=u'Àрpĺè')
            a = result.lastrowid

            result = db.execute(text('select * from Node where id = :id;'), id=a).fetchall()
            assert len(result) == 1
            r = result[0]
            assert a == r['id']
            assert 'a' == r['name']
            assert u'Àрpĺè' == r['value']
Ejemplo n.º 15
0
def render_value_for_node(node_id):
    """
    Wrap render_node for usage in operate scripts.  Returns without template
    rendered.
    """
    value = None
    result = []
    try:
        result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=node_id).fetchall()
    except DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    if result:
        kw = dict(zip(result[0].keys(), result[0].values()))
        value = render_node(node_id, noderequest={'_no_template':True}, **kw)

    return value
Ejemplo n.º 16
0
    def test_insert_one_node(self):
        """
        Add a node
        """
        with self.app.app_context():
            init_db()
            c = db.cursor()
            c.execute(fetch_query_string('insert_node.sql'), {'name': 'a', 'value':'apple'})
            a = c.lastrowid
            db.commit()

            result = c.execute('select * from Node where id = :id;', {'id':a}).fetchall()
            (result, col_names) = rowify(result, c.description)
            assert len(result) == 1
            r = result.pop()
            assert a == r.get('id')
            assert 'a' == r.get('name')
            assert 'apple' == r.get('value')
Ejemplo n.º 17
0
    def test_delete_node_with_link(self):
        """
        Delete a node also will delete from link
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            result = db.execute(text(
                fetch_query_string('select_link_node_from_node.sql')),
                                node_id=a_id)
            result = [x['node_id'] for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = db.execute(text(
                fetch_query_string('select_link_node_from_node.sql')),
                                node_id=b_id)
            result = [x['node_id'] for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result

            # now delete (should use the 'on delete cascade' sql bit)
            db.execute(text(fetch_query_string('delete_node_for_id.sql')),
                       node_id=a_id)

            result = db.execute(text(
                fetch_query_string('select_node_from_id.sql')),
                                node_id=a_id).fetchall()
            assert len(result) == 0

            result = db.execute(text(
                fetch_query_string('select_link_node_from_node.sql')),
                                node_id=a_id).fetchall()
            assert len(result) == 0

            result = db.execute(text(
                fetch_query_string('select_node_node_from_node_id.sql')),
                                node_id=a_id).fetchall()

            assert len(result) == 0
Ejemplo n.º 18
0
    def test_delete_node_with_link(self):
        """
        Delete a node also will delete from link
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            c = db.cursor()
            result = c.execute(fetch_query_string('select_link_node_from_node.sql'), {'node_id': a_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = c.execute(fetch_query_string('select_link_node_from_node.sql'), {'node_id': b_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            result = [x.get('node_id', None) for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result

            # now delete (should use the 'on delete cascade' sql bit)
            c = db.cursor()
            c.execute(fetch_query_string('delete_node_for_id.sql'), {'node_id': a_id})
            db.commit()

            result = c.execute(fetch_query_string('select_node_from_id.sql'), {'node_id': a_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            assert len(result) == 0

            c = db.cursor()
            result = c.execute(fetch_query_string('select_link_node_from_node.sql'), {'node_id': a_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            assert len(result) == 0

            result = c.execute(fetch_query_string('select_node_node_from_node_id.sql'), {'node_id': a_id}).fetchall()
            (result, col_names) = rowify(result, c.description)
            assert len(result) == 0
Ejemplo n.º 19
0
    def test_insert_one_node_with_unicode(self):
        """
        Add a node with a unicode value
        """
        with self.app.app_context():
            init_db()
            trans = db.transaction()
            result = db.db.execute(fetch_query_string('insert_node.sql'), {
                'name': 'a',
                'value': u'Àрpĺè'
            })
            a = result.lastrowid
            trans.commit()

            result = db.query('select * from Node where id = :id;',
                              fetchall=True,
                              **{'id': a})
            assert len(result) == 1
            r = result.first()
            assert a == r.get('id')
            assert 'a' == r.get('name')
            assert u'Àрpĺè' == r.get('value')
Ejemplo n.º 20
0
    def test_delete_node_with_link(self):
        """
        Delete a node also will delete from link
        """
        with self.app.app_context():
            init_db()
            a_id = insert_node(name='a', value=None)
            b_id = insert_node(name='b', value=None)
            c_id = insert_node(name='c', value="c")
            d_id = insert_node(name='d', value="d")

            # a -> c, b -> c
            # a -> d
            insert_node_node(node_id=a_id, target_node_id=c_id)
            insert_node_node(node_id=a_id, target_node_id=d_id)
            insert_node_node(node_id=b_id, target_node_id=c_id)

            result = db.execute(text(fetch_query_string('select_link_node_from_node.sql')), node_id=a_id)
            result = [x['node_id'] for x in result]
            assert c_id in result
            assert d_id in result
            assert a_id not in result

            result = db.execute(text(fetch_query_string('select_link_node_from_node.sql')), node_id=b_id)
            result = [x['node_id'] for x in result]
            assert c_id in result
            assert d_id not in result
            assert a_id not in result

            # now delete (should use the 'on delete cascade' sql bit)
            db.execute(text(fetch_query_string('delete_node_for_id.sql')), node_id=a_id)

            result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=a_id).fetchall()
            assert len(result) == 0

            result = db.execute(text(fetch_query_string('select_link_node_from_node.sql')), node_id=a_id).fetchall()
            assert len(result) == 0


            result = db.execute(text(fetch_query_string('select_node_node_from_node_id.sql')), node_id=a_id).fetchall()

            assert len(result) == 0
Ejemplo n.º 21
0
    def test_rules(self):
        f = open(os.path.join(self.tmp_template_dir, 'insert_promoattr.sql'),
                 'w')
        f.write("""
          insert into PromoAttr (node_id, title, description) values (:node_id, :title, :description);
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_promoattr.sql'),
                 'w')
        f.write("""
          select * from PromoAttr where node_id = :node_id;
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_promos.sql'), 'w')
        f.write("""
          select id as node_id, * from Node where name = 'promo' order by id limit 2 offset 13;
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_mainmenu.sql'),
                 'w')
        f.write("""
          select name as link from Node where name like 'page_' order by link;
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_pageattr.sql'),
                 'w')
        f.write("""
          select 'example title' as title, 'a description of the page' as description;
          """)
        f.close()

        expected = {
            "mainmenu": [{
                "link": "page1"
            }, {
                "link": "page2"
            }, {
                "link": "page3"
            }],
            "pageattr": {
                "description": "a description of the page",
                "title": "example title"
            },
            "promos": [{
                "promo": {
                    "description": "aaaaaaaaaaaaa",
                    "node_id": 20,
                    "title": "promo 13"
                }
            }, {
                "promo": {
                    "description": "aaaaaaaaaaaaaa",
                    "node_id": 21,
                    "title": "promo 14"
                }
            }]
        }
        with self.app.app_context():
            with self.app.test_client() as c:
                init_db()
                trans = db.transaction()
                db.query("""
                create table PromoAttr (
                  node_id integer,
                  abc integer,
                  title varchar(255),
                  description text
                  );
                """)
                trans.commit()

                page_id = insert_node(name='page1', value=None)
                print page_id
                insert_route(path='/page1/', node_id=page_id)

                pageattr_id = insert_node(name='pageattr', value=None)
                print pageattr_id
                insert_node_node(node_id=page_id, target_node_id=pageattr_id)
                insert_query(name='select_pageattr.sql', node_id=pageattr_id)

                mainmenu_id = insert_node(name='mainmenu', value=None)
                insert_node_node(node_id=page_id, target_node_id=mainmenu_id)
                insert_query(name='select_mainmenu.sql', node_id=mainmenu_id)
                # Add some other pages that will be shown in menu as just links
                insert_node(name='page2', value=None)
                insert_node(name='page3', value=None)

                promos_id = insert_node(name='promos', value=None)
                insert_node_node(node_id=page_id, target_node_id=promos_id)
                insert_query(name='select_promos.sql', node_id=promos_id)

                for a in range(0, 100):
                    a_id = insert_node(name='promo', value=None)
                    trans = db.transaction()
                    db.query(
                        fetch_query_string('insert_promoattr.sql'), **{
                            'node_id': a_id,
                            'title': 'promo %i' % a,
                            'description': 'a' * a
                        })
                    trans.commit()
                    # wire the promo to it's attr
                    insert_query(name='select_promoattr.sql', node_id=a_id)

                rv = c.get('/page1', follow_redirects=True)
                print rv
                assert 200 == rv.status_code
                rv_json = json.loads(rv.data)
                assert set(expected.keys()) == set(rv_json.keys())
                assert set(expected['pageattr'].keys()) == set(
                    rv_json['pageattr'].keys())
Ejemplo n.º 22
0
def operate_menu():
    "Select between these operations on the database"

    selection = True
    while selection:

        print globals()['operate_menu'].__doc__
        selection = select([
            'chill.database functions',
            'execute sql file',
            'render_node',
            'New collection',
            'Manage collection',
            'Add document for node',
            'help',
            ])
        if selection == 'chill.database functions':
            mode_database_functions()
        elif selection == 'execute sql file':
            print "View the sql file and show a fill in the blanks interface with raw_input"
            sqlfile = choose_query_file()
            if not sqlfile:
                # return to the menu choices if not file picked
                selection = True
            else:
                sql_named_placeholders_re = re.compile(r":(\w+)")
                sql = fetch_query_string(sqlfile)
                placeholders = set(sql_named_placeholders_re.findall(sql))
                print sql
                data = {}
                for placeholder in placeholders:
                    value = raw_input(placeholder + ': ')
                    data[placeholder] = value

                result = []
                try:
                    result = db.execute(text(sql), data)
                except DatabaseError as err:
                    current_app.logger.error("DatabaseError: %s", err)

                if result and result.returns_rows:
                    result = result.fetchall()
                    print result
                    if not result:
                        print 'No results.'
                    else:
                        kw = result[0]

                        if 'node_id' in kw:
                            print 'render node %s' % kw['node_id']
                            value = render_node(kw['node_id'], **kw)
                            print safe_dump(value, default_flow_style=False)
                        else:
                            #print safe_dump(rowify(result, [(x, None) for x in result[0].keys()]), default_flow_style=False)
                            print safe_dump([dict(zip(x.keys(), x.values())) for x in result], default_flow_style=False)

        elif selection == 'render_node':
            print globals()['render_node'].__doc__
            node_id = existing_node_input()

            value = render_value_for_node(node_id)
            print safe_dump(value, default_flow_style=False)

        elif selection == 'New collection':
            mode_new_collection()
        elif selection == 'Manage collection':
            mode_collection()
        elif selection == 'Add document for node':
            folder = current_app.config.get('DOCUMENT_FOLDER')
            if not folder:
                print "No DOCUMENT_FOLDER configured for the application."
            else:
                choices = map(os.path.basename,
                            glob(os.path.join(folder, '*'))
                            )
                choices.sort()
                if len(choices) == 0:
                    print "No files found in DOCUMENT_FOLDER."
                else:
                    filename = select(choices)
                    if filename:
                        defaultname = os.path.splitext(filename)[0]
                        nodename = raw_input("Enter name for node [{0}]: ".format(defaultname)) or defaultname
                        node = insert_node(name=nodename, value=filename)
                        print "Added document '%s' to node '%s' with id: %s" % (filename, nodename, node)
        elif selection == 'help':
            print "------"
            print __doc__
            print "------"
        else:
            print 'Done'
Ejemplo n.º 23
0
    def test_rules(self):
        f = open(os.path.join(self.tmp_template_dir, 'insert_promoattr.sql'), 'w')
        f.write("""
          insert into PromoAttr (node_id, title, description) values (:node_id, :title, :description);
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_promoattr.sql'), 'w')
        f.write("""
          select * from PromoAttr where node_id = :node_id;
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_promos.sql'), 'w')
        f.write("""
          select id as node_id, * from Node where name = 'promo' order by id limit 2 offset 13;
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_mainmenu.sql'), 'w')
        f.write("""
          select name as link from Node where name like 'page_' order by link;
          """)
        f.close()
        f = open(os.path.join(self.tmp_template_dir, 'select_pageattr.sql'), 'w')
        f.write("""
          select 'example title' as title, 'a description of the page' as description;
          """)
        f.close()

        expected = {
                "mainmenu": [
                    { "link": "page1" },
                    { "link": "page2" },
                    { "link": "page3" }
                    ],
                "pageattr": {
                    "description": "a description of the page",
                    "title": "example title"
                    },
                "promos": [
                    { "promo": {
                            "description": "aaaaaaaaaaaaa",
                            "node_id": 20,
                            "title": "promo 13"
                            }
                        },
                    { "promo": {
                            "description": "aaaaaaaaaaaaaa",
                            "node_id": 21,
                            "title": "promo 14"
                            }
                        }
                    ]
                }
        with self.app.app_context():
            with self.app.test_client() as c:
                init_db()
                db.execute(text("""
                create table PromoAttr (
                  node_id integer,
                  abc integer,
                  title varchar(255),
                  description text
                  );
                """))

                page_id = insert_node(name='page1', value=None)
                insert_route(path='/page1/', node_id=page_id)

                pageattr_id = insert_node(name='pageattr', value=None)
                insert_node_node(node_id=page_id, target_node_id=pageattr_id)
                insert_query(name='select_pageattr.sql', node_id=pageattr_id)

                mainmenu_id = insert_node(name='mainmenu', value=None)
                insert_node_node(node_id=page_id, target_node_id=mainmenu_id)
                insert_query(name='select_mainmenu.sql', node_id=mainmenu_id)
                # Add some other pages that will be shown in menu as just links
                insert_node(name='page2', value=None)
                insert_node(name='page3', value=None)

                promos_id = insert_node(name='promos', value=None)
                insert_node_node(node_id=page_id, target_node_id=promos_id)
                insert_query(name='select_promos.sql', node_id=promos_id)


                for a in range(0,100):
                    a_id = insert_node(name='promo', value=None)
                    db.execute(text(fetch_query_string('insert_promoattr.sql')), **{'node_id':a_id, 'title':'promo %i' % a, 'description': 'a'*a})
                    # wire the promo to it's attr
                    insert_query(name='select_promoattr.sql', node_id=a_id)

                rv = c.get('/page1', follow_redirects=True)
                assert 200 == rv.status_code
                rv_json = json.loads(rv.data)
                assert set(expected.keys()) == set(rv_json.keys())
                assert set(expected['pageattr'].keys()) == set(rv_json['pageattr'].keys())
Ejemplo n.º 24
0
def mode_database_functions():
    "Select a function to perform from chill.database"

    print globals()['mode_database_functions'].__doc__
    selection = True
    database_functions = [
            'init_db',
            'insert_node',
            'insert_node_node',
            'delete_node',
            'select_node',
            'insert_route',
            'insert_query',
            'add_template_for_node',
            'fetch_query_string',
            ]
    while selection:
        choices = database_functions + [
            'help',
            ]
        selection = select(choices)

        if selection:
            print globals().get(selection).__doc__
        if selection == 'init_db':
            confirm = raw_input("Initialize new database y/n? [n] ")
            if confirm == 'y':
                init_db()
        elif selection == 'insert_node':
            name = raw_input("Node name: ")
            value = raw_input("Node value: ")
            node = insert_node(name=name, value=value or None)
            print "name: %s \nid: %s" % (name, node)

        elif selection == 'insert_query':
            sqlfile = choose_query_file()
            if sqlfile:
                node = existing_node_input()
                if node >= 0:
                    insert_query(name=sqlfile, node_id=node)
                    print "adding %s to node id: %s" % (sqlfile, node)

        elif selection == 'insert_node_node':
            print "Add parent node id"
            node = existing_node_input()
            print "Add target node id"
            target_node = existing_node_input()
            if node >= 0 and target_node >= 0:
                insert_node_node(node_id=node, target_node_id=target_node)

        elif selection == 'delete_node':
            node = existing_node_input()
            if node >= 0:
                delete_node(node_id=node)

        elif selection == 'select_node':
            node = existing_node_input()
            if node >= 0:
                result = select_node(node_id=node)
                print safe_dump(dict(zip(result[0].keys(), result[0].values())), default_flow_style=False)

        elif selection == 'insert_route':
            path = raw_input('path: ')
            weight = raw_input('weight: ') or None
            method = raw_input('method: ') or 'GET'
            node = existing_node_input()
            if node >= 0:
                insert_route(path=path, node_id=node, weight=weight, method=method)
        elif selection == 'add_template_for_node':
            folder = current_app.config.get('THEME_TEMPLATE_FOLDER')
            choices = map(os.path.basename,
                        glob(os.path.join(folder, '*'))
                        )
            choices.sort()
            templatefile = select(choices)
            if templatefile:
                node = existing_node_input()
                if node >= 0:
                    add_template_for_node(name=templatefile, node_id=node)
                    print "adding %s to node id: %s" % (templatefile, node)

        elif selection == 'fetch_query_string':
            sqlfile = choose_query_file()
            if sqlfile:
                sql = fetch_query_string(sqlfile)
                print sql

        elif selection == 'help':
            print "------"
            for f in database_functions:
                print "\n** %s **" % f
                print globals().get(f).__doc__
            print "------"
        else:
            pass