Skip to content

Commit 5029bb3

Browse files
added file lock checking inside import command
1 parent b296e1b commit 5029bb3

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

internal/cmd/db_import.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,32 @@ import (
55
"path/filepath"
66
"strings"
77

8+
"fmt"
9+
"os"
10+
"syscall"
11+
812
"github.com/spf13/cobra"
913
)
1014

15+
func isFileLocked(filename string) (bool, error) {
16+
f, err := os.Open(filename)
17+
if err != nil {
18+
return false, err
19+
}
20+
defer f.Close()
21+
22+
err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
23+
if err != nil {
24+
if errors.Is(err, syscall.EWOULDBLOCK) {
25+
return true, nil // File is locked
26+
}
27+
return false, fmt.Errorf("failed to check lock: %w", err)
28+
}
29+
30+
syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
31+
return false, nil
32+
}
33+
1134
func init() {
1235
dbCmd.AddCommand(importCmd)
1336
addGroupFlag(importCmd)
@@ -29,6 +52,15 @@ var importCmd = &cobra.Command{
2952
return errors.New("filename is required: 'turso db import <filename>'")
3053
}
3154
filename := args[0]
55+
56+
locked, err := isFileLocked(filename)
57+
if err != nil {
58+
return fmt.Errorf("could not check file lock: %w", err)
59+
}
60+
if locked {
61+
return errors.New("database file is locked by another process (close any open connections and try again)")
62+
}
63+
3264
fromFileFlag = filename
3365
name := sanitizeDatabaseName(filename)
3466
return CreateDatabase(name)

0 commit comments

Comments
 (0)