db_schema-reader-postgres 0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 06c75ff7d43c7a7fcf852e6e96a2cea6da4e517c
4
+ data.tar.gz: 69866cfefe8454539deca882a00cdbd3f85c1238
5
+ SHA512:
6
+ metadata.gz: d51763814f5e752b7b5a313287780aa39e4e5a7ccf32649620251b128673006f16ccc8192f43ee3a54d47e1644897eeff602b2b3b15ffdf6987245cf774fe816
7
+ data.tar.gz: 6bfb55ff18fde36a8efaac023a8ef07e211daa040d99477797c9a16878253b4da9eb058709f7789c0662a4b7dd313a64ecf3f64914c65f6a00ea42cef375431b
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.8
5
+ - 2.3.5
6
+ - 2.4.2
7
+ before_install: gem install bundler -v 1.16.0
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at 7@7vn.ru. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,15 @@
1
+ guard :rspec, cmd: 'bundle exec rspec', all_on_start: true do
2
+ require 'guard/rspec/dsl'
3
+ dsl = Guard::RSpec::Dsl.new(self)
4
+
5
+ # RSpec files
6
+ rspec = dsl.rspec
7
+ watch(rspec.spec_helper) { rspec.spec_dir }
8
+ watch(rspec.spec_support) { rspec.spec_dir }
9
+ watch(rspec.spec_files)
10
+
11
+ # Ruby files
12
+ ruby = dsl.ruby
13
+ dsl.watch_spec_files_for(ruby.lib_files)
14
+ watch('lib/db_schema/reader/postgres/table.rb') { 'spec/db_schema/reader/postgres_spec.rb' }
15
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Vsevolod Romashov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # DbSchema::Reader::Postgres
2
+
3
+ DbSchema::Reader::Postgres is a library for reading the database
4
+ structure from PostgreSQL.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ``` ruby
11
+ gem 'db_schema-reader-postgres'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ ``` sh
17
+ $ bundle
18
+ ```
19
+ Or install it yourself as:
20
+
21
+ ``` ruby
22
+ $ gem install db_schema-reader-postgres
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ First you need a Sequel connection object with `:pg_enum` and `:pg_array`
28
+ Sequel extensions enabled; once you have that object just pass it to
29
+ the `.read_schema` method to get full database schema definition:
30
+
31
+ ``` ruby
32
+ connection = Sequel.connect(adapter: 'postgres', database: 'db_schema_test').tap do |db|
33
+ db.extension :pg_enum
34
+ db.extension :pg_array
35
+ end
36
+
37
+ DbSchema::Reader::Postgres.read_schema(connection)
38
+ # => #<DbSchema::Definitions::Schema ...>
39
+ ```
40
+
41
+ Other useful methods are `.read_tables`, `.read_table`, `.read_enums` & `.read_extensions`;
42
+ they return definitions of respective parts of the database schema:
43
+
44
+ ``` ruby
45
+ DbSchema::Reader::Postgres.read_tables(connection)
46
+ # => [#<DbSchema::Definitions::Table ...>, #<DbSchema::Definitions::Table ...>, ...]
47
+
48
+ DbSchema::Reader::Postgres.read_table(:users, connection)
49
+ # => #<DbSchema::Definitions::Table name=:users ...>
50
+
51
+ DbSchema::Reader::Postgres.read_enums(connection)
52
+ # => [#<DbSchema::Definitions::Enum ...>, #<DbSchema::Definitions::Enum ...>, ...]
53
+
54
+ DbSchema::Reader::Postgres.read_extensions(connection)
55
+ # => [#<DbSchema::Definitions::Extension ...>, #<DbSchema::Definitions::Extension ...>, ...]
56
+ ```
57
+
58
+ DbSchema::Reader::Postgres emits objects of classes from
59
+ [DbSchema::Definitions](https://github.com/db-schema/definitions).
60
+ Read [here](https://github.com/db-schema/core/wiki/Schema-analysis-DSL)
61
+ how to analyze the schema and all of it's parts.
62
+
63
+ ## Development
64
+
65
+ After checking out the repo, run `bin/setup` to install dependencies.
66
+ Then, run `rake spec` to run the tests. You can also run `bin/console`
67
+ for an interactive prompt that will allow you to experiment.
68
+
69
+ To install this gem onto your local machine, run `bundle exec rake install`.
70
+ To release a new version, update the version number in `version.rb`,
71
+ and then run `bundle exec rake release`, which will create a git tag
72
+ for the version, push git commits and tags, and push the `.gem` file
73
+ to [rubygems.org](https://rubygems.org).
74
+
75
+ ## Contributing
76
+
77
+ Bug reports and pull requests are welcome on GitHub
78
+ at [db-schema/reader-postgres](https://github.com/db-schema/reader-postgres).
79
+ This project is intended to be a safe, welcoming space for collaboration,
80
+ and contributors are expected to adhere to the
81
+ [Contributor Covenant](http://contributor-covenant.org) code of conduct.
82
+
83
+ ## License
84
+
85
+ The gem is available as open source under the terms of
86
+ the [MIT License](https://opensource.org/licenses/MIT).
87
+
88
+ ## Code of Conduct
89
+
90
+ Everyone interacting in the DbSchema::Definitions project’s codebases,
91
+ issue trackers, chat rooms and mailing lists is expected to follow
92
+ the [code of conduct](https://github.com/db-schema/reader-postgres/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'db_schema/reader/postgres'
5
+ require 'sequel'
6
+
7
+ require 'pry'
8
+ require 'awesome_print'
9
+ AwesomePrint.pry!
10
+
11
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,34 @@
1
+ lib = File.expand_path('../lib', __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'db_schema/reader/postgres/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'db_schema-reader-postgres'
7
+ spec.version = DbSchema::Reader::Postgres::VERSION
8
+ spec.authors = ['Vsevolod Romashov']
9
+ spec.email = ['7@7vn.ru']
10
+
11
+ spec.summary = 'Database schema reader for PostgreSQL'
12
+ spec.description = 'A database structure reader for PostgreSQL with support for tables, fields, indexes, foreign keys, check constraints, enum types and extensions.'
13
+ spec.homepage = 'https://github.com/db-schema/reader-postgres'
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^spec/}) }
17
+ spec.bindir = 'exe'
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.add_runtime_dependency 'sequel'
22
+ spec.add_runtime_dependency 'pg'
23
+ spec.add_runtime_dependency 'db_schema-definitions', '~> 0.1.0'
24
+
25
+ spec.add_development_dependency 'bundler', '~> 1.16'
26
+ spec.add_development_dependency 'rake', '~> 10.0'
27
+ spec.add_development_dependency 'pry'
28
+ spec.add_development_dependency 'awesome_print', '~> 1.7'
29
+
30
+ spec.add_development_dependency 'rspec', '~> 3.0'
31
+ spec.add_development_dependency 'guard-rspec'
32
+ spec.add_development_dependency 'terminal-notifier'
33
+ spec.add_development_dependency 'terminal-notifier-guard'
34
+ end
@@ -0,0 +1,56 @@
1
+ require 'db_schema/definitions'
2
+ require_relative 'postgres/table'
3
+ require_relative 'postgres/version'
4
+
5
+ module DbSchema
6
+ module Reader
7
+ module Postgres
8
+ ENUMS_QUERY = <<-SQL.freeze
9
+ SELECT t.typname AS name,
10
+ array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
11
+ FROM pg_enum AS e
12
+ JOIN pg_type AS t
13
+ ON t.oid = e.enumtypid
14
+ GROUP BY name
15
+ SQL
16
+
17
+ EXTENSIONS_QUERY = <<-SQL.freeze
18
+ SELECT extname
19
+ FROM pg_extension
20
+ WHERE extname != 'plpgsql'
21
+ SQL
22
+
23
+ class << self
24
+ def read_schema(connection)
25
+ Definitions::Schema.new(
26
+ tables: read_tables(connection),
27
+ enums: read_enums(connection),
28
+ extensions: read_extensions(connection)
29
+ )
30
+ end
31
+
32
+ def read_tables(connection)
33
+ connection.tables.map do |table_name|
34
+ read_table(table_name, connection)
35
+ end
36
+ end
37
+
38
+ def read_table(table_name, connection)
39
+ Table.new(connection, table_name).read
40
+ end
41
+
42
+ def read_enums(connection)
43
+ connection[ENUMS_QUERY].map do |enum_data|
44
+ Definitions::Enum.new(enum_data[:name].to_sym, enum_data[:values].map(&:to_sym))
45
+ end
46
+ end
47
+
48
+ def read_extensions(connection)
49
+ connection[EXTENSIONS_QUERY].map do |extension_data|
50
+ Definitions::Extension.new(extension_data[:extname].to_sym)
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,319 @@
1
+ module DbSchema
2
+ module Reader
3
+ module Postgres
4
+ class Table
5
+ DEFAULT_VALUE = /\A(
6
+ ('(?<date>\d{4}-\d{2}-\d{2})'::date)
7
+ |
8
+ ('(?<time>\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}([+-]\d{2})?)'::timestamp)
9
+ |
10
+ ('(?<string>.*)')
11
+ |
12
+ (?<float>\d+\.\d+)
13
+ |
14
+ (?<integer>\d+)
15
+ |
16
+ (?<boolean>true|false)
17
+ )/x
18
+
19
+ COLUMN_NAMES_QUERY = <<-SQL.freeze
20
+ SELECT c.column_name AS name,
21
+ c.ordinal_position AS pos,
22
+ c.column_default AS default,
23
+ c.is_nullable AS null,
24
+ c.data_type AS type,
25
+ c.udt_name AS custom_type_name,
26
+ c.character_maximum_length AS char_length,
27
+ c.numeric_precision AS num_precision,
28
+ c.numeric_scale AS num_scale,
29
+ c.datetime_precision AS dt_precision,
30
+ c.interval_type,
31
+ e.data_type AS element_type,
32
+ e.udt_name AS element_custom_type_name
33
+ FROM information_schema.columns AS c
34
+ LEFT JOIN information_schema.element_types AS e
35
+ ON e.object_catalog = c.table_catalog
36
+ AND e.object_schema = c.table_schema
37
+ AND e.object_name = c.table_name
38
+ AND e.object_type = 'TABLE'
39
+ AND e.collection_type_identifier = c.dtd_identifier
40
+ WHERE c.table_schema = 'public'
41
+ AND c.table_name = ?
42
+ SQL
43
+
44
+ CONSTRAINTS_QUERY = <<-SQL.freeze
45
+ SELECT conname AS name,
46
+ pg_get_expr(conbin, conrelid, true) AS condition
47
+ FROM pg_constraint, pg_class
48
+ WHERE conrelid = pg_class.oid
49
+ AND relname = ?
50
+ AND contype = 'c'
51
+ SQL
52
+
53
+ INDEXES_QUERY = <<-SQL.freeze
54
+ SELECT relname AS name,
55
+ indkey AS column_positions,
56
+ indisunique AS unique,
57
+ indoption AS index_options,
58
+ pg_get_expr(indpred, indrelid, true) AS condition,
59
+ amname AS index_type,
60
+ indexrelid AS index_oid
61
+ FROM pg_class, pg_index
62
+ LEFT JOIN pg_opclass
63
+ ON pg_opclass.oid = ANY(pg_index.indclass::int[])
64
+ LEFT JOIN pg_am
65
+ ON pg_am.oid = pg_opclass.opcmethod
66
+ WHERE pg_class.oid = pg_index.indexrelid
67
+ AND pg_class.oid IN (
68
+ SELECT indexrelid
69
+ FROM pg_index, pg_class
70
+ WHERE pg_class.relname = ?
71
+ AND pg_class.oid = pg_index.indrelid
72
+ AND indisprimary != 't'
73
+ )
74
+ GROUP BY name, column_positions, indisunique, index_options, condition, index_type, index_oid
75
+ SQL
76
+
77
+ EXPRESSION_INDEXES_QUERY = <<-SQL.freeze
78
+ WITH index_ids AS (SELECT unnest(?) AS index_id),
79
+ elements AS (SELECT unnest(?) AS element)
80
+ SELECT index_id,
81
+ array_agg(pg_get_indexdef(index_id, element, 't')) AS definitions
82
+ FROM index_ids, elements
83
+ GROUP BY index_id;
84
+ SQL
85
+
86
+ attr_reader :connection, :table_name
87
+
88
+ def initialize(connection, table_name)
89
+ @connection = connection
90
+ @table_name = table_name
91
+ end
92
+
93
+ def read
94
+ primary_key_name = connection.primary_key(table_name)
95
+
96
+ fields = columns_data.map do |column_data|
97
+ build_field(column_data, primary_key: column_data[:name] == primary_key_name)
98
+ end
99
+
100
+ indexes = indexes_data.map do |index_data|
101
+ Definitions::Index.new(index_data)
102
+ end.sort_by(&:name)
103
+
104
+ foreign_keys = connection.foreign_key_list(table_name).map do |foreign_key_data|
105
+ build_foreign_key(foreign_key_data)
106
+ end
107
+
108
+ checks = connection[CONSTRAINTS_QUERY, table_name.to_s].map do |check_data|
109
+ Definitions::CheckConstraint.new(
110
+ name: check_data[:name].to_sym,
111
+ condition: check_data[:condition]
112
+ )
113
+ end
114
+
115
+ Definitions::Table.new(
116
+ table_name,
117
+ fields: fields,
118
+ indexes: indexes,
119
+ checks: checks,
120
+ foreign_keys: foreign_keys
121
+ )
122
+ end
123
+
124
+ private
125
+ def columns_data
126
+ @columns_data ||= connection[COLUMN_NAMES_QUERY, table_name.to_s]
127
+ end
128
+
129
+ def indexes_data
130
+ column_names = columns_data.reduce({}) do |names, column|
131
+ names.merge(column[:pos] => column[:name].to_sym)
132
+ end
133
+
134
+ indexes_data = connection[INDEXES_QUERY, table_name.to_s].to_a
135
+ expressions_data = index_expressions_data(indexes_data)
136
+
137
+ indexes_data.map do |index|
138
+ positions = index[:column_positions].split(' ').map(&:to_i)
139
+ options = index[:index_options].split(' ').map(&:to_i)
140
+
141
+ columns = positions.zip(options).map do |column_position, column_order_options|
142
+ options = case column_order_options
143
+ when 0
144
+ {}
145
+ when 3
146
+ { order: :desc }
147
+ when 2
148
+ { nulls: :first }
149
+ when 1
150
+ { order: :desc, nulls: :last }
151
+ end
152
+
153
+ if column_position.zero?
154
+ expression = expressions_data.fetch(index[:index_oid]).shift
155
+ DbSchema::Definitions::Index::Expression.new(expression, **options)
156
+ else
157
+ DbSchema::Definitions::Index::TableField.new(column_names.fetch(column_position), **options)
158
+ end
159
+ end
160
+
161
+ {
162
+ name: index[:name].to_sym,
163
+ columns: columns,
164
+ unique: index[:unique],
165
+ type: index[:index_type].to_sym,
166
+ condition: index[:condition]
167
+ }
168
+ end
169
+ end
170
+
171
+ def index_expressions_data(indexes_data)
172
+ all_positions, max_position = {}, 0
173
+
174
+ indexes_data.each do |index_data|
175
+ positions = index_data[:column_positions].split(' ').map(&:to_i)
176
+ expression_positions = positions.each_index.select { |i| positions[i].zero? }
177
+
178
+ if expression_positions.any?
179
+ all_positions[index_data[:index_oid]] = expression_positions
180
+ max_position = [max_position, expression_positions.max].max
181
+ end
182
+ end
183
+
184
+ if all_positions.any?
185
+ connection[
186
+ EXPRESSION_INDEXES_QUERY,
187
+ Sequel.pg_array(all_positions.keys),
188
+ Sequel.pg_array((1..max_position.succ).to_a)
189
+ ].each_with_object({}) do |index_data, indexes_data|
190
+ index_id = index_data[:index_id]
191
+ expressions = all_positions[index_id].map { |pos| index_data[:definitions][pos] }
192
+
193
+ indexes_data[index_id] = expressions
194
+ end
195
+ else
196
+ {}
197
+ end
198
+ end
199
+
200
+ def build_field(data, primary_key: false)
201
+ type = data[:type].to_sym.downcase
202
+ if type == :'user-defined'
203
+ type = data[:custom_type_name].to_sym
204
+ end
205
+
206
+ nullable = (data[:null] != 'NO')
207
+
208
+ unless primary_key || data[:default].nil?
209
+ default = if match = DEFAULT_VALUE.match(data[:default])
210
+ if match[:date]
211
+ Date.parse(match[:date])
212
+ elsif match[:time]
213
+ Time.parse(match[:time])
214
+ elsif match[:string]
215
+ match[:string]
216
+ elsif match[:integer]
217
+ match[:integer].to_i
218
+ elsif match[:float]
219
+ match[:float].to_f
220
+ elsif match[:boolean]
221
+ match[:boolean] == 'true'
222
+ end
223
+ else
224
+ data[:default].to_sym
225
+ end
226
+ end
227
+
228
+ options = case type
229
+ when :character, :'character varying', :bit, :'bit varying'
230
+ rename_keys(
231
+ filter_by_keys(data, :char_length),
232
+ char_length: :length
233
+ )
234
+ when :numeric
235
+ rename_keys(
236
+ filter_by_keys(data, :num_precision, :num_scale),
237
+ num_precision: :precision,
238
+ num_scale: :scale
239
+ )
240
+ when :interval
241
+ rename_keys(
242
+ filter_by_keys(data, :dt_precision, :interval_type),
243
+ dt_precision: :precision
244
+ ) do |attributes|
245
+ if interval_type = attributes.delete(:interval_type)
246
+ attributes[:fields] = interval_type.gsub(/\(\d\)/, '').downcase.to_sym
247
+ end
248
+ end
249
+ when :array
250
+ rename_keys(
251
+ filter_by_keys(data, :element_type, :element_custom_type_name)
252
+ ) do |attributes|
253
+ attributes[:element_type] = if attributes[:element_type] == 'USER-DEFINED'
254
+ attributes[:element_custom_type_name]
255
+ else
256
+ attributes[:element_type]
257
+ end.to_sym
258
+ end
259
+ else
260
+ {}
261
+ end
262
+
263
+ Definitions::Field.build(
264
+ data[:name].to_sym,
265
+ type,
266
+ primary_key: primary_key,
267
+ null: nullable,
268
+ default: default,
269
+ **options
270
+ )
271
+ end
272
+
273
+ def build_foreign_key(data)
274
+ keys = if data[:key] == [primary_key_for(data[:table])]
275
+ [] # this foreign key references a primary key
276
+ else
277
+ data[:key]
278
+ end
279
+
280
+ Definitions::ForeignKey.new(
281
+ name: data[:name],
282
+ fields: data[:columns],
283
+ table: data[:table],
284
+ keys: keys,
285
+ on_delete: data[:on_delete],
286
+ on_update: data[:on_update],
287
+ deferrable: data[:deferrable]
288
+ )
289
+ end
290
+
291
+ def primary_key_for(table_name)
292
+ if pkey = connection.primary_key(table_name)
293
+ pkey.to_sym
294
+ end
295
+ end
296
+
297
+ # TODO: replace following methods with Transproc
298
+ def rename_keys(hash, mapping = {})
299
+ hash.reduce({}) do |final_hash, (key, value)|
300
+ new_key = mapping.fetch(key, key)
301
+ final_hash.merge(new_key => value)
302
+ end.tap do |final_hash|
303
+ yield(final_hash) if block_given?
304
+ end
305
+ end
306
+
307
+ def filter_by_keys(hash, *needed_keys)
308
+ hash.reduce({}) do |final_hash, (key, value)|
309
+ if needed_keys.include?(key)
310
+ final_hash.merge(key => value)
311
+ else
312
+ final_hash
313
+ end
314
+ end
315
+ end
316
+ end
317
+ end
318
+ end
319
+ end
@@ -0,0 +1,7 @@
1
+ module DbSchema
2
+ module Reader
3
+ module Postgres
4
+ VERSION = '0.1'
5
+ end
6
+ end
7
+ end
metadata ADDED
@@ -0,0 +1,214 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: db_schema-reader-postgres
3
+ version: !ruby/object:Gem::Version
4
+ version: '0.1'
5
+ platform: ruby
6
+ authors:
7
+ - Vsevolod Romashov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: sequel
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pg
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: db_schema-definitions
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 0.1.0
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 0.1.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.16'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.16'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '10.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '10.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: awesome_print
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '1.7'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '1.7'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rspec
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '3.0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '3.0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: guard-rspec
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ - !ruby/object:Gem::Dependency
140
+ name: terminal-notifier
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ - !ruby/object:Gem::Dependency
154
+ name: terminal-notifier-guard
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ">="
158
+ - !ruby/object:Gem::Version
159
+ version: '0'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ description: A database structure reader for PostgreSQL with support for tables, fields,
168
+ indexes, foreign keys, check constraints, enum types and extensions.
169
+ email:
170
+ - 7@7vn.ru
171
+ executables: []
172
+ extensions: []
173
+ extra_rdoc_files: []
174
+ files:
175
+ - ".gitignore"
176
+ - ".rspec"
177
+ - ".travis.yml"
178
+ - CODE_OF_CONDUCT.md
179
+ - Gemfile
180
+ - Guardfile
181
+ - LICENSE.txt
182
+ - README.md
183
+ - Rakefile
184
+ - bin/console
185
+ - bin/setup
186
+ - db_schema-reader-postgres.gemspec
187
+ - lib/db_schema/reader/postgres.rb
188
+ - lib/db_schema/reader/postgres/table.rb
189
+ - lib/db_schema/reader/postgres/version.rb
190
+ homepage: https://github.com/db-schema/reader-postgres
191
+ licenses:
192
+ - MIT
193
+ metadata: {}
194
+ post_install_message:
195
+ rdoc_options: []
196
+ require_paths:
197
+ - lib
198
+ required_ruby_version: !ruby/object:Gem::Requirement
199
+ requirements:
200
+ - - ">="
201
+ - !ruby/object:Gem::Version
202
+ version: '0'
203
+ required_rubygems_version: !ruby/object:Gem::Requirement
204
+ requirements:
205
+ - - ">="
206
+ - !ruby/object:Gem::Version
207
+ version: '0'
208
+ requirements: []
209
+ rubyforge_project:
210
+ rubygems_version: 2.6.13
211
+ signing_key:
212
+ specification_version: 4
213
+ summary: Database schema reader for PostgreSQL
214
+ test_files: []