Created
December 13, 2022 14:11
-
-
Save thiagozs/e4f8d93123da5ccf341bf31480d2c22e to your computer and use it in GitHub Desktop.
Golang regexp parse schema.rb ruby database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"regexp" | |
) | |
func main() { | |
schema := ` | |
ActiveRecord::Schema.define(version: 2022_12_05_175521) do | |
# These are extensions that must be enabled in order to support this database | |
enable_extension "btree_gin" | |
enable_extension "hstore" | |
enable_extension "pg_stat_statements" | |
enable_extension "pg_trgm" | |
enable_extension "plpgsql" | |
enable_extension "uuid-ossp" | |
create_table "users" force: :cascade do |t| | |
t.string "name" | |
t.string "email" | |
t.string "password_digest" | |
end | |
create_table "posts" force: :cascade do |t| | |
t.integer "user_id" | |
t.string "title" | |
t.text "body" | |
end | |
end | |
` | |
regex := regexp.MustCompile("(?s)(create_table|table)\\s+\"(.*?)\".*?t.(.*?)\\s*end") | |
matches := regex.FindAllStringSubmatch(schema, -1) | |
for _, match := range matches { | |
for i, field := range match { | |
typo := "Match" | |
if i > 0 { | |
typo = "Field" | |
} | |
fmt.Printf("(%s) %d: %s\n", typo, i, trimSpaces(field)) | |
} | |
} | |
} | |
func trimSpaces(s string) string { | |
re := regexp.MustCompile(`[\t|\s]+`) | |
return re.ReplaceAllString(s, " ") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment