You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

appstate.go 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package system
  4. import (
  5. "context"
  6. "code.gitea.io/gitea/models/db"
  7. )
  8. // AppState represents a state record in database
  9. // if one day we would make Gitea run as a cluster,
  10. // we can introduce a new field `Scope` here to store different states for different nodes
  11. type AppState struct {
  12. ID string `xorm:"pk varchar(200)"`
  13. Revision int64
  14. Content string `xorm:"LONGTEXT"`
  15. }
  16. func init() {
  17. db.RegisterModel(new(AppState))
  18. }
  19. // SaveAppStateContent saves the app state item to database
  20. func SaveAppStateContent(key, content string) error {
  21. return db.WithTx(db.DefaultContext, func(ctx context.Context) error {
  22. eng := db.GetEngine(ctx)
  23. // try to update existing row
  24. res, err := eng.Exec("UPDATE app_state SET revision=revision+1, content=? WHERE id=?", content, key)
  25. if err != nil {
  26. return err
  27. }
  28. rows, _ := res.RowsAffected()
  29. if rows != 0 {
  30. // the existing row is updated, so we can return
  31. return nil
  32. }
  33. // if no existing row, insert a new row
  34. _, err = eng.Insert(&AppState{ID: key, Content: content})
  35. return err
  36. })
  37. }
  38. // GetAppStateContent gets an app state from database
  39. func GetAppStateContent(key string) (content string, err error) {
  40. e := db.GetEngine(db.DefaultContext)
  41. appState := &AppState{ID: key}
  42. has, err := e.Get(appState)
  43. if err != nil {
  44. return "", err
  45. } else if !has {
  46. return "", nil
  47. }
  48. return appState.Content, nil
  49. }