Schema Definition
Introducció
Si vols pots crear una consulta SQL amb un String, però el compilador no et por dir si la consulta és correcta ni et pot ajudar a refactoritzar les consultes si hi ha canvis en l’esquema de la base de dades.
Una altre opció és crear la consulta amb el propi llenguatge Kotlin mitjançant un llenguatge específic de domini (DSL) per SQL..
Objecte Table
Una taula SQL es defineixe mitjançant un esquema.
Per exemple, pots crear les taules deparment i employee amb aquestes sentències sql:
TODO revisar
(
id int primary key auto_increment,
name text not null,
location text not null
);
(
id int not null primary key auto_increment,
name text not null,
job text not null,
manager_id int,
hire_date date not null,
salary bigint not null,
department_id int not null references deparment
);Però aquest esquema no el pots utilitzar directament, entre altres coses perquè no està escrit en Kotlin.
El primer pas és definir directament l’esquema en Kotlin mitjançant un objecte que exten la classe Table.
A continuació tens les taules anteriors definides mitjançant objectes:
object Departments : Table<Nothing>("department") {
val id = int("id").primaryKey()
val name = text("name")
val location = text("location")
}
object Employees : Table<Nothing>("employee") {
val id = int("id").primaryKey()
val name = text("name")
val job = text("job")
val managerId = int("manager_id")
val hireDate = date("hire_date")
val salary = long("salary")
val departmentId = int("department_id")
}We can see that both Departments and Employees are extending from Table whose constructor accepts a table name as the parameter.
La classe té un paràmetre genèric de tipus que és el tipus de la classe amb la qual podem vincular la taula per poder treballar directament amb objectes enlloc de files tal com veurem a TODO(link entity).
Però en SQL DSL treballem directament amb els resultats SQL, i per això utilitzem el paràmetre de tipus Nothing.
Columns are defined as properties in table objects by Kotlin’s val keyword, their types are defined by type definition functions, such as int, long, varchar, date, etc.
Commonly, these type definition functions follow the rules below:
- They are all Table class’s extension functions that are only allowed to be used in table object definitions.
- Their names are corresponding to the underlying SQL types’ names.
- They all accept a parameter of string type, that is the column’s name.
- Their return types are
Column<C>, in whichCis the type of current column. We can chaining call the extension functionprimaryKeyto declare the current column as a primary key.
In general, we define tables as Kotlin singleton objects, but we don’t really have to stop there.
For example, sometimes our table is one-off, we don’t need to use it twice, so it’s not necessary to define it as a global object, for fear that the naming space is polluted. This time, we can even define the table as an anonymous object inside a function:
val t = object : Table<Nothing>("config") {
val key = varchar("key").primaryKey()
val value = varchar("value")
}
// Get all configs as a Map<String, String>
val configs = database.from(t).select().associate { row -> row[t.key] to row[t.value] }Activitats
1.- Crea la taula config, inserta alguns valors i verifica que el codi funciona.
{% sol %}
(key string primary key, value string);
insert into config ...Estás leyendo una vista previa.
Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.
Iniciar sesión