github.com/blong14/gache@v0.0.0-20240124023949-89416fd8bbfa/cmd/gctl/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"database/sql"
     7  	"fmt"
     8  	"log"
     9  	"os"
    10  	"os/signal"
    11  	"strings"
    12  	"syscall"
    13  	"time"
    14  
    15  	genv "github.com/blong14/gache/internal/env"
    16  	gache "github.com/blong14/gache/sql"
    17  )
    18  
    19  func mustGetDB() *sql.DB {
    20  	db, err := sql.Open("gache", genv.DSN())
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  	if err = db.Ping(); err != nil {
    25  		panic(err)
    26  	}
    27  	return db
    28  }
    29  
    30  func main() {
    31  	sigint := make(chan os.Signal, 1)
    32  	signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    33  
    34  	ctx, cancel := context.WithCancel(context.Background())
    35  
    36  	db := mustGetDB()
    37  	go accept(ctx, db)
    38  
    39  	s := <-sigint
    40  	log.Printf("\nreceived %s signal\n", s)
    41  	if err := db.Close(); err != nil {
    42  		log.Print(err)
    43  	}
    44  	cancel()
    45  	time.Sleep(500 * time.Millisecond)
    46  }
    47  
    48  func accept(ctx context.Context, db *sql.DB) {
    49  	time.Sleep(1 * time.Second)
    50  	fmt.Print("\n% ")
    51  	scanner := bufio.NewScanner(os.Stdin)
    52  	scanner.Split(bufio.ScanLines)
    53  	for scanner.Scan() {
    54  		select {
    55  		case <-ctx.Done():
    56  			return
    57  		default:
    58  		}
    59  		b := strings.Builder{}
    60  		b.Reset()
    61  		start := time.Now()
    62  		var result *gache.QueryResponse
    63  		if err := db.QueryRowContext(ctx, scanner.Text()).Scan(&result); err != nil {
    64  			log.Println(err)
    65  			fmt.Print("\n% ")
    66  			continue
    67  		}
    68  		b.WriteString("%\tkey\t\tvalue\n")
    69  		if result.Success {
    70  			for i, r := range result.RangeValues {
    71  				b.WriteString(fmt.Sprintf("%d.\t%s\t\t%s\n", i, r[0], r[1]))
    72  			}
    73  		}
    74  		b.WriteString(
    75  			fmt.Sprintf("\n[%s] %d rows\n%% ", time.Since(start), result.Stats.Count))
    76  		fmt.Print(b.String())
    77  	}
    78  }