Gorm (Golang) and database with Single Table Inheritance "type" column - go

I'm experimenting with using Go to read from a database that's been part of an existing Rails app. A few of the models and therefore tables use single table inheritance via a type column. In Rails/ActiveRecord, the presence of this column will create an automatic mapping to the appropriate model. If the table is animals and type is Dog, it will map to the Dog class; if it's Cat, it'll map to the Cat class. I want to setup something similar in Gorm.
Since it doesn't seem like Gorm has a default_scope option for a model, I'm using a new callback.
func scopedSearch(scope *gorm.Scope) {
tablename := scope.TableName()
switch tablename {
case "table_using_sti":
scope.Search.Where("type = ?", "MyModelName")
default:
return
}
}
And then I register the callback in my main function:
db.Callback().Query().Before("gorm:query").Register("my_plugin:before_query", scopedSearch)
When I search against an instance using db.First or the model using db.Model(&MyModel{}).Where(...), it appears to be working. Is this the right way to handle it? Will this scope be respected by all of the query methods or is there something more direct or thorough?

Related

How to prevent Child models from Deletion in Golang GORM?

Well, I would like to know, Is there any solutions, how to prevent Child Model from deletion in foreignKey Constraint, (
For example in gorm there is a couple of options that allows to restrict behavior of the Parent Model after deletion, and Delete or Set to Null the Child Model Objects That has foreignKey relation (onDelete: Cascade / Set Null, and the same thing for onUpdate)
// Pretty a lot of the same words, but I hope you got it :)
Little Example.. from Golang ...
type SomeOtherStruct struct {
gorm.Model
Id int
}
type SomeModel struct {
gorm.Model
someOtherStructId string
someField SomeOtherStruct `gorm:"foreignKey:SomeOtherStructId; OnDelete:Cascade,OnUpdate: SET NULL"` // basically foreign Key Relationship to model `SomeOtherStruct`
}
But I would like to prevent any Update/Deletion behavior, so Child Relation Models Objects won't get deleted after the Parent Model Object has been..
There is actually a concept from Django Framework (Python)
class SomeModel(models.Model):
some_field = models.ForeignKey(to=AnotherModel, verbose_name="SomeField", on_delete=models.PROTECT)
class AnotherModel(models.Model):
pass
As you can see, there is models.PROTECT constraint, that is basically what I'm looking for....
Is there any analogy for that in Golang GORM or some RAW SQL for that as well?
Thanks..
Unfortunately, you didn't mention which database you are using.
In Postgres (as an example) there are multiple options for ON DELETE:
NO ACTION
RESTRICT
CASCADE
SET NULL
SET DEFAULT
Only CASCADE will delete children if the parent is deleted. All other options (including the default NO ACTION) will make sure the children will "survive".
You can find more information in the postgres documentation: https://www.postgresql.org/docs/current/sql-createtable.html
Please feel free to update your question and/or comment with the database you are using.

Go gorm creating many to many relationship using customised table and extra data

I am trying to achieve a join between two models using gorm and a customised table. On this customised table I would like to store extra information about the joined models.
As per the docs I have the following,
func init() {
database.DB.SetupJoinTable(&Foo{}, "Bar", &FooBar{})
}
type Foo struct {
UUID uuid.UUID `json:"uuid" gorm:"type:uuid;primaryKey;"`
SomeValue string `json:"someValue"`
Bars []Bar `json:"bars" gorm:"many2many:foo_bars"`
}
type Bar struct {
UUID uuid.UUID `json:"uuid" gorm:"type:uuid;primaryKey;"`
SomeValue string `json:"someValue"`
}
type FooBar struct {
FooUUID uuid.UUID `json:"foo" gorm:"primaryKey"`
BarUUID uuid.UUID `json:"bar" gorm:"primaryKey"`
ExtraValue string `json:"extraValue"`
}
The above creates a schema as I would expect. The problem is when trying to persist this relationship and set extra data needed to FooBar. The docs provide documentation on appending relationships directly from Foo to Bar, but not adding data to this customised table.
The documentation states:
JoinTable can be a full-featured model
So I would expect this to be possible.
Is this possible using gorm?
How can I create and save this relationship with additional information?
This is actually very simple, the fact that FooBar is a full-featured model means you can use it to interact with the join table directly the same way that any other model can:
// assuming we have a Foo foo and Bar bar
// read
links := []FooBar{}
db.Where(FooBar{FooUUID: foo.UUID, BarUUID: bar.UUID}).Find(&links)
// create
link := FooBar{FooUUID: foo.UUID, BarUUID: bar.UUID, ExtraValue: "foobar"}
db.Create(&link)
// update
link.ExtraValue = "foobarbaz"
db.Save(&link)
// delete
db.Delete(&link)
But to do all this requires you to treat the join table as a separate model. For example you shouldn't expect to be able to extract the ExtraValue when doing regular Associations operations on Foo, because there is literally no space on the []Bar field to put the value. Similar goes for saving the ExtraValue, unless you do some special trickery with Hooks (see this answer for more on this).

How to search on a many-to-many field

Let's assume I have the below structs
type Job struct {
ID string `sql:"type:uuid;primary_key;"`
Title string `json:"title,omitempty"`
Skills []*skill.Skill `json:"skills,omitempty"gorm:"many2many:job_skill;"`
}
type Skill struct {
Name string `json:"name" gorm:"primary_key"`
}
To query all the jobs I do:
jobs := &[]Job{}
gorm.DB.Preload("Skills").Find(&jobs)
How do I search for a Job that contains a certain skill? I have tried the below but it says the column does not exist.
s := "golang"
jobs := &[]Job{}
gorm.DB.Preload("Skills").Where("skill = ?", s).Find(&jobs)
I can see my issues, = doesn't seem to be the correct operator as it needs to search in a list. And it also isn't loading the join table as I assumed it would
Debug output
pq: column "skill" does not exist
SELECT * FROM "jobs" WHERE skill = 'golang'
The Preload method and the Associations feature help you load your fields by constructing basic SQL queries based on the relationships you have created. Queries like loading all skills for a specific job (or jobs). But it doesn't go any more complex than that.
Rather, think of go-gorm as a way to construct your SQL queries and load the data into your models.
Having that in mind, one solution would be to use Joins to include the skill table.
gorm.DB.Preload("Skills")
.Joins("INNER JOIN job_skill js ON js.job_id = jobs.id").
.Joins("INNER JOIN skill s ON s.id = js.skill_id").
.Where("s.name = ?", s).Find(&jobs)

How do I query an optional column with a secondary index using phantom?

I have a secondary index on an optional column:
class Sessions extends CassandraTable[ConcreteSessions, Session] {
object matchId extends LongColumn(this) with PartitionKey[Long]
object userId extends OptionalLongColumn(this) with Index[Option[Long]]
...
}
However, the indexedToQueryColumn implicit conversion is not available for optional columns, so this does not compile:
def getByUserId(userId: Long): Future[Seq[Session]] = {
select.where(_.userId eqs userId).fetch()
}
Neither does this:
select.where(_.userId eqs Some(userId)).fetch()
Or changing the type of the index:
object userId extends OptionalLongColumn(this) with Index[Long]
Is there a way to perform such a query using phantom?
I know that I could denormalize, but it would involve some very messy housekeeping and triple our (substantial) data size. The query usually returns only a handful of results, so I'd be willing to use a secondary index in this case.
Short answer: You could not use optional fields in order to query things in phantom.
Long detailed answer:
But, if you really want to work with secondary optional columns, you should declare your entity field as Option but your phantom representation should not be an option in order to query.
object userId extends LongColumn(this) with Index[Long]
In the fromRow(r: Row) you can create your object like this:
Sessions(matchId(r), Some(userId(r)))
Then in the service part you could do the following:
.value(_.userId, t.userId.getOrElse(0))
You also have a better way to do that. You could duplicate the table, making a new kind of query like sessions_by_user_id where in this table your user_id would be the primary key and the match_id the clustering key.
Since user_id is optional, you would end with a table that contains only valid user ids, which is easy and fast to lookup.
Cassandra relies on queries, so use it in your favor.
Take a look up on my github project that helps you get up with multiple queries in the same table.
https://github.com/iamthiago/cassandra-phantom

Table with a foreign key

how can I build a table of "orders" containing "IdOrder", "Description" and "User"?... the "User" field is a reference to the table "Users", which has "IdUser" and "Name". I'm using repositories.
I have this repository:
Repository<Orders> ordersRepo = new OrderRepo<Orders>(unitOfWork.Session);
to return all Orders to View, I just do:
return View(ordersRepo.All());
But this will result in something like:
IdOrder:1 -- Description: SomeTest -- User: UserProxy123ih12i3123ih12i3uh123
-
When the expected result was:
IdOrder:1 -- Description: SomeTest -- User: Thiago.
PS: I don't know why it returns this "UserProxy123ih12i3123ih12i3uh123". In Db there is a valid value.
The View:
It is showed in a foreach (var item in Model).
#item.Description
#item.User //--> If it is #item.User.Name doesn't work.
What I have to do to put the Name on this list? May I have to do a query using LINQ - NHibernate?
Tks.
What type of ORM are you using? You mention "repositories" but does that mean LinqToSql, Entity Framework, NHibernate, or other?
It looks like you are getting an error because the User field is not loaded as part of the original query. This is likely done to reduce the size of the result set by excluding the related fields from the original query for Orders.
There are a couple of options to work around this:
Set up the repository (or context, depending on the ORM) to include the User property in the result set.
Explicitly load the User property before you access it. Note that this would be an additional round-trip to the database and should not be done in a loop.
In cases where you know that you need the User information it would make sense to ensure that this data in returned from the original query. If you are using LinqToSql take a look at the DataLoadOptions type. You can use this type to specify which relationships you want to retrieve with the query:
var options = new DataLoadOptions();
options.LoadWith<Orders>(o => o.User);
DataContext context = ...;
context.LoadOptions = options;
var query = from o in context.Orders
select o;
There should be similar methods to achive the same thing whatever ORM you are using.
In NHibernate you can do the following:
using (ISession session = SessionFactory.OpenSession())
{
var orders = session.Get<Order>(someId);
NHibernateUtil.Initialize(orders.User);
}
This will result in only two database trips (regardless of the number of orders returned). More information on this can be found here.
In asp.net MVC the foreign key doesn't work the way you are using it. I believe you have to set the user to a variable like this:
User user = #item.User;
Or you have to load the reference sometimes. I don't know why this is but in my experience if I put this line before doing something with a foreign key it works
#item.UserReference.load();
Maybe when you access item.User.Name the session is already closed so NHib cannot load appropriate user from the DB.
You can create some model and initialize it with proper values at the controller. Also you can disable lazy loading for Orders.User in your mapping.
But maybe it is an other problem. What do you have when accessing "#item.User.Name" from your View?

Resources