bun
bun copied to clipboard
[HELP WANTED] Dynamic insert based on scheme
Hello, is it possible to do dynamic inserts with Bun? Unfortunately I can't find anything in the documentation.
I imagine the following, which I know from other JS frameworks:
- given is the table name. Based on this I get the schema of the table
- the schema of the table contains all fields including their data types as well as if it is an association etc.
- now I can build my insert dynamically on it.
Does Bun support this? Commands how to get the schema would be very helpful.
The idea is to make it as dynamic as possible without having to know the model.
Thanks in Advance Nils
The closes thing Bun has is support for map[string]interface{}
- see https://bun.uptrace.dev/guide/query-insert.html#maps
@vmihailenco Thank you! But how do I know what the interface looks like?
So I only know the table name.
Most likely Bun does not a solution for this problem, but I can't say I understand your description well enough. Do you have an example of other projects that tried to solve this problem before?
Unfortunately, not a public one.
The idea is to generate data quite dynamically.
Let's assume I have the table "User". This consists of: id: String, name: String, age: Int
Now, for example, for the simple generation of test data, I want to give only the table name "User" as well as the ID as a field to my rest point.
A post request could for example look like this: { "tableName": "User", "values": [ {"id": "ABC"} ] }
Now the program should automatically read the table User, know that there are still the fields name and age and generate them independently. For ID the given ID should be used. The generation of data is no problem.
But for this I need to know how the table schema is. In other projects with JS the ORM framework could give me exactly this information. Of course you could add the table schema manually. But the goal would be to have a completely dynamic implementation, which can be used in every project.
I hope it is now more understandable.
@nilskasseckert When does the generation of data would occur ? If it is when you insert data into the table, then you can set default values for each column of your table directly in your schema / table definition.
If you need those fields in your Go struct before doing an insert, then maybe you could, at your application startup, insert a dummy struct instance in your DB to capture the default values, and store that struct in a global variable. When you need to process a new instance, you can copy fields from the global variable as needed.
Something like
var defaultUser User
func init() {
db.NewSelect().Model(&defaultUser) // pseudo-code.... the idea here is to get the default values in defaultUser
}
func someHandler(w, r) {
user := User{}
// copy values from defaultUser as needed into user
Not sure if this fits your need, I was just passing by...