-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
686 lines (606 loc) · 18.8 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"github.com/ghetzel/cli"
"github.com/ghetzel/go-stockutil/fileutil"
"github.com/ghetzel/go-stockutil/log"
"github.com/ghetzel/go-stockutil/sliceutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/pivot/v3"
"github.com/ghetzel/pivot/v3/backends"
"github.com/ghetzel/pivot/v3/client"
"github.com/ghetzel/pivot/v3/dal"
"github.com/ghetzel/pivot/v3/filter"
"github.com/ghetzel/pivot/v3/filter/generators"
"github.com/ghetzel/pivot/v3/mapper"
)
func main() {
app := cli.NewApp()
app.Name = pivot.ApplicationName
app.Usage = pivot.ApplicationSummary
app.Version = pivot.ApplicationVersion
app.EnableBashCompletion = true
app.Flags = []cli.Flag{
cli.StringFlag{
Name: `log-level, L`,
Usage: `Level of log output verbosity`,
Value: `info`,
EnvVar: `LOGLEVEL`,
},
cli.StringFlag{
Name: `config, c`,
Usage: `Path to the configuration file to load.`,
Value: `pivot.yml`,
},
cli.BoolFlag{
Name: `log-queries, Q`,
Usage: `Whether to include queries in the logging output`,
},
cli.StringSliceFlag{
Name: `schema, s`,
Usage: `Path to one or more schema files to load`,
},
cli.StringSliceFlag{
Name: `fixtures, F`,
Usage: `Path to one or more data files to load`,
},
cli.BoolTFlag{
Name: `allow-netrc, N`,
Usage: `Allow parsing of a .netrc file.`,
},
cli.StringFlag{
Name: `netrc, n`,
Usage: `Specify the location of the .netrc file to parse.`,
},
cli.BoolFlag{
Name: `autocreate, C`,
Usage: `Whether to automatically create collections defined in schema files that don't already exist in the backend.`,
},
cli.BoolFlag{
Name: `autoexpand, X`,
Usage: `Whether to automatically expand references to embedded collections on records.`,
},
}
app.Before = func(c *cli.Context) error {
log.SetLevelString(c.String(`log-level`))
populateNetrc(c)
return nil
}
app.Commands = []cli.Command{
{
Name: `web`,
Usage: `Start the local REST API and data browser web application.`,
ArgsUsage: `[CONNECTION_STRING [INDEXER_CONNECTION_STRING]]`,
Flags: []cli.Flag{
cli.StringFlag{
Name: `address, a`,
Usage: `The local address the server should listen on.`,
Value: fmt.Sprintf("%s:%d", pivot.DefaultAddress, pivot.DefaultPort),
},
cli.StringFlag{
Name: `ui-dir`,
Usage: `The path to the UI directory`,
Value: pivot.DefaultUiDirectory,
},
},
Action: func(c *cli.Context) {
var backend string
var indexer string
var config pivot.Configuration
if cnf, err := pivot.LoadConfigFile(c.GlobalString(`config`)); err == nil {
config = cnf.ForEnv(os.Getenv(`PIVOT_ENV`))
log.Infof("Loaded configuration file from %v env=%v", c.GlobalString(`config`), os.Getenv(`PIVOT_ENV`))
} else if !os.IsNotExist(err) {
log.Fatalf("Configuration error: %v", err)
}
if v := c.Args().Get(0); v != `` {
backend = v
} else {
backend = config.Backend
}
if v := c.Args().Get(1); v != `` {
indexer = v
} else {
indexer = config.Indexer
}
if c.GlobalIsSet(`autocreate`) {
config.AutocreateCollections = c.GlobalBool(`autocreate`)
}
if c.GlobalIsSet(`autoexpand`) {
config.Autoexpand = c.GlobalBool(`autoexpand`)
}
if backend == `` {
log.Fatalf("Must specify a backend to connect to.")
}
server := pivot.NewServer(backend)
server.Address = c.String(`address`)
server.UiDirectory = c.String(`ui-dir`)
server.ConnectOptions.Indexer = indexer
server.ConnectOptions.AutocreateCollections = config.AutocreateCollections
server.Autoexpand = config.Autoexpand
for _, filename := range c.GlobalStringSlice(`schema`) {
server.AddSchemaDefinition(filename)
}
for _, filename := range c.GlobalStringSlice(`fixtures`) {
server.AddFixturePath(filename)
}
if err := server.ListenAndServe(); err != nil {
log.Fatalf("Failed to start server: %v", err)
os.Exit(3)
}
},
}, {
Name: `diff`,
Usage: `Print the difference between the loaded schema and the given connection.`,
ArgsUsage: `CONNECTION_STRING [COLLECTION ..]`,
Flags: []cli.Flag{},
Action: func(c *cli.Context) {
var backend string
var config pivot.Configuration
if cnf, err := pivot.LoadConfigFile(c.GlobalString(`config`)); err == nil {
config = cnf.ForEnv(os.Getenv(`PIVOT_ENV`))
log.Infof("Loaded configuration file from %v env=%v", c.GlobalString(`config`), os.Getenv(`PIVOT_ENV`))
} else if !os.IsNotExist(err) {
log.Fatalf("Configuration error: %v", err)
}
if cs := c.Args().First(); cs != `` {
backend = cs
} else {
backend = config.Backend
}
config.AutocreateCollections = false
config.Autoexpand = false
if backend == `` {
log.Fatalf("Must specify a backend to connect to.")
}
if db, err := pivot.NewDatabaseWithOptions(backend, pivot.ConnectOptions{}); err == nil {
args := c.Args()
var collections []string
if len(args) > 1 {
collections = args[1:]
} else if all, err := db.ListCollections(); err == nil {
collections = all
} else {
log.Fatalf("failed to retrieve collections: %v", err)
}
if loaded, err := pivot.LoadSchemata(c.GlobalStringSlice(`schema`)...); err == nil {
log.Infof("Checking %d collections against %d schemata", len(collections), len(loaded))
CollectionLoop:
for _, c := range collections {
if actual, err := db.GetCollection(c); err == nil {
var schema *dal.Collection
for _, lc := range loaded {
if lc.Name == actual.Name {
if lc.View {
log.Infof("%s: skipping view", lc.Name)
continue CollectionLoop
}
schema = lc
break
}
}
if schema != nil {
deltas := schema.Diff(actual)
if len(deltas) == 0 {
log.Noticef("%s: up-to-date", actual.Name)
} else {
log.Warningf("%s: %d differences", actual.Name, len(deltas))
for _, delta := range deltas {
log.Warningf("\t%v", delta)
}
}
} else {
log.Warningf("no schema found for database collection %q", actual.Name)
}
} else {
log.Warningf("failed to retrieve collection: %v", err)
}
}
} else {
log.Fatalf("schema: %v", err)
}
} else {
log.Fatalf("connect: %v", err)
}
},
}, {
Name: `copy`,
Usage: `Copies data from one datasource to another`,
ArgsUsage: `SOURCE DESTINATION`,
Flags: []cli.Flag{
cli.StringSliceFlag{
Name: `collection, c`,
Usage: `A specific collection to copy (can be specified multiple times).`,
},
cli.BoolFlag{
Name: `no-schema-check, S`,
Usage: `Skip verifying schema equality.`,
},
},
Action: func(c *cli.Context) {
var source backends.Backend
var destination backends.Backend
if sourceURI := c.Args().Get(0); sourceURI != `` {
if destinationURI := c.Args().Get(1); destinationURI != `` {
if s, err := pivot.NewDatabase(sourceURI); err == nil {
if err := s.Initialize(); err != nil {
log.Fatalf("failed to initialize source: %v", err)
}
if d, err := pivot.NewDatabase(destinationURI); err == nil {
if err := d.Initialize(); err != nil {
log.Fatalf("failed to initialize destination: %v", err)
}
source = s
destination = d
} else {
log.Fatalf("failed to connect to destination: %v", err)
}
} else {
log.Fatalf("failed to connect to source: %v", err)
}
} else {
log.Fatalf("Must specify a destination")
}
} else {
log.Fatalf("Must specify a source")
}
collections := c.StringSlice(`collection`)
if len(collections) == 0 {
if c, err := source.ListCollections(); err == nil {
collections = c
} else {
log.Fatalf("failed to list source collections: %v", err)
}
}
log.Debugf("Copying %d collections", len(collections))
for _, name := range collections {
if collection, err := source.GetCollection(name); err == nil {
if indexer := source.WithSearch(collection); indexer != nil {
var destCollection *dal.Collection
if dc, err := destination.GetCollection(name); err == nil {
destCollection = dc
} else if dal.IsCollectionNotFoundErr(err) {
if err := destination.CreateCollection(collection); err == nil {
destCollection = collection
} else {
log.Errorf("Cannot create destination collection %q: %v", name, err)
continue
}
} else {
log.Errorf("Cannot import to destination collection %q: %v", name, err)
continue
}
if diffs := destCollection.Diff(collection); len(diffs) == 0 || c.Bool(`no-schema-check`) {
sourceItem := mapper.NewModel(source, collection)
var i int
if err := sourceItem.Each(&dal.Record{}, func(ptrToInstance interface{}, err error) {
if newRecord, ok := ptrToInstance.(*dal.Record); ok && err == nil {
if err := destination.Insert(name, dal.NewRecordSet(newRecord)); err == nil {
i += 1
log.Debugf("Copied record %v", newRecord.ID)
} else {
log.Warningf("failed to write record to destination: %v", err)
}
} else if !ok {
log.Warningf("failed to copy record: invalid return type %T", ptrToInstance)
} else {
log.Warningf("failed to copy record %d: %v", i, err)
}
}); err == nil {
log.Noticef("Successfully copied %d records from collection %q", i, name)
} else {
log.Errorf("Failed to copy collection %q: %v", name, err)
}
} else {
log.Errorf("Cannot import to destination collection %q: collections differ", name)
for _, diff := range diffs {
log.Errorf(" %v", diff)
}
}
} else {
log.Errorf("Cannot export source collection %q: collection is not enumerable", name)
}
} else {
log.Errorf("Cannot export source collection %q: %v", name, err)
}
}
},
}, {
Name: `filter`,
Usage: `Converts a given filter into the specified native query`,
ArgsUsage: `COLLECTION GENERATOR[:SUBTYPE] FILTER`,
Action: func(c *cli.Context) {
col := c.Args().Get(0)
gentype, sub := stringutil.SplitPair(c.Args().Get(1), `:`)
flt := c.Args().Get(2)
if f, err := filter.Parse(flt); err == nil {
var gen filter.IGenerator
switch gentype {
case `sql`:
g := generators.NewSqlGenerator()
if mapping, err := generators.GetSqlTypeMapping(sub); err == nil {
g.TypeMapping = mapping
} else {
log.Fatal(err)
}
gen = g
case `mongodb`:
gen = generators.NewMongoDBGenerator()
case `elasticsearch`, `es`:
gen = generators.NewElasticsearchGenerator()
default:
log.Fatalf("Unrecognized query generator %q", gentype)
}
if data, err := filter.Render(gen, col, f); err == nil {
fmt.Println(string(data))
} else {
log.Fatalf("error generating query: %v", err)
}
} else {
log.Fatalf("invalid filter: %v", err)
}
},
}, {
Name: `client`,
Usage: `Provides an HTTP API client for interacting with a running Pivot instance.`,
Flags: []cli.Flag{
cli.StringFlag{
Name: `url, u`,
Usage: `The Pivot API URL to connect to.`,
EnvVar: `PIVOT_URL`,
Value: client.DefaultPivotUrl,
},
cli.StringFlag{
Name: `format, f`,
Usage: `How to format API result output. (one of: text, json, yaml)`,
},
cli.BoolFlag{
Name: `pretty, P`,
Usage: `Pretty-print the formatted output (indenting where applicable)`,
},
},
Subcommands: cli.Commands{
{
Name: `status`,
Usage: `Retrieve status info from Pivot.`,
Action: func(c *cli.Context) {
if status, err := pivotClient(c).Status(); err == nil {
output(c, status, func() error {
fmt.Printf(
"%v %v: backend=%v indexer=%v\n",
status.Application,
status.Version,
status.Backend,
status.Indexer,
)
return nil
})
} else {
log.Fatal(err)
}
},
}, {
Name: `collections`,
Usage: `Return a list of collection names or details on a specific collection.`,
ArgsUsage: `[NAME]`,
Action: func(c *cli.Context) {
if specific := c.Args(); len(specific) == 0 {
if names, err := pivotClient(c).Collections(); err == nil {
output(c, names, func() error {
if len(names) > 0 {
fmt.Println(strings.Join(names, "\n"))
}
return nil
})
} else {
log.Fatal(err)
}
} else {
for _, name := range specific {
if collection, err := pivotClient(c).Collection(name); err == nil {
output(c, collection, nil)
} else {
log.Fatal(err)
}
}
}
},
}, {
Name: `records`,
Usage: `Retrieve (or create, update) records from a specific collection. ` +
`If data is read from standard input, it will be inserted/updated into the ` +
`collection specified in the Record's "collection" field, falling back to ` +
`the collection specified in the first positional argument after this subcommand.`,
ArgsUsage: `[COLLECTION [ID ..]]`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: `warn-errors, w`,
Usage: `Errors creating/updating records will only produce warnings instead of exiting the program.`,
},
},
Action: func(c *cli.Context) {
pc := pivotClient(c)
collection := c.Args().First()
ids := make([]string, 0)
if args := c.Args(); len(args) > 1 {
ids = args[1:]
}
// if stdin is not a terminal (e.g.: something is being piped into the command)
// then read and parse lines as JSON dal.Records
if !fileutil.IsTerminal() {
lines := bufio.NewScanner(os.Stdin)
for lines.Scan() {
line := strings.TrimSpace(lines.Text())
if line == `` || strings.HasPrefix(line, `#`) {
continue
}
var record dal.Record
if err := json.Unmarshal([]byte(line), &record); err == nil {
if record.CollectionName != `` {
collection = record.CollectionName
}
if collection == `` {
logerr(c, "No collection specified in record or on command line")
}
if record.Operation == `` {
if record.ID == nil {
record.Operation = `create`
} else {
record.Operation = `update`
}
}
switch record.Operation {
case `create`:
_, err = pc.CreateRecord(collection, &record)
case `update`:
_, err = pc.UpdateRecord(collection, &record)
case `delete`:
err = pc.DeleteRecords(collection, record.ID)
default:
logerr(c, "Unknown record operation %q", record.Operation)
}
} else {
logerr(c, "malformed input: %v", err)
}
}
if err := lines.Err(); err != nil {
logerr(c, "error reading input: %v", err)
}
}
if len(ids) > 0 {
if collection == `` {
log.Fatalf("Must specify a collection to retrieve records from.")
}
// read any records explicitly requested in positional arguments
// this can be cleverly used as a readback for records just written via stdin
for _, id := range ids {
if record, err := pc.GetRecord(collection, id); err == nil {
output(c, record, nil)
} else {
logerr(c, "retrieve error: %v", err)
}
}
}
},
}, {
Name: `query`,
Usage: `Query a collection and output the results.`,
ArgsUsage: `COLLECTION [FILTERS ..]`,
Flags: []cli.Flag{
cli.IntFlag{
Name: `limit, l`,
Usage: `Limit the number of records to return in one query`,
},
cli.IntFlag{
Name: `offset, o`,
Usage: `The record offset to apply to the query (for retrieving paginated results)`,
},
cli.StringFlag{
Name: `sort, s`,
Usage: `A comma-separated list of fields to sort the results by (in order of priority)`,
},
cli.StringFlag{
Name: `fields, f`,
Usage: `A comma-separated list of fields to include in the resulting records.`,
},
cli.BoolFlag{
Name: `autopage, P`,
Usage: `Automatically paginate through results, performing the query`,
},
},
Action: func(c *cli.Context) {
if collection := c.Args().First(); collection != `` {
filters := make([]string, 0)
offset := c.Int(`offset`)
fSort := sliceutil.CompactString(strings.Split(c.String(`sort`), `,`))
fFields := sliceutil.CompactString(strings.Split(c.String(`fields`), `,`))
if args := c.Args(); len(args) > 1 {
filters = args[1:]
}
for {
if results, err := pivotClient(c).Query(collection, filters, &client.QueryOptions{
Limit: c.Int(`limit`),
Offset: offset,
Sort: fSort,
Fields: fFields,
}); err == nil {
for _, record := range results.Records {
output(c, record.Map(fFields...), nil)
}
if len(results.Records) == 0 {
return
} else if !c.Bool(`autopage`) {
return
}
offset += len(results.Records)
} else {
log.Fatal(err)
return
}
}
} else {
log.Fatalf("Must specify a collection to query.")
}
},
},
},
},
}
app.Run(os.Args)
}
func logerr(c *cli.Context, format string, args ...interface{}) {
if c.Bool(`warn-errors`) {
log.Warningf(format, args...)
} else {
log.Fatalf(format, args...)
}
}
func pivotClient(c *cli.Context) *client.Pivot {
if c, err := client.New(c.String(`url`)); err == nil {
return c
} else {
log.Fatalf("client error: %v", err)
return nil
}
}
func output(c *cli.Context, value interface{}, textFn func() error) error {
format := c.String(`format`)
var err error
if textFn == nil {
format = `json`
}
switch format {
case `json`:
enc := json.NewEncoder(os.Stdout)
if c.Bool(`pretty`) {
enc.SetIndent(``, ` `)
}
err = enc.Encode(value)
default:
if textFn != nil {
err = textFn()
}
}
return err
}
func populateNetrc(c *cli.Context) {
if netrc := c.String(`netrc`); c.Bool(`allow-netrc`) {
if netrc == `` {
if usr, err := user.Current(); err == nil {
pivot.NetrcFile = filepath.Join(usr.HomeDir, ".netrc")
} else {
log.Fatalf("netrc err: %v", err)
}
} else {
pivot.NetrcFile = netrc
}
} else {
pivot.NetrcFile = ``
}
}