MCPcopy Index your code
hub / github.com/perkeep/perkeep / newKeyValueFromJSONConfig

Function newKeyValueFromJSONConfig

pkg/sorted/postgres/postgreskv.go:39–116  ·  view source on GitHub ↗
(cfg jsonconfig.Obj)

Source from the content-addressed store, hash-verified

37}
38
39func newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) {
40 var (
41 user = cfg.RequiredString("user")
42 database = cfg.RequiredString("database")
43 host = cfg.OptionalString("host", "localhost")
44 password = cfg.OptionalString("password", "")
45 sslmode = cfg.OptionalString("sslmode", "require")
46 )
47 if err := cfg.Validate(); err != nil {
48 return nil, err
49 }
50
51 // connect without a database, it may not exist yet
52 conninfo := fmt.Sprintf("user=%s host=%s sslmode=%s", user, host, sslmode)
53 if password != "" {
54 conninfo += fmt.Sprintf(" password=%s", password)
55 }
56 db, err := sql.Open("postgres", conninfo)
57 if err != nil {
58 return nil, err
59 }
60 err = createDB(db, database)
61 db.Close() // ignoring error, if createDB failed db.Close() will likely also fail
62 if err != nil {
63 return nil, err
64 }
65
66 // reconnect after database is created
67 conninfo += fmt.Sprintf(" dbname=%s", database)
68 db, err = sql.Open("postgres", conninfo)
69 if err != nil {
70 return nil, err
71 }
72
73 for _, tableSQL := range SQLCreateTables() {
74 if _, err := db.Exec(tableSQL); err != nil {
75 return nil, fmt.Errorf("error creating table with %q: %v", tableSQL, err)
76 }
77 }
78 for _, statement := range SQLDefineReplace() {
79 if _, err := db.Exec(statement); err != nil {
80 return nil, fmt.Errorf("error setting up replace statement with %q: %v", statement, err)
81 }
82 }
83 r, err := db.Query(fmt.Sprintf(`SELECT replaceintometa('version', '%d')`, SchemaVersion()))
84 if err != nil {
85 return nil, fmt.Errorf("error setting schema version: %v", err)
86 }
87 r.Close()
88
89 kv := &keyValue{
90 db: db,
91 KeyValue: &sqlkv.KeyValue{
92 DB: db,
93 SetFunc: altSet,
94 BatchSetFunc: altBatchSet,
95 PlaceHolderFunc: replacePlaceHolders,
96 },

Callers

nothing calls this directly

Calls 10

pingMethod · 0.95
SchemaVersionMethod · 0.95
IsDevFunction · 0.92
createDBFunction · 0.85
SQLDefineReplaceFunction · 0.85
SQLCreateTablesFunction · 0.70
SchemaVersionFunction · 0.70
OpenMethod · 0.65
CloseMethod · 0.65
QueryMethod · 0.65

Tested by

no test coverage detected