| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | |
| 7 | "gorm.io/gorm" |
| 8 | ) |
| 9 | |
| 10 | var errContentKeyMismatch = errors.New("docs: content key does not match this database") |
| 11 | var errContentMixed = errors.New("docs: mixed content encodings; run docs-seal offline") |
| 12 | |
| 13 | func requireSealedContent(ctx context.Context, g *gorm.DB) error { |
| 14 | var mixed bool |
| 15 | if err := g.WithContext(ctx).Raw(`SELECT EXISTS(SELECT 1 FROM doc_updates WHERE content_encoding != 1 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_snapshots WHERE content_encoding != 1 LIMIT 1)`).Scan(&mixed).Error; err != nil { |
| 16 | return err |
| 17 | } |
| 18 | if mixed { |
| 19 | return errContentMixed |
| 20 | } |
| 21 | return nil |
| 22 | } |
| 23 | |
| 24 | func refuseActivatedLegacyWrite(tx *gorm.DB) error { |
| 25 | var count int64 |
| 26 | if err := tx.Model(&contentSealing{}).Where("id = 1").Count(&count).Error; err != nil { |
| 27 | return err |
| 28 | } |
| 29 | if count != 0 { |
| 30 | return errContentState |
| 31 | } |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | func (s *Store) prepareContentUpdate(tx *gorm.DB, guid string, row *DocUpdate) error { |
| 36 | if s.content == nil { |
| 37 | return refuseActivatedLegacyWrite(tx) |
| 38 | } |
| 39 | return s.content.sealUpdate(guid, row) |
| 40 | } |
| 41 | |
| 42 | func (s *Store) prepareContentSnapshot(tx *gorm.DB, guid string, row *DocSnapshot) error { |
| 43 | if s.content == nil { |
| 44 | return refuseActivatedLegacyWrite(tx) |
| 45 | } |
| 46 | return s.content.sealSnapshot(guid, row) |
| 47 | } |
| 48 | |
| 49 | func (s *Store) openContentUpdate(guid string, row *DocUpdate) error { |
| 50 | if s.content == nil { |
| 51 | if row.ContentEncoding != 0 { |
| 52 | return errContentEncoding |
| 53 | } |
| 54 | return nil |
| 55 | } |
| 56 | return s.content.openUpdate(guid, row) |
| 57 | } |
| 58 | |
| 59 | func (s *Store) openContentSnapshot(guid string, row *DocSnapshot) error { |
| 60 | if s.content == nil { |
| 61 | if row.ContentEncoding != 0 { |
| 62 | return errContentEncoding |
| 63 | } |
| 64 | return nil |
| 65 | } |
| 66 | return s.content.openSnapshot(guid, row) |
| 67 | } |
| 68 | |