Skip to content

feat: Generate DB unique constraints as enums - #3701

Merged
mafredri merged 6 commits into
mainfrom
mafredri/gen-db-enums
Aug 29, 2022
Merged

mafredri merged 6 commits into
mainfrom
mafredri/gen-db-enums

Conversation

@mafredri

@mafredri mafredri commented Aug 26, 2022 •

Copy link
Copy Markdown
Member

This fixes a TODO from #3409.

  • feat: Generate DB unique constraints as enums
  • chore: Move dump to gen/dump, update Makefile

I started out with a bash script, but ultimately I think writing this in Go will be more extensible in the future.


For reference, Bash:

	# Generate unique constraint enums.
	cat <<EOF >unique_constraint.go
// Code generated by generate.sh. DO NOT EDIT.
package database

// UniqueConstraint represents a named unique constraint on a table.
type UniqueConstraint string

// UniqueConstraint enums.
const (
EOF
	cat dump.sql | tr $'\n' ' ' | sed -e 's/\s\+/ /g' | tr ';' $'\n' | grep UNIQUE | while read -r line; do
		line=${line# } # Remove empty line at the beginnig.
		case "$line" in
		*"ALTER TABLE"*"ADD CONSTRAINT"*)
			name=$(awk '{print $7}' <<<"$line")
			;;
		*"CREATE UNIQUE INDEX"*)
			name=$(awk '{print $4}' <<<"$line")
			;;
		esac
		printf "\tUnique%s UniqueConstraint = \"%s\" // %s;" "$name" "$name" "$line"
	done >>unique_constraint.go
	echo ")" >>unique_constraint.go

@mafredri mafredri self-assigned this Aug 26, 2022
@mafredri
mafredri requested a review from a team August 26, 2022 09:46

@johnstcn johnstcn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍
Noting that this is also possible by querying the postgres catalog, but the downside is then that we can't make those nice comments that show the query where the line was added.

@Emyrk

Emyrk commented Aug 26, 2022

Copy link
Copy Markdown
Member

Would be nice to somehow combine it with the apitypings/main.go. Like some sort of gen/main.go that calls both go generators. Just to keep all go generators under the same main.go

@mafredri
mafredri merged commit dc9b415 into main Aug 29, 2022
@mafredri
mafredri deleted the mafredri/gen-db-enums branch August 29, 2022 11:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants