Nullablity of DB generated attributes - orm

I'm working in a Kotlin based project and It force me to deal with any attribute that possibly can hold null. It's nice to find out somewhere nulls are possible while they are not welcome; but I see so much of ?.s and .!!s for attributes that DB generates, e.g. IDs. Maybe I'm abusing that operators?
Is there any convention to mark attribute as not nullable but still have DB generated values here? If I lookup an object It's safe to assume DB generated values are not null anymore. Can VM be made known to this? Maybe by framework or some annotations that language provide?

If your id is generated by the database it is nullable since the JVM/compiler/IDE has no way to know if your entity is already persisted or not.
What you could do though is implement additional methods that are guaranteed to return non-null values by throwing an exception otherwise.

Related

Why use sql tags in struct in some go libs like gorm?

Well I know the necessity of tags in struct in golang and how is it accessed by reflect in golang. But I have searched and could not find a reliable answer to the question of why I should use sql tags in struct while writing struct for sql results. I have explored many sample code and people are using sql:"index" in the struct and sql:"primary_key" in the struct.
Now I have done indexing in the database layer, isn’t it enough? Should I have to use sql:"index" too get the best results? Like so I have defined primary key attribute in the database should I have to specify sql:"primary_key" as well?
My code seems to work fine without those. Just want to know their benefit and usages.
I think you are referring to an ORM library like gorm
In that case, metadata like sql:"primary_key" or sql:"index" will just tell the ORM to create an index while trying to setup the tables or maybe migrate them.
A couple of examples in gorm could be: indexes, primary keys, foreign keys, many2many relations or when trying to adapt an exiting schema into your gorm models, setting the type explicitly, like for example:
type Address struct {
ID int
Address1 string `sql:"not null;unique"` // Set field as not nullable and unique
Address2 string `sql:"type:varchar(100);unique"`
Post sql.NullString `sql:"not null"`
}
Depends on the package you are using and your use-case. Is it enough for CRUD? Almost always, unless the package says so which is often rare but possible. Few packages sometime do under the hood magic which may give rise to bugs. If you are aware of these behaviours, or are quite explicit in your code, you'll probably avoid it.
Indexing tags mostly allows you to use package's migration tools translating your model declaration into sql queries (CREATE statements). So if you always want to do this by yourself, then you probably needn't bother adding such tags.
But you may find yourself a bug if your package requires a tag. For example, in case of gorm, the Model method takes a struct pointer as an input. If this struct has a field named ID it uses it as a primary key, that is, say ID has a value of "4", it will add a WHERE id=4 automatically. In case your struct has ID, you needn't even add a primary_key tag and it will still be treated as one. This behaviour may cause issues when you have both a "non-primary-key" ID field, and another field which you are actually using as the primary key. Another example for gorm is this. A possible behaviour can also be checking for nullable property and throwing an error if an INSERT statement involves a NOT NULL field getting a NULL value.
On a different note, adding tags to your structs can be considered good practice since it gives context of its properties in the DB.

IndexedDB - Do I need an "id" field?

After reading several tutorials I still have problems understanding IndexedDB completely...
I already build a "playground-app" with it, but I have a question before continuing....
Is it recommended to have a distinct "id" field in the ObjectStores?
What happens if object at index 42 (without id-field) needs to be updated? [From what I know IndexedDB doesn't have an update command.] How would you exchange/update this object in-place without breaking the references to this objects?
When you have a id-field - How to find a unused id-value when you add a new object to an ObjectStore? Is there a clever way to do it?
I couldn't find a discussion about this on SO or somewhere else...
cheers!
Using an id is not required but is recommended because it simplifies writing your program. This advice applies to traditional relational databases (SQL) and indexedDB (NoSQL).
Using a simple integer counter is helpful and recommended, even when you have another property or group of properties (a composite/compound primary key) that uniquely identifies each object in a store.
indexedDB provides a way to generate 'unused' id values. Use the autoincrement flag when calling createObjectStore and setting the key path.
See the MDB documentation to learn more. Specifically, review the section on object store keys.
In regards to the 42 question, you can open a cursor, then advance the cursor by 42, and then retrieve the value, change its properties, and then, if the underlying transaction is in readwrite mode, you can call cursor.update to replace the object at the cursor's position. Using this technique is not recommended primarily because it is not practical and can be confusing. It is preferable to use a simple auto-incremented integer id, especially when you are just learning.
It does not matter what the name of the property that represents the key is, so long as it conforms to normal JavaScript object property naming rules, and you access it consistently.

Entity framework map column only if it exists

I am trying to find a way to only populate a property of my entity class, if the column exists in the query?
When I execute a query using DbSet.SqlQuery and returning the column (which is an alias) populated, everything is fine. But when using the built in functionality such as All(), Find(), ToArray() etc, it expects that column to be in the dataset.
Is there a way (without having to write all of the supporting queries manually) to mark a property in my entity class, as optional.
It is currently marked as a nullable DateTime but the framework still complains it does not exist when using the built in functionality.
Any suggestions would be great!
Cheers
No, because they have to build the SQL query. It doesn't matter if a column is nullable or not, what matters is that when they build the query, if that column does not exist, then the database will likely throw an error complaining that the column does not exist.
The only way around it is to not map it, or to query the schema when mapping and conditionally map the property (though I wouldn't recommend that).

Best way to map a hidden property in NHibernate (fluent)

I know this question could lead to a subjective answer, but I'd like to get an opinion from someone else.
Some background
Currently I have a class that maps a private string property to a geometry column in a PostgreSQL (PostGIS) database table along with a public string for WKT. The WKT is used by PostGIS to automatically update the geometry column, using a trigger. As I don't want to include any spatial references in my domain model, all querying is done using WKT strings and a custom spatial criterion, which wraps the WKT in a spatial PostGIS function and queries the private geometry property column reference. All of this works as expected.
The question
Since I need the column reference, I also need the property in my domainmodel, for NHibernate to map to, so I was wondering, what the best solution would be, for NHibernate to never select this property.
My current solution looks as follows with Fluent NHibernate:
Map(Reveal.Member<LocationReference>("Geometry"), "geometry")
.Generated.Always()
.ReadOnly()
.LazyLoad();
This does the trick, and when I select the entity, I won't get the property, unless I manually load it (which isn't possible through the lambda extensions). Unfortunately I would still be able to do a Criteria or HQL query for the property.
So are there any ways for me to do anything that prevents NHibernate from being able to do ever include the column in a select? Or is the above solution the only way to at least ignore the column when selecting with Query<> or QueryOver<>?
Well, I ended up removing the mapped property, because, even though it was lazy, NHibernate would sometimes load it anyway. What I did was actually a bit of a hack. I needed the alias for a property from the same class, so I used the mapping from another property and split the SqlString on '.', to get the correct alias.
All of this makes perfect sense to me, and the "workaround" is not nice, but I don't see any other way of doing it. NHibernate needs to know, what property it's dealing with, to assign proper aliases. Since I'm not mapping the property, it has no way of knowing, what alias I'm looking for.
I guess I'm doing a lot of hacking, just to avoid having to reference NHibernate.Spatial...

Hibernate and IDs

Is it possible in hibernate to have an entity where some IDs are assigned and some are generated?
For instance:
Some objects have an ID between 1-10000 that are generated outside of the database; while some entities come in with no ID and need an ID generated by the database.
You could use 'assigned' as the Id generation strategy, but you would have to give the entity its id before you saved it to the database. Alternately you could build your own implementation of org.hibernate.id.IdentifierGenerator to provide the Id in the manner you've suggested.
I have to agree w/ Cade Roux though, and doing so seems like it be much more difficult than using built in increment, uuid, or other form of id generation.
I would avoid this and simply have an auxiliary column for the information about the source of the object and a column for the external identifier (assuming the external identifier was an important value you wanted to keep track of).
It's generally a bad idea to use columns for mixed purposes - in this case to infer from the nature of a surrogate key the source of an object.
Use any generator you like, make sure it can start at an offset (when you use a sequence, you can initialize it accordingly).
For all other entities, call setId() before you insert them. Hibernate will only generate an id if the id property is 0. Note that you should first insert objects with ids into the db and then work with them. There is a lot of code in Hibernate which expects the object to be in the DB when id != 0.
Another solution is to use negative ids for entities which come with an id. This will also make sure that there are no collisions when you insert an new object.