surrealpatch/txn/db.go

112 lines
2.3 KiB
Go
Raw Normal View History

2021-12-14 08:12:26 +00:00
// Copyright © 2016 SurrealDB Ltd.
2019-11-20 13:20:27 +00:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package txn
import (
"context"
2021-12-14 08:12:26 +00:00
"github.com/surrealdb/surrealdb/cnf"
"github.com/surrealdb/surrealdb/kvs"
"github.com/surrealdb/surrealdb/sql"
"github.com/surrealdb/surrealdb/util/keys"
2019-11-20 13:20:27 +00:00
)
func (t *TX) AllDB(ctx context.Context, ns string) (out []*sql.DefineDatabaseStatement, err error) {
var kvs []kvs.KV
key := &keys.DB{KV: cnf.Settings.DB.Base, NS: ns, DB: keys.Ignore}
if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil {
return
}
for _, kv := range kvs {
val := &sql.DefineDatabaseStatement{}
val.Decode(kv.Val())
out = append(out, val)
}
return
}
func (t *TX) GetDB(ctx context.Context, ns, db string) (val *sql.DefineDatabaseStatement, err error) {
if out, ok := t.get(_db, db); ok {
return out.(*sql.DefineDatabaseStatement), nil
}
var kv kvs.KV
key := &keys.DB{KV: cnf.Settings.DB.Base, NS: ns, DB: db}
if kv, err = t.Get(ctx, 0, key.Encode()); err != nil {
return nil, err
}
if !kv.Exi() {
return nil, ErrorDBNotFound
}
val = &sql.DefineDatabaseStatement{}
val.Decode(kv.Val())
t.set(_db, db, val)
return
}
func (t *TX) AddDB(ctx context.Context, ns, db string) (val *sql.DefineDatabaseStatement, err error) {
if out, ok := t.get(_db, db); ok {
return out.(*sql.DefineDatabaseStatement), nil
}
if _, err = t.AddNS(ctx, ns); err != nil {
return
}
var kv kvs.KV
key := &keys.DB{KV: cnf.Settings.DB.Base, NS: ns, DB: db}
2019-12-02 23:29:18 +00:00
if kv, err = t.Get(ctx, 0, key.Encode()); err != nil {
return
}
if kv != nil && kv.Exi() {
2019-11-20 13:20:27 +00:00
val = &sql.DefineDatabaseStatement{}
val.Decode(kv.Val())
t.set(_db, db, val)
return
}
val = &sql.DefineDatabaseStatement{Name: sql.NewIdent(db)}
t.PutC(ctx, 0, key.Encode(), val.Encode(), nil)
t.set(_db, db, val)
return
}
func (t *TX) DelDB(ns, db string) {
t.del(_db, db)
}