0

I have a table in my database containing a linked list.

ID | page | prior | next
1  | A    | 0     | 2
2  | B    | 1     | 3
3  | C    | 2     | 4
4  | D    | 3     | 5
5  | E    | 4     | 0

How do I display all the items in this table? A SORT BY wouldn't work after a few positional swaps and insertions. I'm using Flask, which uses Jinja2 templates. My current approach is to locate the first item and add it to a list. Then, based on the previous item's "next" value, collect the next row and add it to the list.

num_rows = Pages.query.count()

# find first row, the one where prior is 0
first_row = Pages.query.filter_by(prior=0).first()

# create a list containing just the first row for now
all_rows = [first_row, ]

# add new rows to the list
for i in range(0, (num_rows-1)):
    current_row = all_rows[i].next
    all_rows.append(Pages.query.get(current_row))

Finally, I pass the list to render_template('template.html', all_rows = all_rows), then retrieve it in the template.

Surely there's a more elegant approach? I imagine that this would perform terribly and require lots of resources?

Panpaper
  • 451
  • 1
  • 6
  • 16
  • I think, there is a much simpler way for your use case: pagination. See [Miguels Blog pagination](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination) or [documentation](https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/). Hope this helps. – above_c_level Apr 04 '20 at 11:00
  • 1
    Thanks but I’ve seen that tutorial and used pagination on other parts of my project. Unfortunately that’s not related to what I’m describing here, this structure allows users to rearrange or insert pages in any order they like. Pagination simply displays all the pages in the order they were created in. A column for page orders requires a lot of rewrites whenever an insertion happens in the middle. – Panpaper Apr 04 '20 at 16:18
  • Pagination is not that simple doing manually. If your solution works: Chapeau! – above_c_level Apr 04 '20 at 17:39

1 Answers1

1

It depends on what DBMS you’re using. Oracle has a proprietary CONNECT BY PRIOR syntax that’s very easy to read. Many others have a WITH syntax that’s harder to follow but can accomplish the same result.

See Simulation of CONNECT BY PRIOR of ORACLE in SQL SERVER.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80