• Stars
    star
    309
  • Rank 135,306 (Top 3 %)
  • Language
    Go
  • License
    MIT License
  • Created about 6 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

yo is a command-line tool to generate Go code for Google Cloud Spanner.

yo

yo is a command-line tool to generate Go code for Google Cloud Spanner, forked from xo 🌹.

yo uses database schema to generate code by using Information Schema. yo runs SQL queries against tables in INFORMATION_SCHEMA to fetch metadata for a database, and applies the metadata to Go templates to generate code/models to access Cloud Spanner.

Please feel free to report issues and send pull requests, but note that this application is not officially supported as part of the Cloud Spanner product.

Installation

$ go get -u go.mercari.io/yo

Quickstart

The following is a quick overview of using yo on the command-line:

# change to project directory
$ cd $GOPATH/src/path/to/project

# make an output directory
$ mkdir -p models

# generate code for a schema
$ yo $SPANNER_PROJECT_NAME $SPANNER_INSTANCE_NAME $SPANNER_DATABASE_NAME -o models

Command line options

The following are yo's command-line arguments and options:

$ yo --help
yo is a command-line tool to generate Go code for Google Cloud Spanner.

Usage:
  yo PROJECT_NAME INSTANCE_NAME DATABASE_NAME [flags]

Examples:
  # Generate models under models directory
  yo $SPANNER_PROJECT_NAME $SPANNER_INSTANCE_NAME $SPANNER_DATABASE_NAME -o models

  # Generate models under models directory with custom types
  yo $SPANNER_PROJECT_NAME $SPANNER_INSTANCE_NAME $SPANNER_DATABASE_NAME -o models --custom-types-file custom_column_types.yml

Flags:
      --custom-type-package string   Go package name to use for custom or unknown types
      --custom-types-file string     custom table field type definition file
  -h, --help                         help for yo
      --ignore-fields stringArray    fields to exclude from the generated Go code types
      --ignore-tables stringArray    tables to exclude from the generated Go code types
      --inflection-rule-file string  custom inflection rule file
  -o, --out string                   output path or file name
  -p, --package string               package name used in generated Go code
      --single-file                  toggle single file output
      --suffix string                output file suffix (default ".yo.go")
      --tags string                  build tags to add to package header
      --template-path string         user supplied template path

Generated code

yo generates 1 file per table by default. Each file has struct, metadata and methods for that table.

struct

From this table definition:

CREATE TABLE Examples (
  PKey STRING(32) NOT NULL,
  Num INT64 NOT NULL,
  CreatedAt TIMESTAMP NOT NULL,
) PRIMARY KEY(PKey);

This struct is generated:

type Example struct {
	PKey      string    `spanner:"PKey" json:"PKey"`           // PKey
	Num       int64     `spanner:"Num" json:"Num"`             // Num
	CreatedAt time.Time `spanner:"CreatedAt" json:"CreatedAt"` // CreatedAt
}

Mutation methods

An operation against a table is represented as mutation in Cloud Spanner. yo generates methods to create mutations to modify a table.

  • Insert
    • A wrapper method of spanner.Insert, which embeds struct values implicitly to insert a new record with struct values.
  • Update
    • A wrapper method of spanner.Update, which embeds struct values implicitly to update all columns into struct values.
  • InsertOrUpdate
    • A wrapper method of spanner.InsertOrUpdate, which embeds struct values implicitly to insert a new record or update all columns to struct values.
  • UpdateColumns
    • A wrapper method of spanner.Update, which updates specified columns into struct values.

Read functions

yo generates functions to read data from Cloud Spanner. The functions are generated based on index.

Naming convention of generated functions is FindXXXByYYY. The XXX is table name and YYY is index name. XXX will be singular if the index is unique index, or plural if the index is not unique.

TODO

  • Generated functions use Query only even if it is secondary index. Need a function to use Read.

Error handling

yo wraps all errors as internal yoError. It has some methods for error handling.

  • GRPCStatus()
    • This returns gRPC's *status.Status. It is intended by used from status google.golang.org/grpc/status package.
  • DBTableName()
    • A table name where the error happens.
  • NotFound()
    • A helper to check the error is NotFound.

The yoError inherits an original error from google-cloud-go. It can still be used with status.FromError or status.Code to check status code of the error. So the typical error handling will be like:

result, err := SomeFunction()
if err != nil {
	code := status.Code(err)
	if code == codes.InvalidArgument {
		// error handling for invalid argument
	}
	...
	panic("unexpected")
}

Templates for code generation

yo uses Go template package to generate code. You can use your own template for code generation by using --template-path option.

yo provides default templates and uses them when --template-path option is not specified. The templates exist in templates directory. The templates are embedded into yo binary.

Custom Template Quickstart

The following is a quick overview of copying the base templates contained in the yo project's templates/ directory, editing to suit, and using with yo:

