Skip to content

Instantly share code, notes, and snippets.

@Ajnasz
Last active November 26, 2021 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ajnasz/d4bb16b04166fd513b418f3aaad80bb0 to your computer and use it in GitHub Desktop.
Save Ajnasz/d4bb16b04166fd513b418f3aaad80bb0 to your computer and use it in GitHub Desktop.
# Convert mysql database scheme to typeorm entity for nestjs
# echo DESCRIBE some_db.some_table | mysql -some-login-credentials | gawk -f entity-generator.awk
function get_type_name(s) {
if (s ~ /\)$/) {
sub(/\(.+\)$/, "", s)
return s
}
return s
}
function get_type_len_args(s, _type_params) {
if (s ~ /\)$/) {
match(s, /([0-9]+)(,([0-9]+))?/, ary)
_type_params[0] = int(ary[1])
_type_params[1] = int(ary[3])
return
}
_type_params[0] = -1
}
function camelcase(s) {
out = ""
to_upper = 0
for (i = 1; i <= length(s); i++) {
letter = substr(s, i, 1)
if (letter == "_" || letter == "-") {
to_upper = 1
continue
}
if (to_upper == 1) {
out = out toupper(letter)
to_upper = 0
} else {
out = out letter
}
}
return out
}
NR > 1 {
field = $1
type = get_type_name($2)
get_type_len_args($2, type_params)
len = type_params[0]
fieldname = field
if (field == "pk") {
fieldname = "id"
printf "@PrimaryGeneratedColumn({ name: '"field"' })\n"
} else if (len == -1) {
printf "@Column({ name: '"field"', type: '"type"' })\n"
} else if (type == "int" || type == "tinyint") {
printf "@Column({ name: '"field"', type: '"type"', width: "len" })\n"
} else if (type == "decimal") {
printf "@Column({ name: '"field"', type: '"type"', precision: "len", scale: "type_params[1]" })\n"
} else {
printf "@Column({ name: '"field"', type: '"type"', length: "len" })\n"
}
fieldname = camelcase(fieldname)
ornull = ""
if ($3 == "YES") {
ornull = " | null"
}
if (type == "timestamp") {
printf(fieldname": Date"ornull";\n")
} else if (type == "int" || type == "tinyint" || type == "decimal") {
printf(fieldname": number"ornull";\n")
} else {
printf(fieldname": string"ornull";\n")
}
printf("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment