oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1package store
2
3import "fmt"
4
5// Formats reads every formatted cell in the tab in two queries.
6//
7// Handle.Format answers for one cell with two round trips, which was
8// right while formatting was a thing only the XLSX importer wrote and
9// only the contrast check read. It stops being right the moment the
10// grid paints formats: snapshot walks a whole window, so a hundred
11// formatted cells became two hundred queries per page load — and the
12// cost is invisible in every test, because the tests all use tabs with
13// a handful of cells.
14//
15// Two queries and not one: the join would return the interned Format's
16// columns once per cell using it, which is exactly the duplication
17// interning exists to avoid. A column of 5,000 identically styled cells
18// is one Format row here, and this reads it once.
19//
20// The returned pointers are shared — several coordinates map to the
21// same *Format, because that is what interning means. Callers read
22// them; nothing mutates one in place.
23func (h *Handle) Formats() (map[CellCoord]*Format, error) {
24 var cells []Cell
25 if err := h.db.Select("row_id", "col_id", "format_id").
26 Where("tab_id = ? AND format_id IS NOT NULL", h.tabID).
27 Find(&cells).Error; err != nil {
28 return nil, fmt.Errorf("store: list formatted cells: %w", err)
29 }
30 if len(cells) == 0 {
31 return map[CellCoord]*Format{}, nil
32 }
33
34 ids := make([]uint64, 0, len(cells))
35 seen := make(map[uint64]bool, len(cells))
36 for _, c := range cells {
37 if c.FormatID == nil || seen[*c.FormatID] {
38 continue
39 }
40 seen[*c.FormatID] = true
41 ids = append(ids, *c.FormatID)
42 }
43
44 var rows []Format
45 if err := h.db.Where("id IN ?", ids).Find(&rows).Error; err != nil {
46 return nil, fmt.Errorf("store: read formats: %w", err)
47 }
48 byID := make(map[uint64]*Format, len(rows))
49 for i := range rows {
50 byID[rows[i].ID] = &rows[i]
51 }
52
53 out := make(map[CellCoord]*Format, len(cells))
54 for _, c := range cells {
55 // A cell pointing at a Format row that is not there is dropped
56 // rather than defaulted. It cannot happen through any path this
57 // package offers — formats are interned before they are
58 // assigned and never deleted — and if it ever does, an unstyled
59 // cell is a better answer than a styled one we invented.
60 if c.FormatID == nil {
61 continue
62 }
63 if f, ok := byID[*c.FormatID]; ok {
64 out[CellCoord{RowID: c.RowID, ColID: c.ColID}] = f
65 }
66 }
67 return out, nil
68}
69