summaryrefslogtreecommitdiff
path: root/pkg/database
diff options
context:
space:
mode:
authorJulien Dessaux2025-02-04 23:34:26 +0100
committerJulien Dessaux2025-02-04 23:34:26 +0100
commitfcc220612495a21067f9043396ba63062537ad63 (patch)
tree6ffb59e3f61fdc433a2f7762465e43f6d326d31d /pkg/database
parentchore(tfstated): change database account id format to uuidv7 (diff)
downloadtfstated-fcc220612495a21067f9043396ba63062537ad63.tar.gz
tfstated-fcc220612495a21067f9043396ba63062537ad63.tar.bz2
tfstated-fcc220612495a21067f9043396ba63062537ad63.zip
feat(webui): add state creation page
Diffstat (limited to '')
-rw-r--r--pkg/database/states.go44
1 files changed, 44 insertions, 0 deletions
diff --git a/pkg/database/states.go b/pkg/database/states.go
index ccae942..75af2e5 100644
--- a/pkg/database/states.go
+++ b/pkg/database/states.go
@@ -8,8 +8,52 @@ import (
"time"
"git.adyxax.org/adyxax/tfstated/pkg/model"
+ "github.com/mattn/go-sqlite3"
)
+func (db *DB) CreateState(path string, accountId string, data []byte) (*model.Version, error) {
+ encryptedData, err := db.dataEncryptionKey.EncryptAES256(data)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt state data: %w", err)
+ }
+ version := &model.Version{
+ AccountId: accountId,
+ }
+ return version, db.WithTransaction(func(tx *sql.Tx) error {
+ result, err := tx.ExecContext(db.ctx, `INSERT INTO states(path) VALUES (?)`, path)
+ if err != nil {
+ var sqliteErr sqlite3.Error
+ if errors.As(err, &sqliteErr) {
+ if sqliteErr.Code == sqlite3.ErrNo(sqlite3.ErrConstraint) {
+ version = nil
+ return nil
+ }
+ }
+ return fmt.Errorf("failed to insert new state: %w", err)
+ }
+ stateId, err := result.LastInsertId()
+ if err != nil {
+ return fmt.Errorf("failed to get last insert id for new state: %w", err)
+ }
+ version.StateId = int(stateId)
+ result, err = tx.ExecContext(db.ctx,
+ `INSERT INTO versions(account_id, data, state_id)
+ VALUES (:accountID, :data, :stateID)`,
+ sql.Named("accountID", accountId),
+ sql.Named("data", encryptedData),
+ sql.Named("stateID", stateId))
+ if err != nil {
+ return fmt.Errorf("failed to insert new state version: %w", err)
+ }
+ versionId, err := result.LastInsertId()
+ if err != nil {
+ return fmt.Errorf("failed to get last insert id for new version of the state: %w", err)
+ }
+ version.Id = int(versionId)
+ return nil
+ })
+}
+
// returns true in case of successful deletion
func (db *DB) DeleteState(path string) (bool, error) {
result, err := db.Exec(`DELETE FROM states WHERE path = ?;`, path)