SQLite and Android
class
MyDatabase(context: Context, name: String?) : SQLiteOpenHelper(context, name,
null
,
VERSION
) {
override fun
onCreate(db: SQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE
${
UserColumns.
TABLE_NAME
}
(
${
UserColumns.
ID
}
INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
${
UserColumns.
NAME
}
TEXT NOT NULL
);
"""
.
trimIndent
())
db.execSQL(
"""
CREATE TABLE
${
FriendshipColumns.
TABLE_NAME
}
(
${
FriendshipColumns.
FRIEND_1
}
INTEGER NOT NULL REFERENCES
${
UserColumns.
TABLE_NAME
}
,
${
FriendshipColumns.
FRIEND_2
}
INTEGER NOT NULL REFERENCES
${
UserColumns.
TABLE_NAME
}
,
${
FriendshipColumns.
BECAME_FRIENDS
}
INTEGER NOT NULL DEFAULT CURRENT_TIME,
PRIMARY KEY (
${
FriendshipColumns.
FRIEND_1
}
,
${
FriendshipColumns.
FRIEND_2
}
)
);
"""
.
trimIndent
())
db.execSQL(
"""
CREATE TABLE
${
CheckinColumns.
TABLE_NAME
}
(
${
CheckinColumns.
ID
}
INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
${
CheckinColumns.
NAME
}
TEXT NOT NULL,
${
CheckinColumns.
TIME
}
INTEGER NOT NULL
);
"""
.
trimIndent
())
db.execSQL(
"""
CREATE TABLE
${
UserCheckinColumns.
TABLE_NAME
}
(
${
UserCheckinColumns.
CHECKIN_ID
}
INTEGER NOT NULL REFERENCES
${
CheckinColumns.
TABLE_NAME
}
,
${
UserCheckinColumns.
USER_ID
}
INTEGER NOT NULL REFERENCES
${
UserColumns.
TABLE_NAME
}
,
PRIMARY KEY(
${
UserCheckinColumns.
CHECKIN_ID
}
,
${
UserCheckinColumns.
USER_ID
}
)
);
"""
.
trimIndent
())
}
W
override fun
onUpgrade(db: SQLiteDatabase, old: Int, new
: Int) {
}
X
companion object
{
private const val
VERSION
1
}
Y
}
Z
object
UserColumns {
const val
TABLE_NAME
"user"
const val
ID
"_id"
const val
NAME
"name"
}
A
object
FriendshipColumns {
const val
TABLE_NAME
"friendship"
const val
FRIEND_1
"friend1"
const val
FRIEND_2
"friend2"
const val
BECAME_FRIENDS
"became_friends"
}
B
object
CheckinColumns {
const val
TABLE_NAME
"checkin"
const val
ID
"_id"
const val
NAME
"name"
const val
TIME
"time"
}
C
object
UserCheckinColumns {
const val
TABLE_NAME
"user_checkin"
const val
CHECKIN_ID
"checkin_id"
const val
USER_ID
"user_id"
}
D