# change to working project directory
$ cd $GOPATH/src/path/to/my/project

# create a template directory
$ mkdir -p templates

# copy yo templates
$ cp "$GOPATH/src/github.com/cloudspannerecosystem/yo/templates/*" templates/

# remove yo binary data
$ rm templates/*.go

# edit base templates
$ vi templates/*.tpl.go

# use with yo
$ yo $SPANNER_PROJECT_NAME $SPANNER_INSTANCE_NAME $SPANNER_DATABASE_NAME -o models --template-path templates

See the Custom Template example below for more information on adapting the base templates in the yo source tree for use within your own project.

Template files

Template File Description
templates/type.go.tpl Template for schema tables
templates/index.go.tpl Template for schema indexes
templates/yo_db.go.tpl Package level template generated once per package
templates/yo_package.go.tpl File header template generated once per file

Helper functions

This is not a stable feature

yo provides some helper functions which can be used in templates. Those are defined in generator/funcs.go. Those are not well documented and are likely to change.

Custom inflection rule file

yo use inflection to convert singular or plural name each other. If you want to add own rule, add --inflection-rule-file option with rule yaml file. rule yaml file sample is

- singular: person
  plural: people
- singular: live
  plural: lives

See https://github.com/jinzhu/inflection#register-rules for details.

Contributions

Please read the contribution guidelines before submitting pull requests.

License

Copyright 2018 Mercari, Inc.

yo is released under the MIT License.

More Repositories

1

wrench

wrench - Schema management tool for Cloud Spanner -
Go
236
star
2

spanner-cli

Interactive command line tool for Cloud Spanner
Go
229
star
3

autoscaler

Automatically scale the capacity of your Spanner instances based on their utilization.
JavaScript
86
star
4

memefish

memefish is the foundation to analyze Spanner SQL
Go
71
star
5

spanner-dump

Command line tool for exporting a Cloud Spanner database in text format
Go
39
star
6

spanner-schema-diff-tool

Compare two Cloud Spanner Schema (DDL) files, determine the differences and generate the required ALTER statements to convert one schema to the other.
Java
32
star
7

spanner-truncate

spanner-truncate is a tool to delete all rows from the tables in a Cloud Spanner database without deleting tables themselves.
Go
27
star
8

spanner-change-watcher

Cloud Spanner Change Watcher and Publisher - Detects data changes in Cloud Spanner databases
Java
25
star
9

gcsb

Cloud Spanner load generator to load test your application and pre-warm the database before launch
Go
25
star
10

spanner-bench

Google Cloud Spanner Query Planner Benchmarking
Go
24
star
11

spool

A CLI tool to manage Cloud Spanner databases for testing.
Go
24
star
12

spanner-proxy

An easy way to create Google Cloud Spanner proxies.
Go
20
star
13

liquibase-spanner

Java
19
star
14

spanner-change-streams-tail

CLI to tail Cloud Spanner change streams
Go
19
star
15

spanner-gaming-sample

This repository sets up a sample microservice architecture to highlight how Cloud Spanner integrates with other cloud technologies.
Go
18
star
16

pgadapter

A proxy that translates the wire protocol from Postgres to Cloud Spanner.
Java
14
star
17

spanner-benchmarks-tutorial

Hands-on lab/tutorial for generating benchmarks for Google Cloud Spanner
13
star
18

sqltools-cloud-spanner-driver

TypeScript
10
star
19

machmeter

Quickly perform Cloud Spanner POCs using Machmeter.
Java
8
star
20

scheduled-backups

Showing how to use Cloud Scheduler and Cloud Functions to configure a schedule for creating Cloud Spanner backups.
Go
8
star
21

spanner-sqlalchemy-demo

A demo application for Cloud Spanner SQLAlchemy ORM, simple ranking API for gaming use cases.
Python
7
star
22

dynamodb-adapter

Go
6
star
23

omegatrade

Sample application for Spanner written in Node.js.
TypeScript
6
star
24

emulator-samples

Samples for using Cloud Spanner Emulator
C++
5
star
25

website

Static website for cloudspannerecosystem.dev
CSS
5
star
26

sampledb

Quickly get a sample database into Cloud Spanner
Python
5
star
27

spanner-ai

Spanner Integrations with Vertex AI.
Python
4
star
28

spanner-stress-test-demo

Python
3
star
29

spanner-terraform

Google Cloud Spanner with Terraform
3
star
30

cassandra-to-spanner-proxy

Go
2
star
31

spanner-analytics

Python
2
star
32

appengine-java-sample

Sample for using Cloud Spanner from App Engine Java
Java
2
star
33

spanner-table-copy-pipeline

Java
2
star
34

spanner-rest-cmdlets

PowerShell
2
star
35

spanner-terraform-example

Sample terraform templates for Cloud Spanner.
HCL
1
star