pgparser

command module
v0.0.0-...-1b6ad0c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2020 License: Apache-2.0 Imports: 12 Imported by: 0

README

pgparser

A SQL Parser for postgres using golang from Cockroachdb

How to use it

1. import the parser pkg
import "github.com/ruiaylin/pgparser"
2. demo

this demo show how to parse a alter statement, and get the main info of it

package main

import (
	"fmt"
	"log"
	"reflect"

	"github.com/ruiaylin/pgparser/ast"
	parser "github.com/ruiaylin/pgparser/parser"
	"github.com/ruiaylin/pgparser/types"
)

func main() {

	fmtStr := ast.NewFmtCtx(ast.FmtSimple)
	defer fmtStr.Close()
	postgres := "alter table ttt.tables add column3 varchar(10);"
	stmts, err := parser.Parse(postgres)
	if err != nil {
		log.Println("err = ", err)
	}
	stmt := stmts[0]
	switch node := stmt.AST.(type) {
	case *ast.AlterTable:
		node.Table.Format(fmtStr)
		// get table information from sql
		fmt.Println("table =  ", fmtStr.String())
		fmtStr.Reset()
		// Format implements the NodeFormatter interface.
		fmtStr.FormatNode(&node.Cmds)
		fmt.Println("sub_command =  ", fmtStr.String())
		fmtStr.Reset()
		for _, cmd := range node.Cmds {
			switch cmdType := cmd.(type) {
			case *ast.AlterTableAddColumn:
				fmt.Println("SUB CMD: ADD_COL")
				cmdType.ColumnDef.Format(fmtStr)
				fmt.Println("Col =  ", fmtStr.String())
				fmtStr.Reset()
				fmt.Println("col = ", cmdType.ColumnDef.Name)
				fmt.Println("col type = ", cmdType.ColumnDef.Type)
				fmt.Println("col full type  = ", cmdType.ColumnDef.Type.SQLString())
				tt := cmdType.ColumnDef.Type
				switch t := tt.(type) {
				case *types.T:
					fmt.Println("types length = ", t.InternalType.Width)
				}
			}
		}
	default:
		fmt.Println("stream: " + reflect.TypeOf(node).String() + " " + node.String() + "\n")
	}

}

The ouput:

