Skip to content

feat: Generate DB unique constraints as enums #3701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 29, 2022
Merged

Conversation

mafredri
Copy link
Member

@mafredri mafredri commented Aug 26, 2022

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
Copy link
Member

@johnstcn johnstcn left a comment

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
Copy link
Member

Emyrk commented Aug 26, 2022

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