feat: improve pgsql grammar and add unit tests(#201)

* feat(pgsql: upgrade keywords and refresh them to parser file): pgsql

* feat(pgsql: check create table's syntax): pgsql

* feat(pgsql: check and update drop syntax): pgsql: check and update drop syntax

* feat: pgsql: check create's sql syntax and update g4 file

* feat: pgsql:complete other's sql and syntax except select, insert, drop

* feat: pgsql: update create, delete, insert, select, update and others' syntax

* test: pgsql: update alter's sql

* feat: pgsql: update syntax g4 file

* feat: pgsql: upgrade keywords to without '_P' in lexer and parser file

* docs: pgsql: update copyright and Reference of parser and lexer

---------

Co-authored-by: zhaoge <>
This commit is contained in:
XCynthia 2023-11-09 11:53:40 +08:00 committed by GitHub
parent 1927a70f23
commit 2e6d18e7dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 49877 additions and 47875 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,67 +0,0 @@
import { Lexer } from "antlr4ts/Lexer";
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
export default abstract class PostgreSQLLexerBase extends Lexer {
tags: string[] = [];
_interp: any;
constructor(input) {
super(input);
}
pushTag() {
this.tags.push(this.text);
}
isTag() {
return this.text === this.tags[this.tags.length - 1];
}
popTag() {
this.tags.pop();
}
getInputStream() {
return this._input;
}
checkLA( c) {
return this.getInputStream().LA(1) !== c;
}
charIsLetter() {
return isLetter(this.getInputStream().LA(-1));
}
HandleNumericFail() {
this.getInputStream().seek(this.getInputStream().index - 2);
const Integral = 535;
this.type = Integral;
}
HandleLessLessGreaterGreater() {
const LESS_LESS = 18;
const GREATER_GREATER = 19;
if (this.text === '<<') this.type = LESS_LESS;
if (this.text === '>>') this.type = GREATER_GREATER;
}
UnterminatedBlockCommentDebugAssert() {
}
CheckIfUtf32Letter() {
let codePoint = this.getInputStream().LA(-2) << 8 + this.getInputStream().LA(-1);
let c;
if (codePoint < 0x10000) {
c = String.fromCharCode(codePoint);
} else {
codePoint -= 0x10000;
c = String.fromCharCode(codePoint / 0x400 + 0xd800, codePoint % 0x400 + 0xdc00);
}
return isLetter(c[0]);
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,97 +0,0 @@
import { CharStreams, CommonTokenStream, Parser } from 'antlr4ts';
import { PostgreSQLLexer } from './PostgreSQLLexer';
import { PostgreSQLParser } from './PostgreSQLParser';
export default abstract class PostgreSQLParserBase extends Parser {
constructor( input) {
super(input);
}
GetParsedSqlTree( script, line) {
const ph = this.getPostgreSQLParser(script);
return ph.program();
}
ParseRoutineBody( _localctx) {
let lang = null;
for (let _i = 0, _a = _localctx.createfunc_opt_item(); _i < _a.length; _i++) {
const coi = _a[_i];
if (!!coi.LANGUAGE()) {
if (!!coi.nonreservedword_or_sconst()) {
if (!!coi.nonreservedword_or_sconst().nonreservedword()) {
if (!!coi.nonreservedword_or_sconst().nonreservedword().identifier()) {
if (!!coi.nonreservedword_or_sconst().nonreservedword().identifier().Identifier()) {
lang = coi.nonreservedword_or_sconst().nonreservedword().identifier().Identifier().getText();
break;
}
}
}
}
}
}
if (!lang) return;
let func_as = null;
for (const a of _localctx.createfunc_opt_item()) {
if (!a.func_as()) {
func_as = a;
break;
}
}
if (!func_as) {
const txt = this.GetRoutineBodyString(func_as.func_as().sconst(0));
const line = func_as.func_as().sconst(0).start.getLine();
const ph = this.getPostgreSQLParser(txt);
switch (lang) {
case 'plpgsql':
func_as.func_as().Definition = ph.plsqlroot();
break;
case 'sql':
func_as.func_as().Definition = ph.program();
break;
}
}
}
TrimQuotes( s) {
return (!s) ? s : s.substring(1, s.length() - 1);
}
unquote( s) {
const slength = s.length();
let r = '';
let i = 0;
while (i < slength) {
const c = s.charAt(i);
r = r.concat(c);
if (c === '\'' && i < slength - 1 && (s.charAt(i + 1) === '\'')) i++;
i++;
}
return r.toString();
}
GetRoutineBodyString( rule) {
const anysconst = rule.anysconst();
const StringConstant = anysconst.StringConstant();
if (null !== StringConstant) return this.unquote(this.TrimQuotes(StringConstant.getText()));
const UnicodeEscapeStringConstant = anysconst.UnicodeEscapeStringConstant();
if (null !== UnicodeEscapeStringConstant) return this.TrimQuotes(UnicodeEscapeStringConstant.getText());
const EscapeStringConstant = anysconst.EscapeStringConstant();
if (null !== EscapeStringConstant) return this.TrimQuotes(EscapeStringConstant.getText());
let result = '';
const dollartext = anysconst.DollarText();
for (const s of dollartext) {
result += s.getText();
}
return result;
}
getPostgreSQLParser( script) {
const charStream = CharStreams.fromString(script);
const lexer = new PostgreSQLLexer(charStream);
const tokens = new CommonTokenStream(lexer);
const parser = new PostgreSQLParser(tokens);
// lexer.removeErrorListeners();
// parser.removeErrorListeners();
return parser;
}
}

View File

@ -1,7 +1,4 @@
// Generated from /Users/ziv/github.com/dt-sql-parser/src/grammar/pgsql/PostgreSQLParser.g4 by ANTLR 4.9.0-SNAPSHOT // Generated from /Users/xuxiaoqi/Documents/work/daishu-code/dt-sql-parser/src/grammar/pgsql/PostgreSQLParser.g4 by ANTLR 4.9.0-SNAPSHOT
import PostgreSQLParserBase from "./PostgreSQLParserBase";
import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener";
@ -103,6 +100,7 @@ import { Copy_generic_opt_arg_listContext } from "./PostgreSQLParser";
import { Copy_generic_opt_arg_list_itemContext } from "./PostgreSQLParser"; import { Copy_generic_opt_arg_list_itemContext } from "./PostgreSQLParser";
import { CreatestmtContext } from "./PostgreSQLParser"; import { CreatestmtContext } from "./PostgreSQLParser";
import { OpttempContext } from "./PostgreSQLParser"; import { OpttempContext } from "./PostgreSQLParser";
import { Table_column_listContext } from "./PostgreSQLParser";
import { OpttableelementlistContext } from "./PostgreSQLParser"; import { OpttableelementlistContext } from "./PostgreSQLParser";
import { OpttypedtableelementlistContext } from "./PostgreSQLParser"; import { OpttypedtableelementlistContext } from "./PostgreSQLParser";
import { TableelementlistContext } from "./PostgreSQLParser"; import { TableelementlistContext } from "./PostgreSQLParser";
@ -115,7 +113,8 @@ import { ColquallistContext } from "./PostgreSQLParser";
import { ColconstraintContext } from "./PostgreSQLParser"; import { ColconstraintContext } from "./PostgreSQLParser";
import { ColconstraintelemContext } from "./PostgreSQLParser"; import { ColconstraintelemContext } from "./PostgreSQLParser";
import { Generated_whenContext } from "./PostgreSQLParser"; import { Generated_whenContext } from "./PostgreSQLParser";
import { ConstraintattrContext } from "./PostgreSQLParser"; import { Deferrable_triggerContext } from "./PostgreSQLParser";
import { Initially_triggerContext } from "./PostgreSQLParser";
import { TablelikeclauseContext } from "./PostgreSQLParser"; import { TablelikeclauseContext } from "./PostgreSQLParser";
import { TablelikeoptionlistContext } from "./PostgreSQLParser"; import { TablelikeoptionlistContext } from "./PostgreSQLParser";
import { TablelikeoptionContext } from "./PostgreSQLParser"; import { TablelikeoptionContext } from "./PostgreSQLParser";
@ -219,6 +218,8 @@ import { CreateamstmtContext } from "./PostgreSQLParser";
import { Am_typeContext } from "./PostgreSQLParser"; import { Am_typeContext } from "./PostgreSQLParser";
import { CreatetrigstmtContext } from "./PostgreSQLParser"; import { CreatetrigstmtContext } from "./PostgreSQLParser";
import { TriggeractiontimeContext } from "./PostgreSQLParser"; import { TriggeractiontimeContext } from "./PostgreSQLParser";
import { ForeachrowContext } from "./PostgreSQLParser";
import { RoworstatmentContext } from "./PostgreSQLParser";
import { TriggereventsContext } from "./PostgreSQLParser"; import { TriggereventsContext } from "./PostgreSQLParser";
import { TriggeroneeventContext } from "./PostgreSQLParser"; import { TriggeroneeventContext } from "./PostgreSQLParser";
import { TriggerreferencingContext } from "./PostgreSQLParser"; import { TriggerreferencingContext } from "./PostgreSQLParser";
@ -294,6 +295,8 @@ import { Opt_from_inContext } from "./PostgreSQLParser";
import { GrantstmtContext } from "./PostgreSQLParser"; import { GrantstmtContext } from "./PostgreSQLParser";
import { RevokestmtContext } from "./PostgreSQLParser"; import { RevokestmtContext } from "./PostgreSQLParser";
import { PrivilegesContext } from "./PostgreSQLParser"; import { PrivilegesContext } from "./PostgreSQLParser";
import { BeforeprivilegeselectlistContext } from "./PostgreSQLParser";
import { BeforeprivilegeselectContext } from "./PostgreSQLParser";
import { Privilege_listContext } from "./PostgreSQLParser"; import { Privilege_listContext } from "./PostgreSQLParser";
import { PrivilegeContext } from "./PostgreSQLParser"; import { PrivilegeContext } from "./PostgreSQLParser";
import { Privilege_targetContext } from "./PostgreSQLParser"; import { Privilege_targetContext } from "./PostgreSQLParser";
@ -324,6 +327,7 @@ import { Opt_classContext } from "./PostgreSQLParser";
import { Opt_asc_descContext } from "./PostgreSQLParser"; import { Opt_asc_descContext } from "./PostgreSQLParser";
import { Opt_nulls_orderContext } from "./PostgreSQLParser"; import { Opt_nulls_orderContext } from "./PostgreSQLParser";
import { CreatefunctionstmtContext } from "./PostgreSQLParser"; import { CreatefunctionstmtContext } from "./PostgreSQLParser";
import { AttrilistContext } from "./PostgreSQLParser";
import { Opt_or_replaceContext } from "./PostgreSQLParser"; import { Opt_or_replaceContext } from "./PostgreSQLParser";
import { Func_argsContext } from "./PostgreSQLParser"; import { Func_argsContext } from "./PostgreSQLParser";
import { Func_args_listContext } from "./PostgreSQLParser"; import { Func_args_listContext } from "./PostgreSQLParser";
@ -677,6 +681,7 @@ import { Opt_target_listContext } from "./PostgreSQLParser";
import { Target_listContext } from "./PostgreSQLParser"; import { Target_listContext } from "./PostgreSQLParser";
import { Target_elContext } from "./PostgreSQLParser"; import { Target_elContext } from "./PostgreSQLParser";
import { Qualified_name_listContext } from "./PostgreSQLParser"; import { Qualified_name_listContext } from "./PostgreSQLParser";
import { Table_qualified_nameContext } from "./PostgreSQLParser";
import { Qualified_nameContext } from "./PostgreSQLParser"; import { Qualified_nameContext } from "./PostgreSQLParser";
import { Name_listContext } from "./PostgreSQLParser"; import { Name_listContext } from "./PostgreSQLParser";
import { NameContext } from "./PostgreSQLParser"; import { NameContext } from "./PostgreSQLParser";
@ -692,10 +697,15 @@ import { SconstContext } from "./PostgreSQLParser";
import { AnysconstContext } from "./PostgreSQLParser"; import { AnysconstContext } from "./PostgreSQLParser";
import { Opt_uescapeContext } from "./PostgreSQLParser"; import { Opt_uescapeContext } from "./PostgreSQLParser";
import { SignediconstContext } from "./PostgreSQLParser"; import { SignediconstContext } from "./PostgreSQLParser";
import { GroupnameContext } from "./PostgreSQLParser";
import { RoleidContext } from "./PostgreSQLParser"; import { RoleidContext } from "./PostgreSQLParser";
import { RolespecContext } from "./PostgreSQLParser"; import { RolespecContext } from "./PostgreSQLParser";
import { Role_listContext } from "./PostgreSQLParser"; import { Role_listContext } from "./PostgreSQLParser";
import { ColidContext } from "./PostgreSQLParser"; import { ColidContext } from "./PostgreSQLParser";
import { Index_method_choicesContext } from "./PostgreSQLParser";
import { Exclude_elementContext } from "./PostgreSQLParser";
import { Index_paramentersContext } from "./PostgreSQLParser";
import { WherePredicateContext } from "./PostgreSQLParser";
import { Type_function_nameContext } from "./PostgreSQLParser"; import { Type_function_nameContext } from "./PostgreSQLParser";
import { NonreservedwordContext } from "./PostgreSQLParser"; import { NonreservedwordContext } from "./PostgreSQLParser";
import { CollabelContext } from "./PostgreSQLParser"; import { CollabelContext } from "./PostgreSQLParser";
@ -1913,6 +1923,17 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitOpttemp?: (ctx: OpttempContext) => void; exitOpttemp?: (ctx: OpttempContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.table_column_list`.
* @param ctx the parse tree
*/
enterTable_column_list?: (ctx: Table_column_listContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.table_column_list`.
* @param ctx the parse tree
*/
exitTable_column_list?: (ctx: Table_column_listContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.opttableelementlist`. * Enter a parse tree produced by `PostgreSQLParser.opttableelementlist`.
* @param ctx the parse tree * @param ctx the parse tree
@ -2046,15 +2067,26 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
exitGenerated_when?: (ctx: Generated_whenContext) => void; exitGenerated_when?: (ctx: Generated_whenContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.constraintattr`. * Enter a parse tree produced by `PostgreSQLParser.deferrable_trigger`.
* @param ctx the parse tree * @param ctx the parse tree
*/ */
enterConstraintattr?: (ctx: ConstraintattrContext) => void; enterDeferrable_trigger?: (ctx: Deferrable_triggerContext) => void;
/** /**
* Exit a parse tree produced by `PostgreSQLParser.constraintattr`. * Exit a parse tree produced by `PostgreSQLParser.deferrable_trigger`.
* @param ctx the parse tree * @param ctx the parse tree
*/ */
exitConstraintattr?: (ctx: ConstraintattrContext) => void; exitDeferrable_trigger?: (ctx: Deferrable_triggerContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.initially_trigger`.
* @param ctx the parse tree
*/
enterInitially_trigger?: (ctx: Initially_triggerContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.initially_trigger`.
* @param ctx the parse tree
*/
exitInitially_trigger?: (ctx: Initially_triggerContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.tablelikeclause`. * Enter a parse tree produced by `PostgreSQLParser.tablelikeclause`.
@ -3189,6 +3221,28 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitTriggeractiontime?: (ctx: TriggeractiontimeContext) => void; exitTriggeractiontime?: (ctx: TriggeractiontimeContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.foreachrow`.
* @param ctx the parse tree
*/
enterForeachrow?: (ctx: ForeachrowContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.foreachrow`.
* @param ctx the parse tree
*/
exitForeachrow?: (ctx: ForeachrowContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.roworstatment`.
* @param ctx the parse tree
*/
enterRoworstatment?: (ctx: RoworstatmentContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.roworstatment`.
* @param ctx the parse tree
*/
exitRoworstatment?: (ctx: RoworstatmentContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.triggerevents`. * Enter a parse tree produced by `PostgreSQLParser.triggerevents`.
* @param ctx the parse tree * @param ctx the parse tree
@ -4014,6 +4068,28 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitPrivileges?: (ctx: PrivilegesContext) => void; exitPrivileges?: (ctx: PrivilegesContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.beforeprivilegeselectlist`.
* @param ctx the parse tree
*/
enterBeforeprivilegeselectlist?: (ctx: BeforeprivilegeselectlistContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.beforeprivilegeselectlist`.
* @param ctx the parse tree
*/
exitBeforeprivilegeselectlist?: (ctx: BeforeprivilegeselectlistContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.beforeprivilegeselect`.
* @param ctx the parse tree
*/
enterBeforeprivilegeselect?: (ctx: BeforeprivilegeselectContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.beforeprivilegeselect`.
* @param ctx the parse tree
*/
exitBeforeprivilegeselect?: (ctx: BeforeprivilegeselectContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.privilege_list`. * Enter a parse tree produced by `PostgreSQLParser.privilege_list`.
* @param ctx the parse tree * @param ctx the parse tree
@ -4344,6 +4420,17 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitCreatefunctionstmt?: (ctx: CreatefunctionstmtContext) => void; exitCreatefunctionstmt?: (ctx: CreatefunctionstmtContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.attrilist`.
* @param ctx the parse tree
*/
enterAttrilist?: (ctx: AttrilistContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.attrilist`.
* @param ctx the parse tree
*/
exitAttrilist?: (ctx: AttrilistContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.opt_or_replace`. * Enter a parse tree produced by `PostgreSQLParser.opt_or_replace`.
* @param ctx the parse tree * @param ctx the parse tree
@ -8227,6 +8314,17 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitQualified_name_list?: (ctx: Qualified_name_listContext) => void; exitQualified_name_list?: (ctx: Qualified_name_listContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.table_qualified_name`.
* @param ctx the parse tree
*/
enterTable_qualified_name?: (ctx: Table_qualified_nameContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.table_qualified_name`.
* @param ctx the parse tree
*/
exitTable_qualified_name?: (ctx: Table_qualified_nameContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.qualified_name`. * Enter a parse tree produced by `PostgreSQLParser.qualified_name`.
* @param ctx the parse tree * @param ctx the parse tree
@ -8392,6 +8490,17 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitSignediconst?: (ctx: SignediconstContext) => void; exitSignediconst?: (ctx: SignediconstContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.groupname`.
* @param ctx the parse tree
*/
enterGroupname?: (ctx: GroupnameContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.groupname`.
* @param ctx the parse tree
*/
exitGroupname?: (ctx: GroupnameContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.roleid`. * Enter a parse tree produced by `PostgreSQLParser.roleid`.
* @param ctx the parse tree * @param ctx the parse tree
@ -8436,6 +8545,50 @@ export interface PostgreSQLParserListener extends ParseTreeListener {
*/ */
exitColid?: (ctx: ColidContext) => void; exitColid?: (ctx: ColidContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.index_method_choices`.
* @param ctx the parse tree
*/
enterIndex_method_choices?: (ctx: Index_method_choicesContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.index_method_choices`.
* @param ctx the parse tree
*/
exitIndex_method_choices?: (ctx: Index_method_choicesContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.exclude_element`.
* @param ctx the parse tree
*/
enterExclude_element?: (ctx: Exclude_elementContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.exclude_element`.
* @param ctx the parse tree
*/
exitExclude_element?: (ctx: Exclude_elementContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.index_paramenters`.
* @param ctx the parse tree
*/
enterIndex_paramenters?: (ctx: Index_paramentersContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.index_paramenters`.
* @param ctx the parse tree
*/
exitIndex_paramenters?: (ctx: Index_paramentersContext) => void;
/**
* Enter a parse tree produced by `PostgreSQLParser.wherePredicate`.
* @param ctx the parse tree
*/
enterWherePredicate?: (ctx: WherePredicateContext) => void;
/**
* Exit a parse tree produced by `PostgreSQLParser.wherePredicate`.
* @param ctx the parse tree
*/
exitWherePredicate?: (ctx: WherePredicateContext) => void;
/** /**
* Enter a parse tree produced by `PostgreSQLParser.type_function_name`. * Enter a parse tree produced by `PostgreSQLParser.type_function_name`.
* @param ctx the parse tree * @param ctx the parse tree

View File

@ -1,7 +1,4 @@
// Generated from /Users/ziv/github.com/dt-sql-parser/src/grammar/pgsql/PostgreSQLParser.g4 by ANTLR 4.9.0-SNAPSHOT // Generated from /Users/xuxiaoqi/Documents/work/daishu-code/dt-sql-parser/src/grammar/pgsql/PostgreSQLParser.g4 by ANTLR 4.9.0-SNAPSHOT
import PostgreSQLParserBase from "./PostgreSQLParserBase";
import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor"; import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor";
@ -103,6 +100,7 @@ import { Copy_generic_opt_arg_listContext } from "./PostgreSQLParser";
import { Copy_generic_opt_arg_list_itemContext } from "./PostgreSQLParser"; import { Copy_generic_opt_arg_list_itemContext } from "./PostgreSQLParser";
import { CreatestmtContext } from "./PostgreSQLParser"; import { CreatestmtContext } from "./PostgreSQLParser";
import { OpttempContext } from "./PostgreSQLParser"; import { OpttempContext } from "./PostgreSQLParser";
import { Table_column_listContext } from "./PostgreSQLParser";
import { OpttableelementlistContext } from "./PostgreSQLParser"; import { OpttableelementlistContext } from "./PostgreSQLParser";
import { OpttypedtableelementlistContext } from "./PostgreSQLParser"; import { OpttypedtableelementlistContext } from "./PostgreSQLParser";
import { TableelementlistContext } from "./PostgreSQLParser"; import { TableelementlistContext } from "./PostgreSQLParser";
@ -115,7 +113,8 @@ import { ColquallistContext } from "./PostgreSQLParser";
import { ColconstraintContext } from "./PostgreSQLParser"; import { ColconstraintContext } from "./PostgreSQLParser";
import { ColconstraintelemContext } from "./PostgreSQLParser"; import { ColconstraintelemContext } from "./PostgreSQLParser";
import { Generated_whenContext } from "./PostgreSQLParser"; import { Generated_whenContext } from "./PostgreSQLParser";
import { ConstraintattrContext } from "./PostgreSQLParser"; import { Deferrable_triggerContext } from "./PostgreSQLParser";
import { Initially_triggerContext } from "./PostgreSQLParser";
import { TablelikeclauseContext } from "./PostgreSQLParser"; import { TablelikeclauseContext } from "./PostgreSQLParser";
import { TablelikeoptionlistContext } from "./PostgreSQLParser"; import { TablelikeoptionlistContext } from "./PostgreSQLParser";
import { TablelikeoptionContext } from "./PostgreSQLParser"; import { TablelikeoptionContext } from "./PostgreSQLParser";
@ -219,6 +218,8 @@ import { CreateamstmtContext } from "./PostgreSQLParser";
import { Am_typeContext } from "./PostgreSQLParser"; import { Am_typeContext } from "./PostgreSQLParser";
import { CreatetrigstmtContext } from "./PostgreSQLParser"; import { CreatetrigstmtContext } from "./PostgreSQLParser";
import { TriggeractiontimeContext } from "./PostgreSQLParser"; import { TriggeractiontimeContext } from "./PostgreSQLParser";
import { ForeachrowContext } from "./PostgreSQLParser";
import { RoworstatmentContext } from "./PostgreSQLParser";
import { TriggereventsContext } from "./PostgreSQLParser"; import { TriggereventsContext } from "./PostgreSQLParser";
import { TriggeroneeventContext } from "./PostgreSQLParser"; import { TriggeroneeventContext } from "./PostgreSQLParser";
import { TriggerreferencingContext } from "./PostgreSQLParser"; import { TriggerreferencingContext } from "./PostgreSQLParser";
@ -294,6 +295,8 @@ import { Opt_from_inContext } from "./PostgreSQLParser";
import { GrantstmtContext } from "./PostgreSQLParser"; import { GrantstmtContext } from "./PostgreSQLParser";
import { RevokestmtContext } from "./PostgreSQLParser"; import { RevokestmtContext } from "./PostgreSQLParser";
import { PrivilegesContext } from "./PostgreSQLParser"; import { PrivilegesContext } from "./PostgreSQLParser";
import { BeforeprivilegeselectlistContext } from "./PostgreSQLParser";
import { BeforeprivilegeselectContext } from "./PostgreSQLParser";
import { Privilege_listContext } from "./PostgreSQLParser"; import { Privilege_listContext } from "./PostgreSQLParser";
import { PrivilegeContext } from "./PostgreSQLParser"; import { PrivilegeContext } from "./PostgreSQLParser";
import { Privilege_targetContext } from "./PostgreSQLParser"; import { Privilege_targetContext } from "./PostgreSQLParser";
@ -324,6 +327,7 @@ import { Opt_classContext } from "./PostgreSQLParser";
import { Opt_asc_descContext } from "./PostgreSQLParser"; import { Opt_asc_descContext } from "./PostgreSQLParser";
import { Opt_nulls_orderContext } from "./PostgreSQLParser"; import { Opt_nulls_orderContext } from "./PostgreSQLParser";
import { CreatefunctionstmtContext } from "./PostgreSQLParser"; import { CreatefunctionstmtContext } from "./PostgreSQLParser";
import { AttrilistContext } from "./PostgreSQLParser";
import { Opt_or_replaceContext } from "./PostgreSQLParser"; import { Opt_or_replaceContext } from "./PostgreSQLParser";
import { Func_argsContext } from "./PostgreSQLParser"; import { Func_argsContext } from "./PostgreSQLParser";
import { Func_args_listContext } from "./PostgreSQLParser"; import { Func_args_listContext } from "./PostgreSQLParser";
@ -677,6 +681,7 @@ import { Opt_target_listContext } from "./PostgreSQLParser";
import { Target_listContext } from "./PostgreSQLParser"; import { Target_listContext } from "./PostgreSQLParser";
import { Target_elContext } from "./PostgreSQLParser"; import { Target_elContext } from "./PostgreSQLParser";
import { Qualified_name_listContext } from "./PostgreSQLParser"; import { Qualified_name_listContext } from "./PostgreSQLParser";
import { Table_qualified_nameContext } from "./PostgreSQLParser";
import { Qualified_nameContext } from "./PostgreSQLParser"; import { Qualified_nameContext } from "./PostgreSQLParser";
import { Name_listContext } from "./PostgreSQLParser"; import { Name_listContext } from "./PostgreSQLParser";
import { NameContext } from "./PostgreSQLParser"; import { NameContext } from "./PostgreSQLParser";
@ -692,10 +697,15 @@ import { SconstContext } from "./PostgreSQLParser";
import { AnysconstContext } from "./PostgreSQLParser"; import { AnysconstContext } from "./PostgreSQLParser";
import { Opt_uescapeContext } from "./PostgreSQLParser"; import { Opt_uescapeContext } from "./PostgreSQLParser";
import { SignediconstContext } from "./PostgreSQLParser"; import { SignediconstContext } from "./PostgreSQLParser";
import { GroupnameContext } from "./PostgreSQLParser";
import { RoleidContext } from "./PostgreSQLParser"; import { RoleidContext } from "./PostgreSQLParser";
import { RolespecContext } from "./PostgreSQLParser"; import { RolespecContext } from "./PostgreSQLParser";
import { Role_listContext } from "./PostgreSQLParser"; import { Role_listContext } from "./PostgreSQLParser";
import { ColidContext } from "./PostgreSQLParser"; import { ColidContext } from "./PostgreSQLParser";
import { Index_method_choicesContext } from "./PostgreSQLParser";
import { Exclude_elementContext } from "./PostgreSQLParser";
import { Index_paramentersContext } from "./PostgreSQLParser";
import { WherePredicateContext } from "./PostgreSQLParser";
import { Type_function_nameContext } from "./PostgreSQLParser"; import { Type_function_nameContext } from "./PostgreSQLParser";
import { NonreservedwordContext } from "./PostgreSQLParser"; import { NonreservedwordContext } from "./PostgreSQLParser";
import { CollabelContext } from "./PostgreSQLParser"; import { CollabelContext } from "./PostgreSQLParser";
@ -1518,6 +1528,13 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitOpttemp?: (ctx: OpttempContext) => Result; visitOpttemp?: (ctx: OpttempContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.table_column_list`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTable_column_list?: (ctx: Table_column_listContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.opttableelementlist`. * Visit a parse tree produced by `PostgreSQLParser.opttableelementlist`.
* @param ctx the parse tree * @param ctx the parse tree
@ -1603,11 +1620,18 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
visitGenerated_when?: (ctx: Generated_whenContext) => Result; visitGenerated_when?: (ctx: Generated_whenContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.constraintattr`. * Visit a parse tree produced by `PostgreSQLParser.deferrable_trigger`.
* @param ctx the parse tree * @param ctx the parse tree
* @return the visitor result * @return the visitor result
*/ */
visitConstraintattr?: (ctx: ConstraintattrContext) => Result; visitDeferrable_trigger?: (ctx: Deferrable_triggerContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.initially_trigger`.
* @param ctx the parse tree
* @return the visitor result
*/
visitInitially_trigger?: (ctx: Initially_triggerContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.tablelikeclause`. * Visit a parse tree produced by `PostgreSQLParser.tablelikeclause`.
@ -2330,6 +2354,20 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitTriggeractiontime?: (ctx: TriggeractiontimeContext) => Result; visitTriggeractiontime?: (ctx: TriggeractiontimeContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.foreachrow`.
* @param ctx the parse tree
* @return the visitor result
*/
visitForeachrow?: (ctx: ForeachrowContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.roworstatment`.
* @param ctx the parse tree
* @return the visitor result
*/
visitRoworstatment?: (ctx: RoworstatmentContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.triggerevents`. * Visit a parse tree produced by `PostgreSQLParser.triggerevents`.
* @param ctx the parse tree * @param ctx the parse tree
@ -2855,6 +2893,20 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitPrivileges?: (ctx: PrivilegesContext) => Result; visitPrivileges?: (ctx: PrivilegesContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.beforeprivilegeselectlist`.
* @param ctx the parse tree
* @return the visitor result
*/
visitBeforeprivilegeselectlist?: (ctx: BeforeprivilegeselectlistContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.beforeprivilegeselect`.
* @param ctx the parse tree
* @return the visitor result
*/
visitBeforeprivilegeselect?: (ctx: BeforeprivilegeselectContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.privilege_list`. * Visit a parse tree produced by `PostgreSQLParser.privilege_list`.
* @param ctx the parse tree * @param ctx the parse tree
@ -3065,6 +3117,13 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitCreatefunctionstmt?: (ctx: CreatefunctionstmtContext) => Result; visitCreatefunctionstmt?: (ctx: CreatefunctionstmtContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.attrilist`.
* @param ctx the parse tree
* @return the visitor result
*/
visitAttrilist?: (ctx: AttrilistContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.opt_or_replace`. * Visit a parse tree produced by `PostgreSQLParser.opt_or_replace`.
* @param ctx the parse tree * @param ctx the parse tree
@ -5536,6 +5595,13 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitQualified_name_list?: (ctx: Qualified_name_listContext) => Result; visitQualified_name_list?: (ctx: Qualified_name_listContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.table_qualified_name`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTable_qualified_name?: (ctx: Table_qualified_nameContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.qualified_name`. * Visit a parse tree produced by `PostgreSQLParser.qualified_name`.
* @param ctx the parse tree * @param ctx the parse tree
@ -5641,6 +5707,13 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitSignediconst?: (ctx: SignediconstContext) => Result; visitSignediconst?: (ctx: SignediconstContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.groupname`.
* @param ctx the parse tree
* @return the visitor result
*/
visitGroupname?: (ctx: GroupnameContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.roleid`. * Visit a parse tree produced by `PostgreSQLParser.roleid`.
* @param ctx the parse tree * @param ctx the parse tree
@ -5669,6 +5742,34 @@ export interface PostgreSQLParserVisitor<Result> extends ParseTreeVisitor<Result
*/ */
visitColid?: (ctx: ColidContext) => Result; visitColid?: (ctx: ColidContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.index_method_choices`.
* @param ctx the parse tree
* @return the visitor result
*/
visitIndex_method_choices?: (ctx: Index_method_choicesContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.exclude_element`.
* @param ctx the parse tree
* @return the visitor result
*/
visitExclude_element?: (ctx: Exclude_elementContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.index_paramenters`.
* @param ctx the parse tree
* @return the visitor result
*/
visitIndex_paramenters?: (ctx: Index_paramentersContext) => Result;
/**
* Visit a parse tree produced by `PostgreSQLParser.wherePredicate`.
* @param ctx the parse tree
* @return the visitor result
*/
visitWherePredicate?: (ctx: WherePredicateContext) => Result;
/** /**
* Visit a parse tree produced by `PostgreSQLParser.type_function_name`. * Visit a parse tree produced by `PostgreSQLParser.type_function_name`.
* @param ctx the parse tree * @param ctx the parse tree

View File

@ -1,244 +0,0 @@
SELECT * FROM onek
WHERE onek.unique1 < 10
ORDER BY onek.unique1;
SELECT onek.unique1, onek.stringu1 FROM onek
WHERE onek.unique1 < 20
ORDER BY unique1 using >;
SELECT onek.unique1, onek.stringu1 FROM onek
WHERE onek.unique1 > 980
ORDER BY stringu1 using <;
SELECT onek.unique1, onek.string4 FROM onek
WHERE onek.unique1 > 980
ORDER BY string4 using <, unique1 using >;
SELECT onek.unique1, onek.string4 FROM onek
WHERE onek.unique1 > 980
ORDER BY string4 using >, unique1 using <;
--
-- awk '{if($1<20){print $1,$16;}else{next;}}' onek.data |
-- sort +0nr -1 +1d -2
--
SELECT onek.unique1, onek.string4 FROM onek
WHERE onek.unique1 < 20
ORDER BY unique1 using >, string4 using <;
--
-- awk '{if($1<20){print $1,$16;}else{next;}}' onek.data |
-- sort +0n -1 +1dr -2
--
SELECT onek.unique1, onek.string4 FROM onek
WHERE onek.unique1 < 20
ORDER BY unique1 using <, string4 using >;
--
-- test partial btree indexes
--
-- As of 7.2, planner probably won't pick an indexscan without stats,
-- so ANALYZE first. Also, we want to prevent it from picking a bitmapscan
-- followed by sort, because that could hide index ordering problems.
--
ANALYZE onek2;
SET enable_seqscan TO off;
SET enable_bitmapscan TO off;
SET enable_sort TO off;
--
-- awk '{if($1<10){print $0;}else{next;}}' onek.data | sort +0n -1
--
SELECT onek2.* FROM onek2 WHERE onek2.unique1 < 10;
--
-- awk '{if($1<20){print $1,$14;}else{next;}}' onek.data | sort +0nr -1
--
SELECT onek2.unique1, onek2.stringu1 FROM onek2
WHERE onek2.unique1 < 20
ORDER BY unique1 using >;
--
-- awk '{if($1>980){print $1,$14;}else{next;}}' onek.data | sort +1d -2
--
SELECT onek2.unique1, onek2.stringu1 FROM onek2
WHERE onek2.unique1 > 980;
RESET enable_seqscan;
RESET enable_bitmapscan;
RESET enable_sort;
SELECT two, stringu1, ten, string4
INTO TABLE tmp
FROM onek;
--
-- awk '{print $1,$2;}' person.data |
-- awk '{if(NF!=2){print $3,$2;}else{print;}}' - emp.data |
-- awk '{if(NF!=2){print $3,$2;}else{print;}}' - student.data |
-- awk 'BEGIN{FS=" ";}{if(NF!=2){print $4,$5;}else{print;}}' - stud_emp.data
--
-- SELECT name, age FROM person*; ??? check if different
SELECT p.name, p.age FROM person* p;
--
-- awk '{print $1,$2;}' person.data |
-- awk '{if(NF!=2){print $3,$2;}else{print;}}' - emp.data |
-- awk '{if(NF!=2){print $3,$2;}else{print;}}' - student.data |
-- awk 'BEGIN{FS=" ";}{if(NF!=1){print $4,$5;}else{print;}}' - stud_emp.data |
-- sort +1nr -2
--
SELECT p.name, p.age FROM person* p ORDER BY age using >, name;
--
-- Test some cases involving whole-row Var referencing a subquery
--
select foo from (select 1 offset 0) as foo;
select foo from (select null offset 0) as foo;
select foo from (select 'xyzzy',1,null offset 0) as foo;
--
-- Test VALUES lists
--
select * from onek, (values(147, 'RFAAAA'), (931, 'VJAAAA')) as v (i, j)
WHERE onek.unique1 = v.i and onek.stringu1 = v.j;
-- a more complex case
-- looks like we're coding lisp :-)
select * from onek,
(values ((select i from
(values(10000), (2), (389), (1000), (2000), ((select 10029))) as foo(i)
order by i asc limit 1))) bar (i)
where onek.unique1 = bar.i;
-- try VALUES in a subquery
select * from onek
where (unique1,ten) in (values (1,1), (20,0), (99,9), (17,99))
order by unique1;
-- VALUES is also legal as a standalone query or a set-operation member
VALUES (1,2), (3,4+4), (7,77.7);
VALUES (1,2), (3,4+4), (7,77.7)
UNION ALL
SELECT 2+2, 57
UNION ALL
TABLE int8_tbl;
--
-- Test ORDER BY options
--
CREATE TEMP TABLE foo (f1 int);
INSERT INTO foo VALUES (42),(3),(10),(7),(null),(null),(1);
SELECT * FROM foo ORDER BY f1;
SELECT * FROM foo ORDER BY f1 ASC; -- same thing
SELECT * FROM foo ORDER BY f1 NULLS FIRST;
SELECT * FROM foo ORDER BY f1 DESC;
SELECT * FROM foo ORDER BY f1 DESC NULLS LAST;
-- check if indexscans do the right things
CREATE INDEX fooi ON foo (f1);
SET enable_sort = false;
SELECT * FROM foo ORDER BY f1;
SELECT * FROM foo ORDER BY f1 NULLS FIRST;
SELECT * FROM foo ORDER BY f1 DESC;
SELECT * FROM foo ORDER BY f1 DESC NULLS LAST;
DROP INDEX fooi;
CREATE INDEX fooi ON foo (f1 DESC);
SELECT * FROM foo ORDER BY f1;
SELECT * FROM foo ORDER BY f1 NULLS FIRST;
SELECT * FROM foo ORDER BY f1 DESC;
SELECT * FROM foo ORDER BY f1 DESC NULLS LAST;
DROP INDEX fooi;
CREATE INDEX fooi ON foo (f1 DESC NULLS LAST);
SELECT * FROM foo ORDER BY f1;
SELECT * FROM foo ORDER BY f1 NULLS FIRST;
SELECT * FROM foo ORDER BY f1 DESC;
SELECT * FROM foo ORDER BY f1 DESC NULLS LAST;
--
-- Test planning of some cases with partial indexes
--
-- partial index is usable
explain (costs off)
select * from onek2 where unique2 = 11 and stringu1 = 'ATAAAA';
select * from onek2 where unique2 = 11 and stringu1 = 'ATAAAA';
-- actually run the query with an analyze to use the partial index
explain (costs off, analyze on, timing off, summary off)
select * from onek2 where unique2 = 11 and stringu1 = 'ATAAAA';
explain (costs off)
select unique2 from onek2 where unique2 = 11 and stringu1 = 'ATAAAA';
select unique2 from onek2 where unique2 = 11 and stringu1 = 'ATAAAA';
-- partial index predicate implies clause, so no need for retest
explain (costs off)
select * from onek2 where unique2 = 11 and stringu1 < 'B';
select * from onek2 where unique2 = 11 and stringu1 < 'B';
explain (costs off)
select unique2 from onek2 where unique2 = 11 and stringu1 < 'B';
select unique2 from onek2 where unique2 = 11 and stringu1 < 'B';
-- but if it's an update target, must retest anyway
explain (costs off)
select unique2 from onek2 where unique2 = 11 and stringu1 < 'B' for update;
select unique2 from onek2 where unique2 = 11 and stringu1 < 'B' for update;
-- partial index is not applicable
explain (costs off)
select unique2 from onek2 where unique2 = 11 and stringu1 < 'C';
select unique2 from onek2 where unique2 = 11 and stringu1 < 'C';
-- partial index implies clause, but bitmap scan must recheck predicate anyway
SET enable_indexscan TO off;
explain (costs off)
select unique2 from onek2 where unique2 = 11 and stringu1 < 'B';
select unique2 from onek2 where unique2 = 11 and stringu1 < 'B';
RESET enable_indexscan;
-- check multi-index cases too
explain (costs off)
select unique1, unique2 from onek2
where (unique2 = 11 or unique1 = 0) and stringu1 < 'B';
select unique1, unique2 from onek2
where (unique2 = 11 or unique1 = 0) and stringu1 < 'B';
explain (costs off)
select unique1, unique2 from onek2
where (unique2 = 11 and stringu1 < 'B') or unique1 = 0;
select unique1, unique2 from onek2
where (unique2 = 11 and stringu1 < 'B') or unique1 = 0;
--
-- Test some corner cases that have been known to confuse the planner
--
-- ORDER BY on a constant doesn't really need any sorting
SELECT 1 AS x ORDER BY x;
-- But ORDER BY on a set-valued expression does
create function sillysrf(int) returns setof int as
'values (1),(10),(2),($1)' language sql immutable;
select sillysrf(42);
select sillysrf(-1) order by 1;
drop function sillysrf(int);
-- X = X isn't a no-op, it's effectively X IS NOT NULL assuming = is strict
-- (see bug #5084)
select * from (values (2),(null),(1)) v(k) where k = k order by k;
select * from (values (2),(null),(1)) v(k) where k = k;
-- Test partitioned tables with no partitions, which should be handled the
-- same as the non-inheritance case when expanding its RTE.
create table list_parted_tbl (a int,b int) partition by list (a);
create table list_parted_tbl1 partition of list_parted_tbl
for values in (1) partition by list(b);
explain (costs off) select * from list_parted_tbl;
drop table list_parted_tbl;

View File

@ -1,18 +0,0 @@
import PostgresSQL from '../../../src/parser/pgsql';
import { readSQL } from '../../helper';
const parser = new PostgresSQL();
const features = {
base: readSQL(__dirname, 'select.sql'),
};
describe('Postgre SQL Query Statement Tests', () => {
describe('Base Select', () => {
features.base.forEach((sql) => {
it(sql, () => {
expect(parser.validate(sql).length).toBe(0);
});
});
});
});

View File

@ -1,24 +0,0 @@
import PostgresSQL from '../../../src/parser/pgsql';
describe('PostgresSQL SQL Syntax Tests', () => {
const parser = new PostgresSQL();
test('Select Statement', () => {
const sql = 'select id, t_name from user1;';
const result = parser.validate(sql);
expect(result.length).toBe(0);
});
test('Select 1+1', () => {
const sql = 'SELECT 1+1;';
const result = parser.validate(sql);
expect(result.length).toBe(0);
});
test('Select 1+1', () => {
const sql = 'SELECT 1+1;';
const result = parser.validate(sql);
expect(result.length).toBe(0);
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
alters: readSQL(__dirname, 'alter.sql'),
};
describe('PgSQL Create Syntax Tests', () => {
features.alters.forEach((alters) => {
it(alters, () => {
expect(parser.validate(alters).length).toBe(0);
});
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
creates: readSQL(__dirname, 'create.sql'),
};
describe('PgSQL Create Syntax Tests', () => {
features.creates.forEach((create) => {
it(create, () => {
expect(parser.validate(create).length).toBe(0);
});
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
deletes: readSQL(__dirname, 'delete.sql'),
};
describe('PgSQL Delete Syntax Tests', () => {
features.deletes.forEach((deleteItem) => {
it(deleteItem, () => {
expect(parser.validate(deleteItem).length).toBe(0);
});
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
drops: readSQL(__dirname, 'drop.sql'),
};
describe('PgSQL Delete Syntax Tests', () => {
features.drops.forEach((drop) => {
it(drop, () => {
expect(parser.validate(drop).length).toBe(0);
});
});
});

View File

@ -0,0 +1,314 @@
-- Modifying Tables
-- Adding a Column
ALTER TABLE products ADD COLUMN description text CHECK (description <> '');
-- Removing a Column
ALTER TABLE products DROP COLUMN description;
ALTER TABLE products DROP COLUMN description CASCADE;
-- Adding a Constraint
ALTER TABLE products ADD CHECK (name <> '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;
-- Removing a Constraint
ALTER TABLE products DROP CONSTRAINT some_name;
ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
-- Changing a Column's Default Value
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
-- Changing a Column's Data Type
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
-- Renaming a Column
ALTER TABLE products RENAME COLUMN product_no TO product_number;
-- Renaming a Table
ALTER TABLE products RENAME TO items;
-- Managing Partitions
ALTER TABLE measurement_y2006m02 NO INHERIT measurement;
ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' );
-- ALTER AGGREGATE
ALTER AGGREGATE name ( int, integer) RENAME TO new_name;
ALTER AGGREGATE name ( text,int ) OWNER TO new_owner;
ALTER AGGREGATE name ( integer ) SET SCHEMA new_schema;
-- ALTER COLLATION
ALTER COLLATION name RENAME TO new_name;
ALTER COLLATION name OWNER TO new_owner;
ALTER COLLATION name SET SCHEMA new_schema;
-- ALTER CONVERSION
ALTER CONVERSION name RENAME TO new_name;
ALTER CONVERSION name OWNER TO new_owner;
ALTER CONVERSION name SET SCHEMA new_schema;
-- ALTER DATABASE
ALTER DATABASE name WITH CONNECTION LIMIT connlimit;
ALTER DATABASE name RENAME TO new_name;
ALTER DATABASE name OWNER TO new_owner;
ALTER DATABASE name SET TABLESPACE new_tablespace;
ALTER DATABASE name SET configuration_parameter TO DEFAULT;
ALTER DATABASE name SET configuration_parameter FROM CURRENT;
ALTER DATABASE name RESET configuration_parameter;
ALTER DATABASE name RESET ALL;
-- ALTER DEFAULT PRIVILEGES
ALTER DEFAULT PRIVILEGES
FOR ROLE target_role, target_role2
IN SCHEMA schema_name, schema_name2
GRANT SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
ON TABLES
TO GROUP role_name, PUBLIC WITH GRANT OPTION;
-- ALTER DOMAIN
ALTER DOMAIN name SET DEFAULT expression;
ALTER DOMAIN name DROP DEFAULT;
ALTER DOMAIN name SET NOT NULL;
ALTER DOMAIN name ADD CONSTRAINT constraint_name
CHECK (char_length(VALUE) = 5) NOT VALID;
ALTER DOMAIN name
DROP CONSTRAINT IF EXISTS constraint_name RESTRICT;
ALTER DOMAIN name
RENAME CONSTRAINT constraint_name TO new_constraint_name;
ALTER DOMAIN name
VALIDATE CONSTRAINT constraint_name;
ALTER DOMAIN name
OWNER TO new_owner;
ALTER DOMAIN name
RENAME TO new_name;
ALTER DOMAIN name
SET SCHEMA new_schema;
-- ALTER EVENT TRIGGER
ALTER EVENT TRIGGER name DISABLE;
ALTER EVENT TRIGGER name ENABLE REPLICA;
ALTER EVENT TRIGGER name OWNER TO new_owner;
ALTER EVENT TRIGGER name RENAME TO new_name;
-- ALTER EXTENSION
ALTER EXTENSION name UPDATE TO new_version;
ALTER EXTENSION name SET SCHEMA new_schema;
ALTER EXTENSION name ADD AGGREGATE agg_name (agg_type, agg_type2);
ALTER EXTENSION name DROP CAST (source_type AS target_type);
ALTER EXTENSION name DROP COLLATION object_name;
ALTER EXTENSION name DROP CONVERSION object_name;
ALTER EXTENSION name DROP DOMAIN object_name;
ALTER EXTENSION name DROP EVENT TRIGGER object_name;
ALTER EXTENSION name DROP FOREIGN DATA WRAPPER object_name;
ALTER EXTENSION name DROP FOREIGN TABLE object_name ;
ALTER EXTENSION name DROP FUNCTION function_name ( IN argname int);
ALTER EXTENSION name DROP MATERIALIZED VIEW object_name;
ALTER EXTENSION name DROP OPERATOR > (int, int);
ALTER EXTENSION name DROP OPERATOR CLASS object_name USING index_method;
ALTER EXTENSION name DROP OPERATOR FAMILY object_name USING index_method;
ALTER EXTENSION name DROP PROCEDURAL LANGUAGE object_name;
ALTER EXTENSION name DROP SCHEMA object_name;
ALTER EXTENSION name DROP SEQUENCE object_name;
ALTER EXTENSION name DROP SERVER object_name;
ALTER EXTENSION name DROP TABLE object_name;
ALTER EXTENSION name DROP TEXT SEARCH CONFIGURATION object_name;
ALTER EXTENSION name DROP TEXT SEARCH DICTIONARY object_name;
ALTER EXTENSION name DROP TEXT SEARCH PARSER object_name;
ALTER EXTENSION name DROP TEXT SEARCH TEMPLATE object_name;
ALTER EXTENSION name DROP TYPE object_name;
ALTER EXTENSION name DROP VIEW object_name;
-- ALTER FOREIGN DATA WRAPPER
ALTER FOREIGN DATA WRAPPER name
HANDLER handler_function
VALIDATOR validator_function
OPTIONS (ADD option_1 'value', DROP option_2 'value');
ALTER FOREIGN DATA WRAPPER name OWNER TO new_owner;
ALTER FOREIGN DATA WRAPPER name RENAME TO new_name;
-- ALTER FOREIGN TABLE
ALTER FOREIGN TABLE IF EXISTS name
ADD COLUMN column_name data_type COLLATE collation_name, DROP COLUMN IF EXISTS column_name CASCADE, ALTER COLUMN column_name SET DATA TYPE data_type, OWNER TO new_owner, OPTIONS (ADD option_1 'value', DROP option_2 'value');
ALTER FOREIGN TABLE table_name ALTER column_name DROP DEFAULT;
ALTER FOREIGN TABLE IF EXISTS name
RENAME COLUMN column_name TO new_column_name;
ALTER FOREIGN TABLE IF EXISTS name
RENAME TO new_name;
ALTER FOREIGN TABLE IF EXISTS name
SET SCHEMA new_schema;
-- ALTER FUNCTION
ALTER FUNCTION name (VARIADIC argname argtype)
CALLED ON NULL INPUT RESTRICT;
ALTER FUNCTION name ( INOUT argname argtype, OUT argname argtype)
RENAME TO new_name;
ALTER FUNCTION name (INOUT argname argtype)
OWNER TO new_owner;
ALTER FUNCTION name (IN argname argtype)
SET SCHEMA new_schema;
-- ALTER GROUP
ALTER GROUP group_name ADD USER user_name, user_name1;
ALTER GROUP group_name DROP USER user_name,user_name2;
ALTER GROUP group_name RENAME TO new_name;
-- ALTER INDEX
ALTER INDEX IF EXISTS name RENAME TO new_name;
ALTER INDEX IF EXISTS name SET TABLESPACE tablespace_name;
ALTER INDEX IF EXISTS name SET ( storage_parameter = value2 );
ALTER INDEX IF EXISTS name RESET ( storage_parameter );
-- ALTER LANGUAGE
ALTER PROCEDURAL LANGUAGE name RENAME TO new_name;
ALTER LANGUAGE name OWNER TO new_owner;
-- ALTER LARGE OBJECT
ALTER LARGE OBJECT 32423 OWNER TO new_owner;
-- ALTER MATERIALIZED VIEW
ALTER MATERIALIZED VIEW IF EXISTS name
SET WITHOUT CLUSTER,CLUSTER ON index_name;
ALTER MATERIALIZED VIEW IF EXISTS name
RENAME COLUMN column_name TO new_column_name;
ALTER MATERIALIZED VIEW IF EXISTS name
RENAME TO new_name;
ALTER MATERIALIZED VIEW IF EXISTS name
SET SCHEMA new_schema;
ALTER MATERIALIZED VIEW name SET SCHEMA new_schema;
-- ALTER OPERATOR
ALTER OPERATOR - ( NONE , int ) OWNER TO new_owner;
ALTER OPERATOR = ( integer , NONE ) SET SCHEMA new_schema;
-- ALTER OPERATOR CLASS
ALTER OPERATOR CLASS name USING index_method RENAME TO new_name;
ALTER OPERATOR CLASS name USING index_method OWNER TO new_owner;
ALTER OPERATOR CLASS name USING index_method SET SCHEMA new_schema;
-- ALTER OPERATOR FAMILY
ALTER OPERATOR FAMILY name USING index_method ADD
OPERATOR 4 > ( int, integer ) FOR SEARCH,
FUNCTION 3 ( int, int) function_name ( numeric );
ALTER OPERATOR FAMILY name USING index_method DROP
OPERATOR 4 ( op_type, op_type ),
FUNCTION 4 ( op_type, op_type );
ALTER OPERATOR FAMILY name USING index_method RENAME TO new_name;
ALTER OPERATOR FAMILY name USING index_method OWNER TO new_owner;
ALTER OPERATOR FAMILY name USING index_method SET SCHEMA new_schema;
-- ALTER ROLE
ALTER ROLE name WITH SUPERUSER CREATEDB CREATEROLE VALID UNTIL 'timestamp';
ALTER ROLE name RENAME TO new_name;
ALTER ROLE ALL IN DATABASE database_name SET configuration_parameter = DEFAULT;
ALTER ROLE name IN DATABASE database_name SET configuration_parameter FROM CURRENT;
ALTER ROLE ALL IN DATABASE database_name RESET configuration_parameter;
ALTER ROLE name IN DATABASE database_name RESET ALL;
-- ALTER RULE
ALTER RULE name ON table_name RENAME TO new_name;
-- ALTER SCHEMA
ALTER SCHEMA name RENAME TO new_name;
ALTER SCHEMA name OWNER TO new_owner;
-- ALTER SEQUENCE
ALTER SEQUENCE IF EXISTS name INCREMENT BY 324
MINVALUE 34 MAXVALUE 66
START WITH 12 RESTART WITH 34
CACHE 324 NO CYCLE
OWNED BY table_name.column_name;
ALTER SEQUENCE name OWNER TO new_owner;
ALTER SEQUENCE IF EXISTS name RENAME TO new_name;
ALTER SEQUENCE name SET SCHEMA new_schema;
-- ALTER SERVER
ALTER SERVER name VERSION 'new_version' OPTIONS ( ADD option 'value', SET option 'value', DROP option 'value');
ALTER SERVER name OWNER TO new_owner;
ALTER SERVER name RENAME TO new_name;
-- ALTER TABLE
ALTER TABLE IF EXISTS ONLY name *
ALTER COLUMN column_name SET DEFAULT expression, DISABLE RULE rewrite_rule_name, ADD CONSTRAINT constraint_name
UNIQUE USING INDEX index_name DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE name
RENAME column_name TO new_column_name;
ALTER TABLE IF EXISTS ONLY name *
RENAME CONSTRAINT constraint_name TO new_constraint_name;
ALTER TABLE IF EXISTS name
RENAME TO new_name;
ALTER TABLE name
SET SCHEMA new_schema;
-- ALTER TABLESPACE
ALTER TABLESPACE name RENAME TO new_name;
ALTER TABLESPACE name OWNER TO new_owner;
ALTER TABLESPACE name SET ( tablespace_option = value, tablespace_option = value2 );
ALTER TABLESPACE name RESET ( tablespace_option, tablespace_option2 );
-- ALTER TEXT SEARCH CONFIGURATION
ALTER TEXT SEARCH CONFIGURATION name
ADD MAPPING FOR token_type, token_type2 WITH dictionary_name, dictionary_name2;
ALTER TEXT SEARCH CONFIGURATION name
ALTER MAPPING FOR token_type, token_type2 WITH dictionary_name, dictionary_name2;
ALTER TEXT SEARCH CONFIGURATION name
ALTER MAPPING REPLACE old_dictionary WITH new_dictionary;
ALTER TEXT SEARCH CONFIGURATION name
ALTER MAPPING FOR token_type REPLACE old_dictionary WITH new_dictionary;
ALTER TEXT SEARCH CONFIGURATION name
DROP MAPPING IF EXISTS FOR token_type;
ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name;
ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner;
ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema;
-- ALTER TEXT SEARCH DICTIONARY
ALTER TEXT SEARCH DICTIONARY name (
option_1 = value1, option_2
);
ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name;
ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner;
ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema;
-- ALTER TEXT SEARCH PARSER
ALTER TEXT SEARCH PARSER name RENAME TO new_name;
ALTER TEXT SEARCH PARSER name SET SCHEMA new_schema;
-- ALTER TEXT SEARCH TEMPLATE
ALTER TEXT SEARCH TEMPLATE name RENAME TO new_name;
ALTER TEXT SEARCH TEMPLATE name SET SCHEMA new_schema;
-- ALTER TRIGGER
ALTER TRIGGER name ON table_name RENAME TO new_name;
-- ALTER TYPE
ALTER TYPE name ADD ATTRIBUTE attribute_name data_type COLLATE collation_name CASCADE;
ALTER TYPE name OWNER TO new_owner;
ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name RESTRICT;
ALTER TYPE name RENAME TO new_name;
ALTER TYPE name SET SCHEMA new_schema;
ALTER TYPE name ADD VALUE IF NOT EXISTS 'new_enum_value' BEFORE 'existing_enum_value';
-- ALTER USER
ALTER USER name WITH NOSUPERUSER NOCREATEDB NOCREATEROLE NOCREATEUSER NOINHERIT NOLOGIN NOREPLICATION CONNECTION LIMIT 23 PASSWORD 'password' VALID UNTIL 'timestamp';
ALTER USER name;
-- ALTER USER MAPPING
ALTER USER MAPPING FOR CURRENT_USER
SERVER server_name
OPTIONS (ADD option 'value', SET option 'value', DROP option 'value');
-- ALTER VIEW
ALTER VIEW name ALTER COLUMN column_name SET DEFAULT expression;
ALTER VIEW IF EXISTS name ALTER column_name DROP DEFAULT;
ALTER VIEW name OWNER TO new_owner;
ALTER VIEW IF EXISTS name RENAME TO new_name;
ALTER VIEW name SET SCHEMA new_schema;
ALTER VIEW IF EXISTS name SET ( view_option_name = view_option_value, view_option_name2 = view_option_value2);
ALTER VIEW name RESET ( view_option_name, view_option_name );

View File

@ -0,0 +1,512 @@
-- Creating a New Table
-- index_method: btree, hash, gist, spgist and gin
-- The Most Complicated
CREATE GLOBAL TEMPORARY TABLE IF NOT EXISTS table1 (col1 int COLLATE collation1 CONSTRAINT constraint_name NOT NULL DEFERRABLE) INHERITS (table_parent) WITH (storage_parameter = 1) ON COMMIT PRESERVE ROWS TABLESPACE tablespace_name;
CREATE LOCAL TEMP TABLE table1 (col1 int CONSTRAINT constraint_name NULL NOT DEFERRABLE, col2 text CHECK (age > 5) NOT DEFERRABLE INITIALLY DEFERRED, LIKE source_table INCLUDING DEFAULTS) INHERITS (table_parent) WITH OIDS TABLESPACE tablespace_name;
CREATE LOCAL TEMP TABLE table1 (col1 int) INHERITS (table_parent) WITH OIDS ON COMMIT DELETE ROWS;
CREATE UNLOGGED TABLE table1 (col1 int) INHERITS (table_parent) WITHOUT OIDS ON COMMIT DROP;
CREATE TABLE table_name1 OF type_name (col1 WITH OPTIONS CONSTRAINT constraint_name NOT NULL, col2 WITH OPTIONS CONSTRAINT constraint_name CHECK (age > 5) NOT DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE table_name1 OF type_name (col1 WITH OPTIONS CONSTRAINT constraint_name NOT NULL, EXCLUDE USING hash (c WITH &&+) WITH (storage_parameter=3) USING INDEX TABLESPACE tablespace_name WHERE (predicate1=123) NOT DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE weather (
city varchar(80),
temp_lo int,
-- low temperature
temp_hi int,
-- high temperature
prcp real,
-- precipitation
date date
);
CREATE TABLE cities (
name varchar(80),
location point
);
-- remove it
DROP TABLE weather;
-- operate view
CREATE VIEW myview AS
SELECT
city,
temp_lo,
temp_hi,
prcp,
date,
location
FROM
weather,
cities
WHERE
city = name;
-- Foreign Keys
CREATE TABLE cities (
city varchar(80) primary key,
location point
);
CREATE TABLE weather (
city varchar(80) references cities(city),
temp_lo int,
temp_hi int,
prcp real,
date date
);
-- Schemas
-- Creating a Schema
CREATE SCHEMA myschema;
CREATE SCHEMA database1.schema1.table1;
CREATE SCHEMA schemaname AUTHORIZATION username;
-- The Public Schema
CREATE TABLE public7.products(col1 int);
-- Inheritance
CREATE TABLE capitals (
state char(2)
) INHERITS (cities);
-- Partitioning Implementing Partitioning
CREATE TABLE measurement_y2006m02 (
CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
) INHERITS (measurement);
CREATE TRIGGER insert_measurement_trigger
BEFORE INSERT ON measurement
FOR EACH ROW EXECUTE PROCEDURE measurement_insert_trigger();
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
);
CREATE VIEW measurement AS
SELECT * FROM measurement_y2006m02
UNION ALL SELECT * FROM measurement_y2006m03;
-- create Function
CREATE FUNCTION get_color_note (rainbow) RETURNS text AS
'SELECT note FROM my_colors WHERE color = $1'
LANGUAGE SQL;
-- Data types
CREATE TABLE products (
product_no integer,
price numeric,
col4 smallint,
col5 int,
col6 bigint,
col7 decimal,
col8 smallserial,
col9 serial,
col10 bigserial,
col11 real
);
-- Character Types
CREATE TABLE test1 (
name text,
a character(4),
b character varying(4),
c varchar(4)
);
-- Enumerated Types
CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
-- Bit String Types
CREATE TABLE test (a BIT(3), b BIT VARYING(5));
-- Arrays
CREATE TABLE sal_emp (
name text,
pay_by_quarter integer[],
schedule text[][]
);
-- Composite Types
CREATE TYPE inventory_item AS (
name text,
supplier_id integer,
price numeric
);
CREATE TABLE on_hand (
item inventory_item,
count integer
);
-- Ranger Types
CREATE TYPE floatrange AS RANGE (
subtype = float8,
subtype_diff = float8mi
);
-- CREATE AGGREGATE
CREATE AGGREGATE agg_name1 ( int, integer) (
SFUNC = sfunc,
STYPE = state_data_type,
FINALFUNC = ffunc,
INITCOND = initial_condition,
SORTOP = sort_operator
);
CREATE AGGREGATE agg_name2 ( int, integer) (
SFUNC = sfunc,
STYPE = state_data_type
);
CREATE AGGREGATE agg_name3 (
BASETYPE = base_type,
SFUNC = sfunc,
STYPE = state_data_type,
FINALFUNC = ffunc,
INITCOND = initial_condition,
SORTOP = sort_operator
);
CREATE AGGREGATE agg_name4 (
BASETYPE = base_type,
SFUNC = sfunc,
STYPE = state_data_type
);
-- CREATE CAST
CREATE CAST (source_type1 AS target_type1)
WITH FUNCTION function_name1 (argument_type1,argument_type2)
AS ASSIGNMENT;
CREATE CAST (source_type1 AS target_type1)
WITH FUNCTION function_name1 (argument_type1);
CREATE CAST (source_type2 AS target_type2)
WITHOUT FUNCTION
AS IMPLICIT;
CREATE CAST (source_type2 AS target_type2)
WITHOUT FUNCTION;
CREATE CAST (source_type3 AS target_type3)
WITH INOUT
AS ASSIGNMENT;
CREATE CAST (source_type3 AS target_type3)
WITH INOUT;
-- CREATE COLLATION
CREATE COLLATION coll_name (
LOCALE = locale,
LC_COLLATE = lc_collate,
LC_CTYPE = lc_ctype
);
CREATE COLLATION coll_name FROM existing_collation;
-- CREATE CONVERSION
CREATE DEFAULT CONVERSION conver_name
FOR 'source_encoding' TO 'dest_encoding' FROM function_name;
CREATE CONVERSION conver_name1
FOR 'source_encoding' TO 'dest_encoding' FROM function_name;
-- CREATE DATABASE
CREATE DATABASE name1
WITH
OWNER = user_name
TEMPLATE = template
ENCODING = encoding
LC_COLLATE = lc_collate
LC_CTYPE = lc_ctype
TABLESPACE = tablespace_name
CONNECTION LIMIT = connlimit;
CREATE DATABASE name2;
-- CREATE DOMAIN
CREATE DOMAIN name AS data_type
COLLATE collation
DEFAULT expression
CONSTRAINT constraint_name NOT NULL
NULL
CHECK(
VALUE ~ '^\d{5}$'
OR VALUE ~ '^\d{5}-\d{4}$'
);
CREATE DOMAIN domain_name my_type;
-- CREATE EVENT TRIGGER
CREATE EVENT TRIGGER trigger_name
ON event_name
WHEN TAG IN ('filter_value1', 'filter_value2') AND filter_variable IN ('filter_value1', 'filter_value2')
EXECUTE PROCEDURE function_name();
CREATE EVENT TRIGGER trigger_name
ON event_name
EXECUTE PROCEDURE function_name();
-- CREATE EXTENSION
CREATE EXTENSION IF NOT EXISTS extension_name
WITH SCHEMA schema_name
VERSION version
FROM old_version;
CREATE EXTENSION extension_name1;
-- CREATE FOREIGN DATA WRAPPER
CREATE FOREIGN DATA WRAPPER name1
HANDLER handler_function
VALIDATOR validator_function
OPTIONS ( option_name 'value', option_name1 'value2');
CREATE FOREIGN DATA WRAPPER name2
NO HANDLER
NO VALIDATOR
OPTIONS ( option_name 'value');
CREATE FOREIGN DATA WRAPPER name3;
-- CREATE FOREIGN TABLE
CREATE FOREIGN TABLE IF NOT EXISTS table_name (column_name varchar(10) OPTIONS ( option_name1 'value', option_name2 'values') COLLATE coll_name CONSTRAINT constraint_name NOT NULL)
SERVER server_name
OPTIONS ( option_name1 'value', option_name2 'value3');
CREATE FOREIGN TABLE films (
code char(5) NOT NULL,
title varchar(40) NOT NULL,
did integer NOT NULL,
date_prod date,
kind varchar(10),
len interval hour to minute
)
SERVER film_server;
-- CREATE FUNCTION
CREATE OR REPLACE FUNCTION
name ( INOUT argname int DEFAULT a>3)
RETURNS integer
AS 'obj_file'
WITH (isStrict, isCachable);
-- CREATE GROUP
CREATE GROUP group_name WITH SUPERUSER;
CREATE GROUP group_name WITH ENCRYPTED PASSWORD 'password';
CREATE GROUP group_name;
-- CREATE INDEX
CREATE UNIQUE INDEX CONCURRENTLY index_name ON table_name USING btree
((a > 4) COLLATE collation_name ASC NULLS LAST )
WITH ( storage_parameter = 1)
TABLESPACE tablespace_name
WHERE (y > 4);
CREATE INDEX ON table_name (col1);
-- CREATE LANGUAGE
CREATE OR REPLACE PROCEDURAL LANGUAGE lan_name
CREATE OR REPLACE TRUSTED PROCEDURAL LANGUAGE lan_name1
HANDLER call_handler INLINE inline_handler VALIDATOR valfunction;
-- CREATE MATERIALIZED VIEW
CREATE MATERIALIZED VIEW table_name
(column_name, column_name2)
WITH ( storage_parameter=3, storage_parameter1=4)
TABLESPACE tablespace_name
AS SELECT * FROM product
WITH NO DATA;
CREATE MATERIALIZED VIEW table_name2 AS SELECT * FROM product;
-- CREATE OPERATOR
CREATE OPERATOR - (
PROCEDURE = function_name,
LEFTARG = left_type,
RIGHTARG = right_type,
COMMUTATOR = com_op,
NEGATOR = neg_op,
RESTRICT = res_proc,
JOIN = join_proc,
HASHES,
MERGES
);
CREATE OPERATOR == (
PROCEDURE = function_name
);
-- CREATE OPERATOR CLASS
CREATE OPERATOR CLASS op_class_name DEFAULT FOR TYPE type4
USING index_method FAMILY family_name AS
OPERATOR 2 = (arraytype, arraytype1) FOR ORDER BY sort_family_name,
FUNCTION 4 (op_type1, op_type2 ) function_name ( argument_type, argument_type2 ),
STORAGE storage_type;
CREATE OPERATOR CLASS gist__int_ops
FOR TYPE _int4 USING gist AS
OPERATOR 3 &&;
-- CREATE OPERATOR FAMILY
CREATE OPERATOR FAMILY name USING index_method;
-- CREATE ROLE
CREATE ROLE name WITH SUPERUSER CREATEDB CREATEROLE
CREATEUSER
INHERIT
LOGIN
REPLICATION
CONNECTION LIMIT 234
ENCRYPTED PASSWORD 'password'
VALID UNTIL '2013-09-20'
IN ROLE role_name, role_name2
IN GROUP role_name2, role_name3
ROLE role_name3, role_name4
ADMIN role_name4, role_name5
USER role_name5, role_name6
SYSID 234;
-- CREATE RULE
CREATE OR REPLACE RULE name AS ON SELECT
TO table_name WHERE y=3
DO INSTEAD NOTHING;
CREATE OR REPLACE RULE name AS ON SELECT
TO table_name WHERE y=3
DO ALSO (SELECT bb FROM prod);
CREATE RULE rule_name AS ON UPDATE TO table_name DO NOTHING;
-- CREATE SCHEMA
CREATE SCHEMA schema_name AUTHORIZATION user_name CREATE TABLE films (title text, release date, awards text[]) CREATE VIEW winners AS
SELECT title, release FROM films WHERE awards IS NOT NULL;
CREATE SCHEMA AUTHORIZATION user_name CREATE TABLE films (title text, release date, awards text[]);
CREATE SCHEMA IF NOT EXISTS schema_name AUTHORIZATION user_name;
CREATE SCHEMA IF NOT EXISTS AUTHORIZATION user_name;
-- CREATE SEQUENCE
CREATE TEMPORARY SEQUENCE squen_name INCREMENT BY 2432 MINVALUE 45 MAXVALUE 12
START WITH 4654 CACHE 1232 NO CYCLE
OWNED BY table_name.column_name;
CREATE SEQUENCE squen_name;
-- CREATE SERVER
CREATE SERVER server_name TYPE 'server_type' VERSION 'server_version'
FOREIGN DATA WRAPPER fdw_name
OPTIONS ( option 'value', option 'value3');
CREATE SERVER server_name FOREIGN DATA WRAPPER fdw_name;
-- CREATE TABLE AS
CREATE GLOBAL TEMPORARY TABLE table_name
(column_name, column_name2)
WITH ( storage_parameter = 4)
ON COMMIT PRESERVE ROWS
TABLESPACE tablespace_name
AS SELECT * FROM ad
WITH NO DATA;
CREATE TABLE table_name AS SELECT * FROM ad;
-- CREATE TABLESPACE
CREATE TABLESPACE tablespace_name OWNER user_name LOCATION 'directory';
CREATE TABLESPACE tablespace_name LOCATION 'directory';
-- CREATE TEXT SEARCH CONFIGURATION
CREATE TEXT SEARCH CONFIGURATION name (
PARSER = parser_name
);
CREATE TEXT SEARCH CONFIGURATION name (
COPY = source_config
);
-- CREATE TEXT SEARCH DICTIONARY
CREATE TEXT SEARCH DICTIONARY name (
TEMPLATE = template
);
-- CREATE TEXT SEARCH PARSER
CREATE TEXT SEARCH PARSER name (
START = start_function ,
GETTOKEN = gettoken_function ,
END = end_function ,
LEXTYPES = lextypes_function,
HEADLINE = headline_function
);
CREATE TEXT SEARCH PARSER name (
START = start_function ,
GETTOKEN = gettoken_function ,
END = end_function ,
LEXTYPES = lextypes_function
);
-- CREATE TEXT SEARCH TEMPLATE
CREATE TEXT SEARCH TEMPLATE name (
INIT = init_function,
LEXIZE = lexize_function
);
CREATE TEXT SEARCH TEMPLATE name (
LEXIZE = lexize_function
);
-- CREATE TRIGGER
CREATE CONSTRAINT TRIGGER trig_name INSTEAD OF INSERT OR UPDATE
ON table_name
FROM referenced_table_name
DEFERRABLE INITIALLY IMMEDIATE
FOR EACH STATEMENT
WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
EXECUTE PROCEDURE function_name ();
-- CREATE TYPE
CREATE TYPE name AS
(attribute_name int COLLATE collation_name, attribute_name integer COLLATE collation_name);
CREATE TYPE name AS ENUM
('label', 'name');
CREATE TYPE name AS RANGE (
SUBTYPE = subtype,
SUBTYPE_OPCLASS = subtype_operator_class,
COLLATION = collation,
CANONICAL = canonical_function,
SUBTYPE_DIFF = subtype_diff_function
);
CREATE TYPE name (
INPUT = input_function,
OUTPUT = output_function,
RECEIVE = receive_function,
SEND = send_function,
TYPMOD_IN = type_modifier_input_function,
TYPMOD_OUT = type_modifier_output_function,
ANALYZE = analyze_function,
INTERNALLENGTH = 13,
PASSEDBYVALUE,
ALIGNMENT = alignment,
STORAGE = storage,
LIKE = like_type,
CATEGORY = category,
PREFERRED = preferred,
DEFAULT = default_value,
ELEMENT = float4,
DELIMITER = delimiter,
COLLATABLE = collatable
);
CREATE TYPE name;
-- CREATE USER
CREATE USER name WITH NOSUPERUSER NOCREATEDB NOCREATEROLE
NOCREATEUSER
NOINHERIT
NOLOGIN
NOREPLICATION
CONNECTION LIMIT 234
UNENCRYPTED PASSWORD 'password'
VALID UNTIL '2013-09-20'
IN ROLE role_name, role_name2
IN GROUP role_name2, role_name3
ROLE role_name3, role_name4
ADMIN role_name4, role_name5
USER role_name5, role_name6
SYSID 234;
-- CREATE USER MAPPING
CREATE USER MAPPING FOR CURRENT_USER
SERVER server_name
OPTIONS ( option 'value');
CREATE USER MAPPING FOR PUBLIC
SERVER server_name;
-- CREATE VIEW
CREATE OR REPLACE TEMP RECURSIVE VIEW name ( column_name, column_name2)
WITH ( view_option_name = 2321, view_option_name2='ewfwe')
AS SELECT * FROM my_view;
CREATE VIEW view_name AS SELECT * FROM my_view;

View File

@ -0,0 +1,11 @@
DELETE FROM weather WHERE city = 'Hayward';
DELETE FROM products
WHERE obsoletion_date = 'today'
RETURNING ab AS abc_name;
WITH RECURSIVE a AS (SELECT * from bt )
DELETE FROM ONLY table_name * AS alias
USING using_list
WHERE y > 4
RETURNING *;

View File

@ -0,0 +1,144 @@
-- Drop Table
DROP TABLE IF EXISTS table1, table2 RESTRICT;
DROP TABLE products CASCADE;
DROP TABLE products1;
-- DROP AGGREGATE
DROP AGGREGATE IF EXISTS aggname1(int, integer) CASCADE;
DROP AGGREGATE aggname2(int);
-- DROP CAST
DROP CAST IF EXISTS (integer AS int) RESTRICT;
DROP CAST (int AS integer);
-- DROP COLLATION
DROP COLLATION IF EXISTS collation_name CASCADE;
DROP COLLATION collation_name1;
-- DROP CONVERSION
DROP CONVERSION IF EXISTS conver_name RESTRICT;
DROP CONVERSION conver_name1;
-- DROP DATABASE
DROP DATABASE IF EXISTS db_name;
DROP DATABASE db_name;
-- DROP DOMAIN
DROP DOMAIN IF EXISTS domain_name1, domain_name2 CASCADE;
DROP DOMAIN domain_name3;
-- DROP EVENT TRIGGER
DROP EVENT TRIGGER IF EXISTS trigger_name RESTRICT;
DROP EVENT TRIGGER trigger_name1;
-- DROP EXTENSION
DROP EXTENSION IF EXISTS extension_name1, extension_name2 CASCADE;
DROP EXTENSION extension_name3;
-- DROP FOREIGN DATA WRAPPER
DROP FOREIGN DATA WRAPPER IF EXISTS foreigndata_name RESTRICT;
DROP FOREIGN DATA WRAPPER foreigndata_name2;
-- DROP FOREIGN TABLE
DROP FOREIGN TABLE IF EXISTS foreigntable_name1, foreigntable_name2 CASCADE;
DROP FOREIGN TABLE foreigntable_name3;
-- DROP FUNCTION
DROP FUNCTION IF EXISTS function_name (IN argname integer) RESTRICT;
DROP FUNCTION function_name (integer);
-- DROP GROUP
DROP GROUP IF EXISTS group_name1, group_name2;
DROP GROUP group_name3;
-- DROP INDEX
DROP INDEX CONCURRENTLY IF EXISTS index_name1, index_name2 CASCADE;
DROP INDEX index_name3;
-- DROP LANGUAGE
DROP PROCEDURAL LANGUAGE IF EXISTS lan_name RESTRICT;
DROP LANGUAGE lan_name1;
-- DROP MATERIALIZED VIEW
DROP MATERIALIZED VIEW IF EXISTS view_name1, view_name2 CASCADE;
DROP MATERIALIZED VIEW view_name3;
-- DROP OPERATOR
DROP OPERATOR IF EXISTS ! ( NONE , int ) RESTRICT;
DROP OPERATOR - (int, int);
DROP OPERATOR ^ (int, int);
-- DROP OPERATOR CLASS
DROP OPERATOR CLASS IF EXISTS classs_name USING btree CASCADE;
DROP OPERATOR CLASS classs_name USING index_method;
-- DROP OPERATOR FAMILY
DROP OPERATOR FAMILY IF EXISTS family_name USING index_method RESTRICT;
DROP OPERATOR FAMILY family_name1 USING index_method;
-- DROP OWNED
DROP OWNED BY owner_name1, owner_name2 CASCADE;
DROP OWNED BY owner_name3;
-- DROP ROLE
DROP ROLE IF EXISTS role_name1, role_name2;
DROP ROLE role_name3;
-- DROP RULE
DROP RULE IF EXISTS rule_name ON table_name CASCADE;
DROP RULE rule_name1 ON table_name1;
-- DROP SCHEMA
DROP SCHEMA IF EXISTS schema_name1, schema_name2 RESTRICT;
DROP SCHEMA myschema;
-- DROP SEQUENCE
DROP SEQUENCE IF EXISTS con_name1, con_name2 CASCADE;
DROP SEQUENCE con_name3;
-- DROP SERVER
DROP SERVER IF EXISTS server_name RESTRICT;
DROP SERVER server_name1;
-- DROP TABLESPACE
DROP TABLESPACE IF EXISTS tbspace_name1;
DROP TABLESPACE tbspace_name2;
-- DROP TEXT SEARCH CONFIGURATION
DROP TEXT SEARCH CONFIGURATION IF EXISTS text_name CASCADE;
DROP TEXT SEARCH CONFIGURATION text_name1;
-- DROP TEXT SEARCH DICTIONARY
DROP TEXT SEARCH DICTIONARY IF EXISTS dic_name1 RESTRICT;
DROP TEXT SEARCH DICTIONARY dic_name2;
-- DROP TEXT SEARCH PARSER
DROP TEXT SEARCH PARSER IF EXISTS parser_name1 CASCADE;
DROP TEXT SEARCH PARSER parser_name2;
-- DROP TEXT SEARCH TEMPLATE
DROP TEXT SEARCH TEMPLATE IF EXISTS temp_name1 RESTRICT;
DROP TEXT SEARCH TEMPLATE temp_name2;
-- DROP TRIGGER
DROP TRIGGER IF EXISTS trigger_name1 ON table_name1 CASCADE;
DROP TRIGGER trigger_name2 ON table_name2;
-- DROP TYPE
DROP TYPE IF EXISTS type_name1, type_name2 RESTRICT;
DROP TYPE type_name3;
-- DROP USER
DROP USER IF EXISTS user_name1, user_name2;
DROP USER user_name3;
-- DROP USER MAPPING
DROP USER MAPPING IF EXISTS FOR user_name SERVER server_name;
DROP USER MAPPING IF EXISTS FOR USER SERVER server_name;
DROP USER MAPPING IF EXISTS FOR CURRENT_USER SERVER server_name;
DROP USER MAPPING IF EXISTS FOR PUBLIC SERVER server_name;
DROP USER MAPPING FOR PUBLIC SERVER server_name;
-- DROP VIEW
DROP VIEW IF EXISTS view_name1, view_name2 RESTRICT;
DROP VIEW view_name3;

View File

@ -0,0 +1,37 @@
-- Inserting Data
INSERT INTO weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');
INSERT INTO weather (city, temp_lo, temp_hi, prcp, date)
VALUES ('San Francisco', 43, 57, 0.0, '1994-11-29');
INSERT INTO weather (date, city, temp_hi, temp_lo)
VALUES ('1994-11-29', 'Hayward', 54, 37);
INSERT INTO products (product_no, name, price)
SELECT product_no, name, price FROM new_products
WHERE release_date = 'today';
INSERT INTO products DEFAULT VALUES;
INSERT INTO cities (name, population, altitude, state)
VALUES ('New York', NULL, NULL, 'NY');
-- Boolean Type
INSERT INTO test1 VALUES (FALSE, TRUE, 'non est', 't', 'true', 'y', 'on', '1', 'f', 'false', 'n', 'no', 'off', 0);
-- Arrays -- . Array Value Input
INSERT INTO sal_emp
VALUES ('Bill',
'{10000, 10000, 10000, 10000}',
'{{"meeting", "lunch"}, {"training", "presentation"}}');
-- Range Types
INSERT INTO reservation VALUES
(1108, '[2010-01-01 14:30, 2010-01-01 15:30)');
-- INSERT
WITH RECURSIVE a AS (SELECT * from bt )
INSERT INTO table_name ( column_name, column_name2)
VALUES (1, 2)
RETURNING * ;
INSERT INTO films DEFAULT VALUES;

View File

@ -0,0 +1,287 @@
-- ABORT
ABORT WORK;
ABORT TRANSACTION;
-- ANALYZE
ANALYZE VERBOSE table_name ( column_name, column_name2);
ANALYZE;
-- BEGIN
BEGIN WORK ISOLATION LEVEL READ UNCOMMITTED
READ WRITE
NOT DEFERRABLE;
-- CHECKPOINT
CHECKPOINT;
-- CLUSTER
CLUSTER VERBOSE table_name USING index_name;
CLUSTER VERBOSE;
-- CLOSE
CLOSE ALL;
CLOSE name_2;
-- COMMENT
COMMENT ON
AGGREGATE agg_name (agg_type, agg_type2) IS 'text';
COMMENT ON CAST (source_type AS target_type) IS 'text';
COMMENT ON COLLATION object_name IS 'text';
COMMENT ON COLUMN relation_name.column_name IS 'text'
COMMENT ON CONVERSION object_name IS 'text';
COMMENT ON CONSTRAINT constraint_name ON table_name IS 'text';
COMMENT ON DATABASE object_name IS 'text';
COMMENT ON DOMAIN object_name IS 'text';
COMMENT ON EXTENSION object_name IS 'text';
COMMENT ON EVENT TRIGGER object_name IS 'text';
COMMENT ON FOREIGN DATA WRAPPER object_name IS 'text';
COMMENT ON FOREIGN TABLE object_name IS 'text';
COMMENT ON FUNCTION function_name ( INOUT argname timestamp) IS 'text';
COMMENT ON INDEX object_name IS 'text';
COMMENT ON LARGE OBJECT 346344 IS 'text';
COMMENT ON MATERIALIZED VIEW object_name IS 'text';
COMMENT ON OPERATOR -(int, NONE) IS 'text';
COMMENT ON OPERATOR CLASS object_name USING index_method IS 'text';
COMMENT ON OPERATOR FAMILY object_name USING index_method IS 'text';
COMMENT ON PROCEDURAL LANGUAGE object_name IS 'text';
COMMENT ON ROLE object_name IS 'text';
COMMENT ON RULE rule_name ON table_name IS 'text';
COMMENT ON SCHEMA object_name IS 'text';
COMMENT ON SEQUENCE object_name IS 'text';
COMMENT ON SERVER object_name IS 'text';
COMMENT ON TABLE object_name IS 'text';
COMMENT ON TABLESPACE object_name IS 'text';
COMMENT ON TEXT SEARCH CONFIGURATION object_name IS 'text';
COMMENT ON TEXT SEARCH DICTIONARY object_name IS 'text';
COMMENT ON TEXT SEARCH PARSER object_name IS 'text';
COMMENT ON TEXT SEARCH TEMPLATE object_name IS 'text';
COMMENT ON TRIGGER trigger_name ON table_name IS 'text';
COMMENT ON TYPE object_name IS 'text';
COMMENT ON VIEW object_name IS 'text';
-- COMMIT
COMMIT TRANSACTION;
COMMIT WORK;
-- COMMIT PREPARED
COMMIT PREPARED 'foobar';
-- COPY
COPY table_name ( column_name, column_name2)
FROM PROGRAM 'command'
WITH ( FORMAT format_name);
COPY (SELECT * FROM td)
TO STDOUT
WITH (DELIMITER 'delimiter_character');
-- DEALLOCATE
DEALLOCATE PREPARE name;
DEALLOCATE PREPARE ALL;
-- DECLARE
DECLARE name BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR
SELECT
*
FROM
tb;
DECLARE name CURSOR FOR
SELECT
*
FROM
abs;
-- DISCARD
DISCARD TEMPORARY;
DISCARD PLANS;
DISCARD ALL;
DISCARD TEMP;
-- DO
DO LANGUAGE lang_name '$$DECLARE' r record;
DO '$$DECLARE' r record;
-- END
END TRANSACTION;
END WORK;
-- EXECUTE
EXECUTE name ( parameter, parameter2);
-- EXPLAIN
EXPLAIN ( ANALYZE 'true',VERBOSE true, COSTS TRUE, FORMAT TEXT) SELECT * FROM no_nw;
EXPLAIN ANALYZE VERBOSE SELECT * FROM no_nw;
-- FETCH
FETCH NEXT FROM cursor_name;
-- GRANT
GRANT SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
ON TABLE table_name, table_name2
TO GROUP role_name,PUBLIC WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA schema_name, schema_name2 TO PUBLIC;
GRANT SELECT( column_name, column_name2), INSERT( column_name, column_name2), UPDATE( column_name, column_name2), REFERENCES ( column_name, column_name2)
ON TABLE table_name
TO GROUP role_name WITH GRANT OPTION;
GRANT ALL PRIVILEGES ( column_name, column_name2) ON table_name TO role_name;
GRANT USAGE, SELECT, UPDATE
ON SEQUENCE sequence_name
TO GROUP role_name, PUBLIC WITH GRANT OPTION;
GRANT ALL PRIVILEGES
ON ALL SEQUENCES IN SCHEMA schema_name
TO PUBLIC WITH GRANT OPTION;
GRANT CREATE, CONNECT, TEMPORARY, TEMP
ON DATABASE database_name
TO GROUP role_name, PUBLIC WITH GRANT OPTION;
GRANT role_name TO role_name;
-- LISTEN
LISTEN channel;
-- LOAD
LOAD 'filename';
-- LOCK
-- lockmodeACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE
-- | SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE
LOCK TABLE ONLY name * IN ACCESS SHARE MODE NOWAIT;
-- MOVE
MOVE NEXT FROM cursor_name;
-- NOTIFY
NOTIFY virtual, 'This is the payload';
-- PREPARE
PREPARE name ( int, numeric) AS INSERT INTO foo VALUES($1, $2, $3, $4);
-- PREPARE TRANSACTION
PREPARE TRANSACTION 'foobar';
-- REASSIGN OWNED
REASSIGN OWNED BY old_role TO new_role;
-- REFRESH MATERIALIZED VIEW
REFRESH MATERIALIZED VIEW name WITH NO DATA;
-- REINDEX
REINDEX DATABASE name FORCE;
REINDEX TABLE name;
REINDEX INDEX name;
REINDEX SYSTEM name;
-- RELEASE SAVEPOINT
RELEASE SAVEPOINT savepoint_name;
-- RESET
RESET configuration_parameter;
RESET ALL;
-- REVOKE
REVOKE GRANT OPTION FOR
REFERENCES, CREATE
ON TABLE table_name
FROM GROUP role_name, PUBLIC
RESTRICT;
REVOKE ALL PRIVILEGES ON accounts FROM PUBLIC;
REVOKE CREATE ON SCHEMA public_name FROM PUBLIC;
-- ROLLBACK
ROLLBACK TRANSACTION;
ROLLBACK WORK;
-- ROLLBACK PREPARED
ROLLBACK PREPARED 'foobar';
-- ROLLBACK TO SAVEPOINT
ROLLBACK TRANSACTION TO SAVEPOINT savepoint_name;
ROLLBACK WORK TO SAVEPOINT savepoint_name;
ROLLBACK TO savepoint_name;
-- SAVEPOINT
SAVEPOINT savepoint_name;
-- SECURITY LABEL
SECURITY LABEL FOR provider ON TABLE object_name IS 'label';
SECURITY LABEL FOR provider ON COLUMN table_name.column_name IS 'label';
SECURITY LABEL FOR provider ON AGGREGATE agg_name (agg_type, agg_type2) IS 'label';
SECURITY LABEL FOR provider ON DATABASE object_name IS 'label';
SECURITY LABEL FOR provider ON DOMAIN object_name IS 'label';
SECURITY LABEL FOR provider ON EVENT TRIGGER object_name IS 'label';
SECURITY LABEL FOR provider ON FOREIGN TABLE object_name IS 'label';
SECURITY LABEL FOR provider ON FUNCTION function_name ( VARIADIC arg_name timestamp) IS 'label';
SECURITY LABEL FOR provider ON LARGE OBJECT 2432 IS 'label';
SECURITY LABEL FOR provider ON MATERIALIZED VIEW object_name IS 'label';
SECURITY LABEL FOR provider ON PROCEDURAL LANGUAGE object_name IS 'label';
SECURITY LABEL FOR provider ON ROLE object_name IS 'label';
SECURITY LABEL FOR provider ON SCHEMA object_name IS 'label';
SECURITY LABEL FOR provider ON SEQUENCE object_name IS 'label';
SECURITY LABEL FOR provider ON TABLESPACE object_name IS 'label';
SECURITY LABEL FOR provider ON TYPE object_name IS 'label';
SECURITY LABEL FOR provider ON VIEW object_name IS 'label';
-- SET
SET SESSION configuration_parameter TO DEFAULT;
SET LOCAL TIME ZONE LOCAL;
-- SET CONSTRAINTS
SET CONSTRAINTS ALL IMMEDIATE;
SET CONSTRAINTS name1, name2 DEFERRED;
-- SET ROLE
SET SESSION ROLE role_name;
SET LOCAL ROLE NONE;
RESET ROLE;
-- SET SESSION AUTHORIZATION
SET SESSION SESSION AUTHORIZATION user_name;
SET LOCAL SESSION AUTHORIZATION DEFAULT;
RESET SESSION AUTHORIZATION;
-- SET TRANSACTION
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
READ WRITE
NOT DEFERRABLE;
SET TRANSACTION SNAPSHOT '000003A1-1';
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY DEFERRABLE;
-- SHOW
SHOW name;
SHOW ALL;
-- START TRANSACTION
START TRANSACTION ISOLATION LEVEL SERIALIZABLE
READ WRITE
NOT DEFERRABLE, ISOLATION LEVEL REPEATABLE READ READ ONLY DEFERRABLE;
START TRANSACTION;
-- TRUNCATE
TRUNCATE TABLE ONLY name
RESTART IDENTITY CASCADE;
TRUNCATE TABLE ONLY name
CONTINUE IDENTITY RESTRICT;
TRUNCATE name;
-- UNLISTEN
UNLISTEN *;
UNLISTEN channel;
-- VACUUM
VACUUM ( FULL, FREEZE, VERBOSE, ANALYZE) table_name (column_name, column_name2);
VACUUM FULL FREEZE VERBOSE table_name;
VACUUM FULL FREEZE VERBOSE ANALYZE table_name (column_name,column_name2);
VACUUM ANALYZE;
ANALYZE;
-- VALUES
VALUES (1, '3'), (3, 'sdsd')
ORDER BY sort_expression ASC
LIMIT 20
OFFSET 324 ROW
FETCH NEXT 343 ROWS ONLY ;
VALUES (1, '3'), (3, 'sdsd');
-- Caveats
ANALYZE measurement;

View File

@ -0,0 +1,176 @@
-- SELECT
WITH RECURSIVE query_name (id) AS (SELECT id FROM table_expression) SELECT ALL random() AS name1 FROM table_expression WHERE name1=name1 GROUP BY id HAVING sum(len) < interval '5 hours' WINDOW w AS (PARTITION BY depname ORDER BY salary DESC) UNION ALL (SELECT * FROM others) ORDER BY salary DESC LIMIT ALL OFFSET start FETCH NEXT ROWS ONLY FOR UPDATE;
WITH query_name (id) AS (SELECT id FROM table_expression) SELECT DISTINCT random() AS name1 FROM table_expression WHERE name1=name1 GROUP BY id HAVING sum(len) < interval '5 hours' WINDOW w AS (PARTITION BY depname ORDER BY salary DESC) INTERSECT DISTINCT (SELECT * FROM others) ORDER BY salary ASC LIMIT ALL OFFSET start FETCH NEXT ROW ONLY FOR NO KEY UPDATE;
WITH query_name (id) AS (SELECT id FROM table_expression) SELECT DISTINCT ON (col1) random() AS name1 FROM table_expression WHERE name1=name1 GROUP BY id HAVING sum(len) < interval '5 hours' WINDOW w AS (PARTITION BY depname ORDER BY salary DESC) EXCEPT (SELECT * FROM others) ORDER BY salary USING > NULL FIRST LIMIT 40 OFFSET start FETCH NEXT ROW ONLY FOR SHARE;
WITH query_name (id) AS (SELECT id FROM table_expression) SELECT DISTINCT ON (col1) random() AS name1 FROM table_expression WHERE name1=name1 GROUP BY id HAVING sum(len) < interval '5 hours' WINDOW w AS (PARTITION BY depname ORDER BY salary DESC) EXCEPT (SELECT * FROM others) ORDER BY salary USING > NULL FIRST LIMIT 40 OFFSET start FETCH NEXT ROW ONLY FOR KEY SHARE OF table_name NOWAIT;
-- SELECT INTO
WITH RECURSIVE query_name (id) AS (SELECT id FROM table_expression)
SELECT DISTINCT ON (col2)
INTO TEMPORARY TABLE new_table
FROM from_item
WHERE name2=name1
GROUP BY name
HAVING s > 8
WINDOW window_name AS ( RANGE UNBOUNDED PRECEDING )
INTERSECT DISTINCT (SELECT * FROM tb)
ORDER BY expression_1 USING > NULLS FIRST
LIMIT ALL
OFFSET start ROW
FETCH FIRST 234 ROWS ONLY
FOR UPDATE OF table_name NOWAIT;
-- The Most Easy
SELECT * ;
-- Querying a Table
SELECT city, temp_lo, temp_hi, prcp, date FROM weather;
SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;
SELECT * FROM weather
WHERE city = 'San Francisco' AND prcp > 0.0;
SELECT * FROM weather
ORDER BY city;
SELECT * FROM weather
ORDER BY city, temp_lo;
SELECT DISTINCT city
FROM weather;
SELECT DISTINCT city
FROM weather
ORDER BY city;
-- Joins Between Tables
SELECT weather.city, weather.temp_lo, weather.temp_hi,
weather.prcp, weather.date, cities.location
FROM weather NATURAL LEFT OUTER JOIN cities
WHERE cities.name = weather.city;
SELECT W1.city, W1.temp_lo AS low, W1.temp_hi AS high,
W2.city, W2.temp_lo AS low, W2.temp_hi AS high
FROM weather W1 NATURAL RIGHT OUTER JOIN weather W2
WHERE W1.temp_lo < W2.temp_lo
AND W1.temp_hi > W2.temp_hi;
SELECT *
FROM weather w NATURAL FULL OUTER JOIN cities c
WHERE w.city = c.name;
SELECT *
FROM weather w CROSS JOIN cities c
WHERE w.city = c.name;
-- Aggregate Functions
SELECT city, max(temp_lo)
FROM weather
WHERE city LIKE 'S%'
GROUP BY city
HAVING max(temp_lo) < 40;
-- Window Functions
SELECT depname, empno, salary, enroll_date
FROM
(SELECT depname, empno, salary, enroll_date,
rank() OVER (PARTITION BY depname ORDER BY salary DESC, empno) AS pos
FROM empsalary
) AS ss
WHERE pos < 3;
SELECT sum(salary) OVER w, avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);
SELECT name, altitude
FROM ONLY cities
WHERE altitude > 500;
SELECT name, altitude
FROM cities*
WHERE altitude > 500;
SELECT c.tableoid, c.name, c.altitude
FROM cities c
WHERE c.altitude > 500;
-- Overview
WITH query_name (id) AS (SELECT id FROM table_expression) SELECT random() FROM table_expression ORDER BY salary DESC
-- Partitioning and Constraint Exclusion
SET constraint_exclusion = on;
SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
-- Table Functions
SELECT * FROM foo
WHERE foosubid IN (
SELECT foosubid
FROM getfoo(foo.fooid) z
WHERE z.fooid = foo.fooid
);
SELECT *
FROM dblink('dbname=mydb', 'SELECT proname, prosrc FROM pg_proc')
AS t1(proname name, prosrc text)
WHERE proname LIKE 'bytea%';
-- The Schema Search Path
SELECT 3 OPERATOR(pg_catalog.+) 4;
-- Monetary Types
SELECT '12.34'::float8::numeric::money;
-- Binary Data Types
SELECT '\xDEADBEEF';
-- bytea Escape Format
SELECT 'abc \153\154\155 \052\251\124'::bytea;
-- Date/Time Types Interval Input
SELECT EXTRACT(days from '80 hours'::interval);
-- Text Search Types
SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector;
SELECT $$the lexeme ' ' contains spaces$$::tsvector;
SELECT $$the lexeme 'Joe''s' contains a quote$$::tsvector;
SELECT 'a:1 fat:2 cat:3 sat:4 on:5 a:6 mat:7 and:8 ate:9 a:10 fat:11 rat:12'::tsvector;
SELECT to_tsvector('english', 'The Fat Rats');
SELECT 'fat & rat & ! cat'::tsquery;
SELECT to_tsquery('Fat:ab & Cats');
-- Arrays --Accessing Arrays
SELECT name FROM sal_emp WHERE pay_by_quarter[1] <> pay_by_quarter[2];
SELECT schedule[1:2][2] FROM sal_emp WHERE name = 'Bill';
-- Arrays -- Searching in Arrays
SELECT * FROM sal_emp WHERE pay_by_quarter[1] = 10000 OR
pay_by_quarter[2] = 10000 OR
pay_by_quarter[3] = 10000 OR
pay_by_quarter[4] = 10000;
-- Array Input and Output Syntax
SELECT f1[1][-2][3] AS e1, f1[1][-1][5] AS e2
FROM (SELECT '[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'::int[] AS f1) AS ss;
-- Containment
SELECT int4range(10, 20) @> 3;
-- Object Identifier Types
SELECT * FROM pg_attribute WHERE attrelid = 'mytable'::regclass;

View File

@ -0,0 +1,38 @@
UPDATE MY_TABLE SET A = 5;
UPDATE weather
SET temp_hi = temp_hi - 2, temp_lo = temp_lo - 2
WHERE date > '1994-11-28';
-- Transactions
UPDATE accounts SET balance = balance - 100.00
WHERE name = 'Alice';
UPDATE branches SET balance = balance - 100.00
WHERE name = (SELECT branch_name FROM accounts WHERE name = 'Alice');
UPDATE accounts SET balance = balance + 100.00
WHERE name = 'Bob';
UPDATE branches SET balance = balance + 100.00
WHERE name = (SELECT branch_name FROM accounts WHERE name = 'Bob');
UPDATE accounts SET balance = balance - 100.00
WHERE name = 'Alice';
UPDATE mytable SET a = 5, b = b * 3, c = c + 1 WHERE a > 0;
-- Arrays -- Modifying Arrays
UPDATE sal_emp SET pay_by_quarter = ARRAY[25000,25000,27000,27000]
WHERE name = 'Carol';
UPDATE sal_emp SET pay_by_quarter[1:2] = '{27000,27000}'
WHERE name = 'Carol';
--
-- UPDATE
WITH RECURSIVE query_name (id) AS (SELECT id FROM table_expression)
UPDATE ONLY table_name * AS alias
SET column_name = DEFAULT, (column_name, column_nam2) = ( a+1,DEFAULT)
FROM from_list
WHERE a=b
RETURNING * AS output_name;
UPDATE table_name SET column_name = a + 3;

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
inserts: readSQL(__dirname, 'insert.sql'),
};
describe('PgSQL Insert Syntax Tests', () => {
features.inserts.forEach((insertItem) => {
it(insertItem, () => {
expect(parser.validate(insertItem).length).toBe(0);
});
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
others: readSQL(__dirname, 'others.sql'),
};
describe('PgSQL Other SQL Syntax Tests', () => {
features.others.forEach((other) => {
it(other, () => {
expect(parser.validate(other).length).toBe(0);
});
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
selects: readSQL(__dirname, 'select.sql'),
};
describe('PgSQL Select Syntax Tests', () => {
features.selects.forEach((select) => {
it(select, () => {
expect(parser.validate(select).length).toBe(0);
});
});
});

View File

@ -0,0 +1,16 @@
import PgSQL from '../../../../src/parser/pgsql';
import { readSQL } from '../../../helper';
const parser = new PgSQL();
const features = {
updates: readSQL(__dirname, 'update.sql'),
};
describe('PgSQL Update Syntax Tests', () => {
features.updates.forEach((update) => {
it(update, () => {
expect(parser.validate(update).length).toBe(0);
});
});
});