table =   ttt.tables
sub_command =    ADD COLUMN column3 VARCHAR(10)
SUB CMD: ADD_COL
Col =   column3 VARCHAR(10)
col =  column3
col type =  varchar
col full type  =  VARCHAR(10)
types length =  10

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
Package oidext contains oids that are not in `github.com/lib/pq/oid` as they are not shipped by default with postgres.
Package oidext contains oids that are not in `github.com/lib/pq/oid` as they are not shipped by default with postgres.
hba
Package hba implements an hba.conf parser.
Package hba implements an hba.conf parser.
pgcode
Package pgcode defines the PostgreSQL 5-character support codes used throughout the CockroachDB source ast.
Package pgcode defines the PostgreSQL 5-character support codes used throughout the CockroachDB source ast.
pgwirebase
Package pgwirebase contains type definitions and very basic protocol structures to be used by both the pgwire package and by others (particularly by the sql package).
Package pgwirebase contains type definitions and very basic protocol structures to be used by both the pgwire package and by others (particularly by the sql package).
securitytest
Package securitytest embeds the TLS test certificates.
Package securitytest embeds the TLS test certificates.
Package settings provides a central registry of runtime editable settings and accompanying helper functions for retrieving their current values.
Package settings provides a central registry of runtime editable settings and accompanying helper functions for retrieving their current values.
Package sqltelemetry contains telemetry counter definitions for various SQL features.
Package sqltelemetry contains telemetry counter definitions for various SQL features.
Package telemetry contains helpers for capturing diagnostics information.
Package telemetry contains helpers for capturing diagnostics information.
lint
Package lint tests Go code for policy and style violations, as well as detecting suspicious constructs that are typically bugs.
Package lint tests Go code for policy and style violations, as well as detecting suspicious constructs that are typically bugs.
lint/passes/descriptormarshal
Package descriptormarshal defines an suite of Analyzers that detects correct setting of timestamps when unmarshaling table descriptors.
Package descriptormarshal defines an suite of Analyzers that detects correct setting of timestamps when unmarshaling table descriptors.
lint/passes/errcmp
Package errcmp defines an Analyzer which checks for usage of errors.Is instead of direct ==/!= comparisons.
Package errcmp defines an Analyzer which checks for usage of errors.Is instead of direct ==/!= comparisons.
lint/passes/hash
Package hash defines an Analyzer that detects correct use of hash.Hash.
Package hash defines an Analyzer that detects correct use of hash.Hash.
lint/passes/nocopy
Package nocopy defines an Analyzer that detects invalid uses of util.NoCopy.
Package nocopy defines an Analyzer that detects invalid uses of util.NoCopy.
lint/passes/returnerrcheck
Package returnerrcheck defines an suite of Analyzers that detects conditionals which check for a non-nil error and then proceed to return a nil error.
Package returnerrcheck defines an suite of Analyzers that detects conditionals which check for a non-nil error and then proceed to return a nil error.
lint/passes/timer
Package timer defines an Analyzer that detects correct use of timeutil.Timer.
Package timer defines an Analyzer that detects correct use of timeutil.Timer.
lint/passes/unconvert
Package unconvert defines an Analyzer that detects unnecessary type conversions.
Package unconvert defines an Analyzer that detects unnecessary type conversions.
reduce
Package reduce implements a reducer core for reducing the size of test failure cases.
Package reduce implements a reducer core for reducing the size of test failure cases.
geo
Package geo contains the base types for spatial data type operations.
Package geo contains the base types for spatial data type operations.
geo/geodist
Package geodist finds distances between two geospatial shapes.
Package geodist finds distances between two geospatial shapes.
geo/geographiclib
Package geographiclib is a wrapper around the GeographicLib library.
Package geographiclib is a wrapper around the GeographicLib library.
geo/geomfn
Package geomfn contains functions that are used for geometry-based builtins.
Package geomfn contains functions that are used for geometry-based builtins.
geo/geoproj
Package geoproj contains functions that interface with the PROJ library.
Package geoproj contains functions that interface with the PROJ library.
geo/geoprojbase
Package geoprojbase is a minimal dependency package that contains basic metadata and data structures for SRIDs and their CRS transformations.
Package geoprojbase is a minimal dependency package that contains basic metadata and data structures for SRIDs and their CRS transformations.
geo/geos
Package geos is a wrapper around the spatial data types between the geo package and the GEOS C library.
Package geos is a wrapper around the spatial data types between the geo package and the GEOS C library.
encoding/csv
Package csv reads and writes comma-separated values (CSV) files.
Package csv reads and writes comma-separated values (CSV) files.
hlc
Package hlc implements the Hybrid Logical Clock outlined in "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases", available online at http://www.cse.buffalo.edu/tech-reports/2014-04.pdf.
Package hlc implements the Hybrid Logical Clock outlined in "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases", available online at http://www.cse.buffalo.edu/tech-reports/2014-04.pdf.
interval
Package interval provides two implementations for an interval tree.
Package interval provides two implementations for an interval tree.
interval/generic
Package generic provides an implementation of a generic immutable interval B-Tree.
Package generic provides an implementation of a generic immutable interval B-Tree.
leaktest
Package leaktest provides tools to detect leaked goroutines in tests.
Package leaktest provides tools to detect leaked goroutines in tests.
log
Package log implements logging.
Package log implements logging.
metric
Package metric provides server metrics (a.k.a.
Package metric provides server metrics (a.k.a.
metric/aggmetric
Package aggmetric provides functionality to create metrics which expose aggregate metrics for internal collection and additionally per-child reporting to prometheus.
Package aggmetric provides functionality to create metrics which expose aggregate metrics for internal collection and additionally per-child reporting to prometheus.
mon
pretty
Package pretty prints documents based on a target line width.
Package pretty prints documents based on a target line width.
syncutil/singleflight
Package singleflight provides a duplicate function call suppression mechanism.
Package singleflight provides a duplicate function call suppression mechanism.
sysutil
Package sysutil is a cross-platform compatibility layer on top of package syscall.
Package sysutil is a cross-platform compatibility layer on top of package syscall.
timeutil/pgdate
Package pgdate contains parsing functions and types for dates and times in a manner that is compatible with PostgreSQL.
Package pgdate contains parsing functions and types for dates and times in a manner that is compatible with PostgreSQL.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL