From ef5fc6b24a8ee38da11ad5fd0957a83acf4afc0e Mon Sep 17 00:00:00 2001 From: Lukas Fittl Date: Mon, 1 Jul 2019 01:14:00 -0700 Subject: [PATCH] Add support for CREATE SCHEMA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Author: Mehmet Emin KARAKAŞ (#136) --- lib/pg_query/deparse.rb | 11 ++++++++++ spec/lib/pg_query/deparse_spec.rb | 34 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/lib/pg_query/deparse.rb b/lib/pg_query/deparse.rb index abb93978..0d2fe58d 100644 --- a/lib/pg_query/deparse.rb +++ b/lib/pg_query/deparse.rb @@ -108,6 +108,8 @@ def deparse_item(item, context = nil) # rubocop:disable Metrics/CyclomaticComple deparse_create_function(node) when CREATE_RANGE_STMT deparse_create_range(node) + when CREATE_SCHEMA_STMT + deparse_create_schema(node) when CREATE_STMT deparse_create_table(node) when CREATE_TABLE_AS_STMT @@ -892,6 +894,15 @@ def deparse_create_range(node) output.join(' ') end + def deparse_create_schema(node) + output = ['CREATE SCHEMA'] + output << 'IF NOT EXISTS' if node['if_not_exists'] + output << deparse_identifier(node['schemaname']) if node.key?('schemaname') + output << format('AUTHORIZATION %s', deparse_item(node['authrole'])) if node.key?('authrole') + output << deparse_item_list(node['schemaElts']) if node.key?('schemaElts') + output.join(' ') + end + def deparse_create_table(node) output = [] output << 'CREATE' diff --git a/spec/lib/pg_query/deparse_spec.rb b/spec/lib/pg_query/deparse_spec.rb index 289fb2a1..39adfd8a 100644 --- a/spec/lib/pg_query/deparse_spec.rb +++ b/spec/lib/pg_query/deparse_spec.rb @@ -808,6 +808,40 @@ end end + context 'CREATE SCHEMA' do + # Taken from https://www.postgresql.org/docs/11/sql-createschema.html + context 'basic' do + let(:query) { 'CREATE SCHEMA myschema' } + + it { is_expected.to eq query } + end + + context 'with authorization' do + let(:query) { 'CREATE SCHEMA AUTHORIZATION "joe"' } + + it { is_expected.to eq query } + end + + context 'with if not exist' do + let(:query) { 'CREATE SCHEMA IF NOT EXISTS test AUTHORIZATION "joe"' } + + it { is_expected.to eq query } + end + + context 'with cschema_element' do + let(:query) do + """ + CREATE SCHEMA hollywood + CREATE TABLE \"films\" (title text, release date, awards text[]) + CREATE VIEW winners AS + SELECT \"title\", \"release\" FROM \"films\" WHERE \"awards\" IS NOT NULL + """.strip + end + + it { is_expected.to eq oneline_query } + end + end + context 'CREATE TABLE' do context 'top-level' do let(:query) do