SQLite CREATE table with an alias for ROWID - android

Looking at this answer I was trying to work out how to actually create a table with a column that is just an alias for ROWID. I would like to do this as some android classes require a unique column named '_id' but i dont want that col to be a PRIMARY KEY. I cant use AUTO_INCREMENT on the col that not a PK either, so I would just like _id to be an alias. I know I could do that in the query but thats not practical for my situation. Any pointers? Is this even possible?
Thanks :)
EDIT: really i just want to be able to have my own PK but also have an id field for CursorAdapters to work correctly etc
EDIT: Looking at Do i have to use _ID as a SQlite primary key? and does it have to be an INT? (Android Dev) it suggests to do it in the query if my PK is a number type also, but what if its a TEXT col that im using for my PK? (sort of thinking aloud here) - I guess i could copy CursorAdaptor and just getString instead of a long for the _id col (plus, pass the name of the col to use as the PK in to cursor adapter, get rid of _id!) OR just add a alias for the ROWID as _id in the SELECT, feels a bit hacky though...

You may have a primary key that is completely independent of SQLite's built-in rowid.
Every row of every SQLite table has a 64-bit signed integer key that uniquely identifies the row within its table. This integer is usually called the "rowid". The rowid value can be accessed using one of the special case-independent names "rowid", "oid", or "rowid" in place of a column name.
You may formulate your query so that the built-in rowid is called _id for the benefit of the CursorAdaptor by prepending the hidden rowid column to your results:
select _rowid_ as _id, ...
The rowid is unique, but need not be the primary key. You can make the primary key anything you like in the CREATE TABLE statement.

TBH, I don't think that this is really feasible. You are required to have that kind of PK column (even though with a lot of hacking you could create some kind of workaround).
I would rather suggest to have the _id column as a technical PK and have an additional column as logical PK i.e. just a freely defined column with a unique constraint. Your program logic should then be able to simply use the logical PK for all operations. Of course this would require you to use custom queries for find operations etc. but that is usually more fitting anyways.
hth..

Related

Get/Return the autogenerated id (as primary key) generated by Android Room database

For an android room interface, I want to get the autogenerated id (as primary key of a record just inserted), so that I can put it in the object without executing a select after insert, where the select might return the wrong record if there is no other unique attribute, or set of attributes for those record types.
For example, for 2 people having the same name being inserted into the same table. You might say generate a composite key to make a unique set. However that might involve the addition of new fields that are otherwise not required.
I've seen various links, including those below. Some mention that it is the row id that is returned if the insert method is declared to return integer (or long), and succeeds.
However it is my understanding that the row id cannot be assumed to be the same as the primary key. (Refer Rowid after Insert in Room).
I cannot comment on any posts because I don't have enough reputation points.
I appreciate any comments regarding what might be a good/typical approach to this problem.
These are the posts I have looked upon:
Android Room - Get the id of new inserted row with auto-generate
https://developer.android.com/training/data-storage/room/accessing-data
https://commonsware.com/AndroidArch/previews/the-dao-of-entities
Late answer just for anyone seeing this question in the future
from SQLite docs it says :
The PRIMARY KEY of a rowid table (if there is one) is usually not the
true primary key for the table, in the sense that it is not the unique
key used by the underlying B-tree storage engine. The exception to
this rule is when the rowid table declares an INTEGER PRIMARY KEY. In
the exception, the INTEGER PRIMARY KEY becomes an alias for the rowid.
therefore it's correct to assume that the rowId returned by insert query is the same as the autoincremented-primary-key

New to Android - Is _id a must for databases?

I have an already functioning app running on iOS whose database uses a composite primary key. For discussions sake, lets say "CID" and "RID" make up that composite pk, resulting in something that looks like:
CID-RID
F6uuDTEU1c-1
F6uuDTEU1c-2
F6uuDTEU1c-3
However, there are conditions under which the CID column is altered, resetting the RID column. For example:
CID-RID
...
F6uuDTEU1c-4
F6uuDTEU1c-5
WQq6JnyrDI-1
WQq6JnyrDI-2
WQq6JnyrDI-3
...etc
These databases are to be shared cross-platform (ios - android) and going back and editing the current ios structure is not an option. What issues am I going to run into not having an _id column as my pk running on Android?
I found this here on SO - which seems to state that the db itself does not have to have the _id column, only that ...
"The result set for the cursor must contain _id, not the cursor itself."
... but I could be reading this all wrong. Any input/help is much appreciated.
PS: I already looked at a few (what I thought were) similar questions here, here, and here.
You are free to have any database schema you want. Android doesn't impose any additional restrictrions there.
Only if you use a CursorAdapter, then the Cursor needs an _id column. Any app can be written without using CursorAdapter, it's just there to provide some convenience. sqlite tables always have a ROWID column that aliases to the INTEGER PRIMARY KEY column if the table has one. You can always select it as the _id, e.g. SELECT rowid AS _id ... if needed.

SQLite insert record with _id value for two or more fields

I have a case that I would like to insert record in SQLite with database.insert(table, null, values).
TABLE t2 (_id, field1, field2)
..
val.setVal1(null);
val.setVal2(val2);
..
if(val.getVal1==null){
values.put(field1, _id);
}else{
values.put(field1, var.val1);
}
values.put(field2, var.val2);
database.insert("t2", null, values);
Is possible to do sth like this "values.put(field1, _id);"?
_id is generated at database.insert().
Note: I am looking for solution for one insert call. Insert and update row with (field1=_id) is easy.
i think i see now. you're asking if you can enter a value into a specific SQLite row _id field if it's available in your val object. Else, you want the database to automatically create a unique id for that column while inserting, like normally done. Is this correct?
To that end, i would seriously reconsider this purpose. You should never be specifying values for the _id column because it needs to be unique or else you'll get exceptions thrown. Moreover, it's only purpose is to be a unique identifier for the system, so you personally knowing this value should be of no use to you.
If you still need this functionality, i'd suggest making another field in your table (much like the _id column but not it), which you can fill with randomly generated numbers or val.getVal1 values.

Android SQLite dilemma

I want to increase my integer primary key by 1 for every new entry in a specific table. I read that i could do that by using AUTOINCREMENT. On the other hand i found the note below:
Note that "monotonically increasing" does not imply that the ROWID always increases by exactly one. One is the usual increment. However, if an insert fails due to (for example) a uniqueness constraint, the ROWID of the failed insertion attempt might not be reused on subsequent inserts, resulting in gaps in the ROWID sequence. AUTOINCREMENT guarantees that automatically chosen ROWIDs will be increasing but not that they will be sequential.
So my question is, shall i use autoincrement to keep counting my rows in the table?
Use AUTOINCREMENT for increasing the primary key and a simple query to count the number of rows in the table. Don't use AUTOINCREMENT to count the number of rows.
SELECT COUNT(*) FROM table_name
You should count the number of rows using
SELECT Count(*) FROM tableName
For ensuring a unique id for your rows, you can use the autoIncrement function. That is its purpose and that is what it will do.
Usually there's no need to be perfectionist with your db key index - its important that it will be unique but in 99% of the times the consistency is not important.
AUTOINCREMENT ensure your key id will be unique and that's why you should use it.
of-course I don't know the reason you want a consistent key so there is a chance you do need it but
there's other aids for anything you would think of doing with a consistent id row
in Android - for counting and going through your table you can use cursors.

Android composite primary key?

Can anyone tell me how to declare a composite primary key in Android 1.6 which includes an autoincrement _id column? I'm not sure of the syntax. I've ended up just enforcing it in Java when I try to add values (where registrationNumber + date has to be unique in the table):
Cursor fuelUpsCursor = getFuelUps(registrationNumber, date);
if(!fuelUpsCursor.moveToNext())
{
//add registrationNumber and date
}
I don't really need the _id column but it can make life tricky if tables don't have one.
Cheers,
Barry
Your question does not make much sense. Your subject line asks for a "composite foreign key", your first sentence asks for a "composite primary key" with an AUTOINCREMENT that your sample code then ignores.
I am going to interpret your question this way: You want an _ID INTEGER PRIMARY KEY AUTOINCREMENT column in your table to be able to use Android's CursorAdapter, but you want to also make sure that the combination of two other columns is unique.
In that case, I think that you want to use a UNIQUE constraint:
Multiple Unique Columns in SQLite
SQLite table constraint - unique on multiple columns
http://sqlite.org/lang_createtable.html

Categories

Resources