Skip to content

Instantly share code, notes, and snippets.

@chrisvdg
Created September 26, 2017 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvdg/0858228b6843d46289232619bebe4bc4 to your computer and use it in GitHub Desktop.
Save chrisvdg/0858228b6843d46289232619bebe4bc4 to your computer and use it in GitHub Desktop.
Crude example metadata storage fs with Gorm and Cockroach db
package testcockroach
import (
"fmt"
"log"
"testing"
// Import GORM-related packages.
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type Path struct {
Name string `gorm:"primary_key"`
Files []File
}
type File struct {
ID int `sql:"AUTO_INCREMENT" gorm:"primary_key"`
PathName string `gorm:"index"`
Name string
Filemode int32
IsDir bool
StorKey []byte
}
func TestCockroach(t *testing.T) {
const addr = "postgresql://maxroach@localhost:26257/fs?sslmode=disable"
db, err := gorm.Open("postgres", addr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.AutoMigrate(&Path{}, &File{})
// create a fs
rootPath := Path{
Name: "\\root",
Files: []File{
File{
Name: "nothing_to_worry_about.exe",
},
File{
Name: "some_dir",
IsDir: true,
},
},
}
someDir := Path{
Name: "\\root\\some_dir",
Files: []File{
File{
Name: "not_a_virus.exe",
},
},
}
db.Create(&rootPath)
db.Create(&someDir)
// select dir
var firstPath Path
db.Where("name = ?", "\\root").Find(&firstPath)
fmt.Println(firstPath.Name)
// find file in dir
var file File
db.Where("name = ? AND path_name = ?", "not_a_virus.exe", "\\root\\some_dir").Find(&file)
fmt.Println(file.Name)
// make new path
NewPath := Path{
Name: "\\root\\other_dir",
}
db.Create(&NewPath)
rootPath.Files = append(rootPath.Files, File{Name: "other_dir", IsDir: true})
db.Model(&rootPath).Updates(&rootPath)
// add file to new dir
NewPath.Files = append(NewPath.Files, File{Name: "nice.jpg"})
db.Model(&NewPath).Updates(&NewPath)
var niceFile File
db.Where("name = ? AND path_name = ?", "nice.jpg", "\\root\\other_dir").Find(&niceFile)
fmt.Println(niceFile.Name)
// list directory
var files []File
db.Where("path_name = ?", "\\root").Find(&files)
fmt.Println("printing dir: \\root")
printDir(files)
}
func printDir(files []File) {
for _, file := range files {
if file.IsDir {
fmt.Printf("%s\t%s\n", file.Name, "dir")
} else {
fmt.Printf("%s\t%s\n", file.Name, "file")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment