-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
73 lines (65 loc) · 1.73 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package couchdb
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/simia-tech/couchdb/value"
)
// Various errors.
var (
ErrDatabaseAlreadyExists = errors.New("database already exists")
ErrDatabaseDoesNotExists = errors.New("database does not exists")
)
// Database implements all methods on a couchdb database.
type Database struct {
client *Client
name string
}
// NewDatabase returns a new database using the provided `*Client` with the provided name.
func NewDatabase(client *Client, name string) *Database {
return &Database{
client: client,
name: name,
}
}
// Create creates the database.
func (db *Database) Create(ctx context.Context) error {
r := value.Status{}
if err := db.client.requestJSON(ctx, http.MethodPut, "/"+db.name, nil, nil, &r); err != nil {
return err
}
if !r.OK {
switch r.Error {
case "file_exists":
return fmt.Errorf("create database %s: %w", db.name, ErrDatabaseAlreadyExists)
default:
return fmt.Errorf("unknown error %s: %s", r.Error, r.Reason)
}
}
return nil
}
// Delete deletes the database.
func (db *Database) Delete(ctx context.Context) error {
r := value.Status{}
if err := db.client.requestJSON(ctx, http.MethodDelete, "/"+db.name, nil, nil, &r); err != nil {
return err
}
if !r.OK {
switch r.Error {
case "not_found":
return fmt.Errorf("delete database %s: %w", db.name, ErrDatabaseDoesNotExists)
default:
return fmt.Errorf("unknown error %s: %s", r.Error, r.Reason)
}
}
return nil
}
// Info fetches infos about the database.
func (db *Database) Info(ctx context.Context) (value.DatabaseInfo, error) {
r := value.DatabaseInfo{}
if err := db.client.requestJSON(ctx, http.MethodGet, "/"+db.name, nil, nil, &r); err != nil {
return r, err
}
return r, nil
}