schema_to_dbml 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1d1c7e55da915704ade42e031926565a591aa815626fcf0f54ef9f75a9e85875
4
+ data.tar.gz: 80e1485742492b48126ab3ef28023b72c67f86d1512f97f751b9c7bd05ff1180
5
+ SHA512:
6
+ metadata.gz: c4e534e1ed44995890a6d4cfa425c5157e83d9b29299a77783c4d7a1e427fd55732410c915262f71e02a274a4390315ca548c2ce73ec585f7d3c5ca4b4fcdc8a
7
+ data.tar.gz: fa702214c60f1e94c587c4509d94816ce2cebd0e1ad441441dfe5a4cbb634018d56ae0ebc49ffe87e5fcbb5c89273b62effdd34021bc65e0601ab8a5d77a6e23
data/.rubocop.yml ADDED
@@ -0,0 +1,82 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1.2
3
+ Exclude:
4
+ - spec/lib/schema_to_dbml/support/*
5
+ - spec/shared_examples/*
6
+ - vendor/bundle/**/*
7
+ NewCops: enable
8
+
9
+ Layout/LineLength:
10
+ Max: 150
11
+
12
+ Metrics/MethodLength:
13
+ Max: 14
14
+
15
+ Metrics/AbcSize:
16
+ Max: 24
17
+
18
+ Style/Documentation:
19
+ Enabled: false
20
+
21
+ Metrics/BlockLength:
22
+ Enabled: false
23
+
24
+ Layout/EmptyLinesAroundAttributeAccessor:
25
+ Enabled: true
26
+
27
+ Layout/SpaceAroundMethodCallOperator:
28
+ Enabled: true
29
+
30
+ Lint/MixedRegexpCaptureTypes:
31
+ Enabled: true
32
+
33
+ Lint/RaiseException:
34
+ Enabled: true
35
+
36
+ Lint/StructNewOverride:
37
+ Enabled: true
38
+
39
+ Style/ExponentialNotation:
40
+ Enabled: true
41
+
42
+ Style/HashEachMethods:
43
+ Enabled: true
44
+
45
+ Style/HashTransformKeys:
46
+ Enabled: true
47
+
48
+ Style/HashTransformValues:
49
+ Enabled: true
50
+
51
+ Style/RedundantRegexpCharacterClass:
52
+ Enabled: true
53
+
54
+ Style/RedundantRegexpEscape:
55
+ Enabled: true
56
+
57
+ Style/SlicingWithRange:
58
+ Enabled: true
59
+
60
+ Style/AccessorGrouping:
61
+ Enabled: true
62
+
63
+ Style/BisectedAttrAccessor:
64
+ Enabled: true
65
+
66
+ Style/RedundantAssignment:
67
+ Enabled: true
68
+
69
+ Style/RedundantFetchBlock:
70
+ Enabled: true
71
+
72
+ Style/Documentation:
73
+ Enabled: false
74
+
75
+ Style/MethodCallWithArgsParentheses:
76
+ Enabled: false
77
+
78
+ Gemspec/DevelopmentDependencies:
79
+ Enabled: false
80
+
81
+ Metrics/ParameterLists:
82
+ Max: 7
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-04-05
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at ricardo.ribeiro@knokcare.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in schema_to_dbml.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,68 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ schema_to_dbml (0.0.1)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ byebug (11.1.3)
11
+ diff-lcs (1.5.0)
12
+ docile (1.4.0)
13
+ json (2.6.3)
14
+ parallel (1.22.1)
15
+ parser (3.2.2.0)
16
+ ast (~> 2.4.1)
17
+ rainbow (3.1.1)
18
+ rake (13.0.6)
19
+ regexp_parser (2.7.0)
20
+ rexml (3.2.5)
21
+ rspec (3.12.0)
22
+ rspec-core (~> 3.12.0)
23
+ rspec-expectations (~> 3.12.0)
24
+ rspec-mocks (~> 3.12.0)
25
+ rspec-core (3.12.1)
26
+ rspec-support (~> 3.12.0)
27
+ rspec-expectations (3.12.2)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.12.0)
30
+ rspec-mocks (3.12.5)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.12.0)
33
+ rspec-support (3.12.0)
34
+ rubocop (1.49.0)
35
+ json (~> 2.3)
36
+ parallel (~> 1.10)
37
+ parser (>= 3.2.0.0)
38
+ rainbow (>= 2.2.2, < 4.0)
39
+ regexp_parser (>= 1.8, < 3.0)
40
+ rexml (>= 3.2.5, < 4.0)
41
+ rubocop-ast (>= 1.28.0, < 2.0)
42
+ ruby-progressbar (~> 1.7)
43
+ unicode-display_width (>= 2.4.0, < 3.0)
44
+ rubocop-ast (1.28.0)
45
+ parser (>= 3.2.1.0)
46
+ ruby-progressbar (1.13.0)
47
+ simplecov (0.22.0)
48
+ docile (~> 1.1)
49
+ simplecov-html (~> 0.11)
50
+ simplecov_json_formatter (~> 0.1)
51
+ simplecov-html (0.12.3)
52
+ simplecov_json_formatter (0.1.4)
53
+ unicode-display_width (2.4.2)
54
+
55
+ PLATFORMS
56
+ x86_64-darwin-22
57
+
58
+ DEPENDENCIES
59
+ bundler
60
+ byebug
61
+ rake
62
+ rspec
63
+ rubocop
64
+ schema_to_dbml!
65
+ simplecov
66
+
67
+ BUNDLED WITH
68
+ 2.4.4
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Ricardo Ribeiro
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Ricardo Ribeiro
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,94 @@
1
+ # SchemaToDbml
2
+
3
+ SchemaToDbml is a gem that generates a DBML (Database Markup Language) content from a Rails application schema.rb file. With SchemaToDbml, you can easily visualize your application's database schema in a clean and organized way.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'schema_to_dbml'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```ruby
16
+ $ bundle install
17
+ ```
18
+
19
+ ```ruby
20
+ $ gem install schema_to_dbml
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ To use the SchemaToDbml, first, create a schema.rb file for your Rails application by running:
26
+
27
+ ```ruby
28
+ $ rails db:schema:dump
29
+ ```
30
+ Then, you can use the SchemaToDbml to generate a DBML content from the schema.rb file:
31
+
32
+ ```ruby
33
+ require 'schema_to_dbml'
34
+
35
+ # Load configuration from default file
36
+ SchemaToDbml.configuration
37
+
38
+ dbml_content = SchemaToDbml.new.convert(schema: 'db/schema.rb')
39
+ puts dbml_content
40
+ ```
41
+
42
+ This will output the generated DBML content.
43
+
44
+ ## Custom Configuration
45
+
46
+ If you want to customize the DBML content, you can create a YAML configuration file with your desired properties.
47
+ By default, the SchemaToDbml will try to load the configuration from `schema_to_dbml/configs/custom_config.yml`.
48
+
49
+ Here's an example of the configuration file:
50
+
51
+ ```yaml
52
+ custom_project_name: 'My Project'
53
+ custom_database_type: 'PostgreSQL'
54
+ custom_project_notes: 'This is my project.'
55
+ custom_primary_key: 'id [pk]'
56
+ ```
57
+
58
+ You can change the properties as you want. After that, you can load the configuration by calling:
59
+
60
+ ```ruby
61
+ SchemaToDbml.load_configuration_from_yaml('/path/to/your/custom_config.yml')
62
+ ```
63
+
64
+ Or you can pass the configuration directly:
65
+
66
+ ```ruby
67
+ config = Configuration.new
68
+ config.custom_project_name = 'My Project'
69
+ config.custom_database_type = 'PostgreSQL'
70
+ config.custom_project_notes = 'This is my project.'
71
+ config.custom_primary_key = 'id'
72
+
73
+ SchemaToDbml.configure(config)
74
+ ```
75
+
76
+ After that, you can use the SchemaToDbml to generate the DBML content as usual.
77
+
78
+ ## Development
79
+
80
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
81
+
82
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
83
+
84
+ ## Contributing
85
+
86
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/schema_to_dbml. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/schema_to_dbml/blob/main/CODE_OF_CONDUCT.md).
87
+
88
+ ## License
89
+
90
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
91
+
92
+ ## Code of Conduct
93
+
94
+ Everyone interacting in the SchemaToDbml project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/schema_to_dbml/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Configuration
4
+ attr_accessor :custom_primary_key,
5
+ :custom_database_type,
6
+ :custom_project_name,
7
+ :custom_project_notes
8
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ class BuildDbmlContent
4
+ def initialize(configuration: SchemaToDbml.configuration)
5
+ @configuration = configuration
6
+ end
7
+
8
+ def build(converted:)
9
+ dbml = []
10
+ dbml << project_header
11
+ dbml << tables_section(converted[:tables])
12
+ dbml << relations_section(converted[:relations])
13
+
14
+ dbml.join("\n\n")
15
+ end
16
+
17
+ private
18
+
19
+ def project_header
20
+ header = "Project #{project_name} {\n"
21
+ header += " database_type: #{custom_database_type}\n"
22
+ header += " Note: '#{custom_project_notes}'\n"
23
+ header += '}'
24
+ header
25
+ end
26
+
27
+ def tables_section(tables)
28
+ tables.join("\n\n")
29
+ end
30
+
31
+ def relations_section(relations)
32
+ relations.join("\n\n")
33
+ end
34
+
35
+ def project_name
36
+ configuration.custom_project_name
37
+ end
38
+
39
+ def custom_database_type
40
+ configuration.custom_database_type
41
+ end
42
+
43
+ def custom_project_notes
44
+ configuration.custom_project_notes
45
+ end
46
+
47
+ attr_reader :configuration
48
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'helpers/constants'
4
+ require_relative './dbml_tables_formatter'
5
+ require_relative './dbml_relations_formatter'
6
+
7
+ class SchemaConverter
8
+ include Helpers::Constants
9
+
10
+ def initialize(
11
+ dbml_relations_formatter: DbmlRelationsFormatter.new,
12
+ dbml_tables_formatter: DbmlTablesFormatter.new
13
+ )
14
+ @dbml_relations_formatter = dbml_relations_formatter
15
+ @dbml_tables_formatter = dbml_tables_formatter
16
+ end
17
+
18
+ def convert(schema_content:)
19
+ tables = []
20
+ relations = []
21
+ schema_content.scan(TABLES_REGEXP).each do |table_name, table_comment, columns|
22
+ tables << dbml_tables_formatter.format(table_name:, table_comment:, parsed_columns: columns)
23
+ end
24
+
25
+ schema_content.scan(RELATIONS_REGEXP).each do |from_table, to_table, column, on_delete|
26
+ relations << dbml_relations_formatter.format(from_table:, to_table:, column:, on_delete:)
27
+ end
28
+
29
+ { tables:, relations: }
30
+ end
31
+
32
+ private
33
+
34
+ attr_reader :dbml_relations_formatter, :dbml_tables_formatter
35
+ end
@@ -0,0 +1,10 @@
1
+ custom_project_name: 'dbml_database_definition'
2
+ custom_database_type: "'PostgreSQL'"
3
+ custom_project_notes: |
4
+ # My Project Notes
5
+ This is a **project** that documents the database. Here are some key points:
6
+
7
+ - Utilizes the custom primary key for better indexing
8
+ - Specifies the appropriate database type (e.g., PostgreSQL)
9
+ - Provides meaningful project information and descriptions
10
+ custom_primary_key: "id integer [pk, unique, note: 'Unique identifier and primary key']"
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ class DbmlRelationsFormatter
4
+ # Formats a database relationship for a DBML file
5
+ #
6
+ # @param from_table [String] the table that has the foreign key
7
+ # @param to_table [String] the table being referenced
8
+ # @param column [String, nil] the name of the foreign key column; defaults to the singularized form of the to_table
9
+ # @param on_delete [String, nil] the delete behavior (e.g., "cascade"); optional
10
+ #
11
+ # @return [String] the formatted relationship string for a DBML file
12
+ def format(from_table:, to_table:, column: nil, on_delete: nil)
13
+ column ||= default_foreign_key_column(to_table)
14
+
15
+ ref_name = generate_reference_name(from_table, to_table, column)
16
+ ref = build_reference_string(ref_name, from_table, column, to_table)
17
+
18
+ ref += " [delete: #{on_delete}]" if on_delete
19
+ ref
20
+ end
21
+
22
+ private
23
+
24
+ def default_foreign_key_column(to_table)
25
+ "#{singularize(to_table)}_id"
26
+ end
27
+
28
+ def generate_reference_name(from_table, to_table, column)
29
+ ref_name = "fk_rails_#{from_table}_#{to_table}"
30
+ ref_name += "_#{column}" if column != default_foreign_key_column(to_table)
31
+ ref_name
32
+ end
33
+
34
+ def build_reference_string(ref_name, from_table, column, to_table)
35
+ "Ref #{ref_name}:#{from_table}.#{column} - #{to_table}.id"
36
+ end
37
+
38
+ # Singularizes a word
39
+ #
40
+ # @param word [String] the word to singularize
41
+ #
42
+ # @return [String] the singularized word
43
+ def singularize(word)
44
+ word.sub(/(?:([^aeiouy])y|s)$/, '\1').sub(/ies$/, 'y')
45
+ end
46
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'formatters/fields_formatter'
4
+ require_relative 'helpers/constants'
5
+
6
+ class DbmlTablesFormatter
7
+ include Helpers::Constants
8
+ include Formatters::FieldsFormatter
9
+
10
+ def initialize(configuration: SchemaToDbml.configuration)
11
+ @configuration = configuration
12
+ end
13
+
14
+ def format(table_name:, table_comment:, parsed_columns:)
15
+ columns = build_columns(parsed_columns)
16
+
17
+ format_dbml(table_name, columns, table_comment)
18
+ end
19
+
20
+ private
21
+
22
+ def build_columns(parsed_columns)
23
+ columns = []
24
+
25
+ parsed_columns.scan(COLUMNS_REGEXP).each do |type, name, default, null, comment, _precision, array|
26
+ formatted_comment = format_comment(comment:)
27
+ formatted_default = format_default(default:)
28
+ formatted_null = format_null(null:)
29
+ formatted_type = format_type(type:, array:)
30
+
31
+ final_values = [formatted_default, formatted_null, formatted_comment].compact.reject(&:empty?)
32
+ columns << build_line(name, formatted_type, final_values)
33
+ end
34
+
35
+ columns
36
+ end
37
+
38
+ def build_line(name, formatted_type, final_values)
39
+ line = " #{name} #{formatted_type}"
40
+
41
+ return line if final_values.empty?
42
+
43
+ line << " [#{final_values.join(',')}]"
44
+ end
45
+
46
+ def format_dbml(table_name, columns, table_comment)
47
+ dbml_table = "Table #{table_name} {\n"
48
+ dbml_table << " #{custom_primary_key}\n"
49
+ dbml_table << columns.join("\n")
50
+ dbml_table << "\n Note: '#{table_comment}'" unless table_comment.to_s.empty?
51
+ dbml_table << "\n}"
52
+ dbml_table
53
+ end
54
+
55
+ def custom_primary_key
56
+ configuration.custom_primary_key
57
+ end
58
+
59
+ attr_reader :configuration
60
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Errors
4
+ class SchemaFileNotFoundError < StandardError
5
+ def initialize(message = 'schema.rb file not found.')
6
+ super
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formatters
4
+ module FieldsFormatter
5
+ TYPE_MAPPER = {
6
+ string: 'varchar',
7
+ integer: 'int',
8
+ boolean: 'bool',
9
+ datetime: 'timestamp'
10
+ }.freeze
11
+
12
+ def format_type(type:, array:)
13
+ return '' if type.to_s.empty?
14
+
15
+ parsed = TYPE_MAPPER[type.to_sym] || type.to_s
16
+
17
+ return "#{parsed}[]" if array == 'true'
18
+
19
+ parsed
20
+ end
21
+
22
+ def format_default(default:)
23
+ return '' if default.to_s.empty?
24
+
25
+ "default: #{default}"
26
+ end
27
+
28
+ def format_null(null:)
29
+ return '' if null.to_s.empty?
30
+
31
+ 'not null'
32
+ end
33
+
34
+ def format_comment(comment:)
35
+ return '' if comment.to_s.empty?
36
+
37
+ "note: '#{comment}'"
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Helpers
4
+ module Constants
5
+ # rubocop:disable Layout/LineLength
6
+ TABLES_REGEXP = /create_table\s+"(?<table_name>\w+)"(?:,\s+comment:\s+"(?<comment>.*?)")?(?:,\s+force:\s+:cascade)?\s+do\s+\|t\|\n(?<table_content>.*?)end/m
7
+
8
+ COLUMNS_REGEXP = /t\.(?<type>\w+)\s+"(?<name>\w+)"(?:,\s+default:\s+(?<default>[^,\s]+))?(?:,\s+(?<null>null:\s+\w+))?(?:,\s+comment:\s+"(?<comment>[^"]+)")?(?:,\s+precision:\s+(?<precision>\d+))?(?:,\s+array:\s+(?<array>true|false))?.*/
9
+
10
+ RELATIONS_REGEXP = /add_foreign_key\s+"(?<from_table>\w+)",\s+"(?<to_table>\w+)"(?:,\s+column:\s+"(?<column>\w+)")?(?:,\s+on_delete:\s+:(?<on_delete>\w+))?/
11
+ # rubocop:enable Layout/LineLength
12
+ end
13
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'helpers/constants'
4
+ require_relative './dbml_tables_formatter'
5
+ require_relative './dbml_relations_formatter'
6
+
7
+ class SchemaConverter
8
+ include Helpers::Constants
9
+
10
+ def initialize(
11
+ dbml_relations_formatter: DbmlRelationsFormatter.new,
12
+ dbml_tables_formatter: DbmlTablesFormatter.new
13
+ )
14
+ @dbml_relations_formatter = dbml_relations_formatter
15
+ @dbml_tables_formatter = dbml_tables_formatter
16
+ end
17
+
18
+ def convert(schema_content:)
19
+ tables = []
20
+ relations = []
21
+ schema_content.scan(TABLES_REGEXP).each do |table_name, table_comment, columns|
22
+ tables << dbml_tables_formatter.format(table_name:, table_comment:, parsed_columns: columns)
23
+ end
24
+
25
+ schema_content.scan(RELATIONS_REGEXP).each do |from_table, to_table, column, on_delete|
26
+ relations << dbml_relations_formatter.format(from_table:, to_table:, column:, on_delete:)
27
+ end
28
+
29
+ { tables:, relations: }
30
+ end
31
+
32
+ private
33
+
34
+ attr_reader :dbml_relations_formatter, :dbml_tables_formatter
35
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class SchemaToDbml
4
+ VERSION = '0.0.1'
5
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require_relative 'configuration'
5
+ require_relative 'schema_to_dbml/build_dbml_content'
6
+ require_relative 'schema_to_dbml/errors/schema_file_not_found_error'
7
+ require_relative 'schema_to_dbml/schema_converter'
8
+ require_relative 'schema_to_dbml/version'
9
+
10
+ class SchemaToDbml
11
+ DEFAULT_CONFIG_FILE = File.join(__dir__, 'schema_to_dbml/configs/custom_config.yml')
12
+
13
+ class << self
14
+ def configuration
15
+ @configuration ||= begin
16
+ config = Configuration.new
17
+ load_configuration_from_yaml(DEFAULT_CONFIG_FILE, config)
18
+ config
19
+ end
20
+ end
21
+
22
+ def load_configuration_from_yaml(file_path, config = configuration)
23
+ raise 'Configuration file not found Error' unless File.exist?(file_path)
24
+
25
+ yaml_data = YAML.load_file(file_path)
26
+ configure(config) do |c|
27
+ c.custom_primary_key = yaml_data['custom_primary_key']
28
+ c.custom_database_type = yaml_data['custom_database_type']
29
+ c.custom_project_name = yaml_data['custom_project_name']
30
+ c.custom_project_notes = yaml_data['custom_project_notes']
31
+ end
32
+ end
33
+
34
+ def configure(config = configuration)
35
+ yield(config)
36
+ end
37
+ end
38
+
39
+ def initialize(
40
+ build_dbml_content: BuildDbmlContent.new,
41
+ schema_converter: SchemaConverter.new
42
+ )
43
+ @build_dbml_content = build_dbml_content
44
+ @schema_converter = schema_converter
45
+ end
46
+
47
+ def convert(schema:)
48
+ converted = schema_converter.convert(schema_content: schema_content(schema))
49
+
50
+ build_dbml_content.build(converted:)
51
+ end
52
+
53
+ private
54
+
55
+ def schema_content(schema)
56
+ raise Errors::SchemaFileNotFoundError unless File.exist?(schema)
57
+
58
+ File.read(schema)
59
+ end
60
+
61
+ attr_accessor :build_dbml_content, :schema_converter
62
+ end
@@ -0,0 +1,4 @@
1
+ module SchemaToDbml
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,154 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: schema_to_dbml
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Ricardo Ribeiro
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-05-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
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: byebug
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
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: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: simplecov
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
+ description: This gem provides functionality for parsing a Rails schema.rb file and
98
+ generating a corresponding DBML file.
99
+ email:
100
+ - ricardo.costa.ribeiro@gmail.com
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".rubocop.yml"
106
+ - CHANGELOG.md
107
+ - CODE_OF_CONDUCT.md
108
+ - Gemfile
109
+ - Gemfile.lock
110
+ - LICENSE
111
+ - LICENSE.txt
112
+ - README.md
113
+ - Rakefile
114
+ - lib/configuration.rb
115
+ - lib/schema_to_dbml.rb
116
+ - lib/schema_to_dbml/build_dbml_content.rb
117
+ - lib/schema_to_dbml/build_dbml_file.rb
118
+ - lib/schema_to_dbml/configs/custom_config.yml
119
+ - lib/schema_to_dbml/dbml_relations_formatter.rb
120
+ - lib/schema_to_dbml/dbml_tables_formatter.rb
121
+ - lib/schema_to_dbml/errors/schema_file_not_found_error.rb
122
+ - lib/schema_to_dbml/formatters/fields_formatter.rb
123
+ - lib/schema_to_dbml/helpers/constants.rb
124
+ - lib/schema_to_dbml/schema_converter.rb
125
+ - lib/schema_to_dbml/version.rb
126
+ - sig/schema_to_dbml.rbs
127
+ homepage: https://github.com/ricardojcribeiro/schema_to_dbml
128
+ licenses:
129
+ - MIT
130
+ metadata:
131
+ homepage_uri: https://github.com/ricardojcribeiro/schema_to_dbml
132
+ source_code_uri: https://github.com/ricardojcribeiro/schema_to_dbml
133
+ changelog_uri: https://github.com/ricardojcribeiro/schema_to_dbml/blob/main/CHANGELOG.md
134
+ rubygems_mfa_required: 'true'
135
+ post_install_message:
136
+ rdoc_options: []
137
+ require_paths:
138
+ - lib
139
+ required_ruby_version: !ruby/object:Gem::Requirement
140
+ requirements:
141
+ - - ">="
142
+ - !ruby/object:Gem::Version
143
+ version: 3.1.0
144
+ required_rubygems_version: !ruby/object:Gem::Requirement
145
+ requirements:
146
+ - - ">="
147
+ - !ruby/object:Gem::Version
148
+ version: '0'
149
+ requirements: []
150
+ rubygems_version: 3.3.7
151
+ signing_key:
152
+ specification_version: 4
153
+ summary: A Ruby on Rails gem for converting schema.rb files to DBML.
154
+ test_files: []