1/*
2 * blob.go
3 *
4 * This source file is part of the FoundationDB open source project
5 *
6 * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *     http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21package main
22
23import (
24	"fmt"
25	"github.com/apple/foundationdb/bindings/go/src/fdb"
26	"github.com/apple/foundationdb/bindings/go/src/fdb/directory"
27	"github.com/apple/foundationdb/bindings/go/src/fdb/subspace"
28	"github.com/apple/foundationdb/bindings/go/src/fdb/tuple"
29)
30
31const CHUNK_SIZE int = 5
32
33func write_blob(t fdb.Transactor, blob_subspace subspace.Subspace, blob []byte) (err error) {
34
35	_, err = t.Transact(func(tr fdb.Transaction) (interface{}, error) {
36
37		if len(blob) == 0 {
38			return nil, nil
39		}
40
41		for i := 0; i < len(blob); i += CHUNK_SIZE {
42			if i+CHUNK_SIZE <= len(blob) {
43				tr.Set(blob_subspace.Pack(tuple.Tuple{i}), blob[i:i+CHUNK_SIZE])
44			} else {
45				tr.Set(blob_subspace.Pack(tuple.Tuple{i}), blob[i:])
46			}
47		}
48		return nil, nil
49	})
50	return
51}
52
53func read_blob(t fdb.ReadTransactor, blob_subspace subspace.Subspace) ([]byte, error) {
54
55	blb, err := t.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
56
57		var blob []byte
58
59		ri := rtr.GetRange(blob_subspace, fdb.RangeOptions{}).Iterator()
60
61		for ri.Advance() {
62
63			kv := ri.MustGet()
64
65			blob = append(blob, rtr.Get(kv.Key).MustGet()...)
66
67		}
68
69		return blob, nil
70	})
71
72	if err != nil {
73
74		return nil, err
75	}
76
77	return blb.([]byte), nil
78}
79
80func main() {
81	fdb.MustAPIVersion(610)
82
83	db := fdb.MustOpenDefault()
84
85	blobdir, err := directory.CreateOrOpen(db, []string{"blobdir"}, nil)
86
87	if err != nil {
88		fmt.Println(err)
89	}
90
91	blobspace := blobdir.Sub("blob")
92
93	test := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
94
95	write_blob(db, blobspace, test)
96
97	ret, e := read_blob(db, blobspace)
98
99	if e == nil {
100		fmt.Println(string(ret))
101	}
102}
103