code.gitea.io/gitea@v1.21.7/models/system/appstate.go (about)

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