Skip to content
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

Add helper Args() []interface function to get all builder arguments #134

Closed
wants to merge 2 commits into from

Conversation

0x9ef
Copy link

@0x9ef 0x9ef commented Nov 28, 2023

The main goal of this function is to provide a helper function to get all builder arguments like with String() string function.

Why did I come up with this solution? If you use Struct builder with omitempty tags and also you use WHERE clause you may get into a trap when you don't have any update arguments, but you have arguments in WHERE clause:

UPDATE s_table WHERE id = $1; # will get an error

To solve this problem and to understand if you really have arguments in the update part, you should build statement and then check if len(args) != 0 before WHERE statement.

func main() {
	toUpdate := S{} // empty fields
	b := ss.Update("s_table", toUpdate)
	q, args := b.Build()
	if len(args) != 0 {
		// Process this update
	}
}

But it would be more convenient to use Args function:

type S struct {
	ID   int    `db:"id" fieldopt:"omitempty"`
	Name string `db:"name" fieldopt"name"`
}

var ss = sqlb.NewStruct(new(S))

func main() {
	p := S{}
	ub := ss.Update("s_table", p)

	if len(ub.Args()) != 0 {

	}
}

Also, I understand that there is a good chance to implement a cache builder mechanism to prevent building every time we call String() string or Args() []interface methods. But at the time I don't have enough information to implement this.

@huandu
Copy link
Owner

huandu commented Nov 29, 2023

I get your point. I can implement a new method to return how many struct fields will be used in builds after calling WithTag and WithoutTag.

Regarding to this PR, it's not correct to implement Args like this. The args, which is returned by Build, can include all args in WHERE clause as well.

@huandu
Copy link
Owner

huandu commented Nov 30, 2023

@0x9ef I submit a commit a5eff69 to add new methods like UpdateBuilder.NumAssignment() which returns the number of assignments in UpdateBuilder. With this value, you can easily check whether an UpdateBuilder has any assignment.

I'll wait for your feedback for at least one day before I make a new release. If you have any suggestion on this design, it's highly appreciated. You can review the diff in a5eff69 and leave message in this PR or in commit. Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants