Git Product home page Git Product logo

kabin's Introduction

Kabin Release Kotlin License Apache 2.0


Kabin: Multiplatform Database Library

A Kotlin Multiplatform library for database storage, which aims to support all functionality offered by Room.

Kabin uses drivers from SQLDelight, offering a stable interaction with SQL on all targets supported by the latter.

Caution

This library is still under development. Avoid using it in production. You are very welcome to create issues and Pull Requests. Contribution will accelerate development, and pave the way for a production ready solution.

Showcase

Using Kabin is straight forward. Annotations are identical to those in Room, which means usage is identical too. Here's how you declare a simple database:

  1. Create an Entity:
@Entity
data class UserEntity(
    @PrimaryKey
    val id: Int,
    val name: String
)
  1. Create a Dao:
@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertOrReplace(entity: UserEntity)
}
  1. Create a Database:
@Database(
    entities = [
        UserEntity::class
    ],
    version = 1
)
interface SampleDatabase : KabinDatabase {
    val userDao: UserDao
}

Kabin will generate code for you and glue everything together.

  1. Finally, create a platform configuration, then pass it to the newInstance method, to initialize SampleDatabase:
// Create configuration for every platform, here's an example for android
val configuration = KabinDatabaseConfiguration(
    context = this,
    name = "sample-database"
)

val sampleDatabase = SampleDatabase::class.newInstance(
    configuration,
    migrations = emptyList(),
    migrationStrategy = KabinMigrationStrategy.DESTRUCTIVE
)

For more advanced topics, read Room documentation and tutorials, and apply the same logic using Kabin.

Installation

Latest Kabin version

Kabin Release

Add common modules to your sourceSet:

kotlin {
    sourceSets {
        val commonMain by getting {
            dependencies {
                // Kabin
                implementation("com.attafitamim.kabin:core:$kabin_version")
            }

            // Make generated code visible for commonMain
            kotlin.srcDir("$buildDir/generated/ksp/metadata/commonMain/kotlin/")
        }
    }
}

Add ksp compiler:

plugins {
    alias(libs.plugins.kotlin.multiplatform)
    alias(libs.plugins.ksp)
}

dependencies {
    add("kspCommonMainMetadata", "com.attafitamim.kabin:compiler:$kabin_version")
}

// Workaround for using KSP in common
tasks.withType<KotlinCompile<*>>().configureEach {
    if (name != "kspCommonMainKotlinMetadata") {
        dependsOn("kspCommonMainKotlinMetadata")
    }
}

afterEvaluate {
    tasks.filter { task ->
        task.name.contains("SourcesJar", true)
    }.forEach { task ->
        task.dependsOn("kspCommonMainKotlinMetadata")
    }
}

Optional

Configure ksp processor to generate more suitable code for you

ksp {
    // Use this prefix for fts tables to keep the old room scheme
    arg("FTS_TRIGGER_NAME_PREFIX", "room_fts_content_sync")
}

Available keys, with their default values

TABLE_SUFFIX("KabinTable")
ENTITY_MAPPER_SUFFIX("KabinMapper")
DATABASE_SUFFIX("KabinDatabase")
DAO_SUFFIX("KabinDao")
DAO_QUERIES_SUFFIX("KabinQueries")
INDEX_NAME_PREFIX("index")
FTS_TRIGGER_NAME_PREFIX("kabin_fts_content_sync")
BEFORE_UPDATE_TRIGGER_NAME_SUFFIX("BEFORE_UPDATE")
AFTER_UPDATE_TRIGGER_NAME_SUFFIX("AFTER_UPDATE")
BEFORE_DELETE_TRIGGER_NAME_SUFFIX("BEFORE_DELETE")
AFTER_INSERT_TRIGGER_NAME_SUFFIX("AFTER_INSERT")

Supported Room Features

This list shows Room features, which are already supported by Kabin, or under development

Note

To accelerate the development of certain features, create issues to increase priority, or upvote existing ones

@Entity

  • tableName
  • indices
  • inheritSuperIndices
  • primaryKeys
  • foreignKeys
  • ignoredColumns

@PrimaryKey

  • autoGenerate
  • Use @PrimaryKey on multiple columns
  • Use @PrimaryKey on @Embedded columns

@Embedded

  • prefix
  • Nested @Embedded (@Embedded inside an @Embedded)
  • Compound (@Embedded entity inside a class for working with @Relations)
  • @Embedded columns as primary keys using @PrimaryKey

@ColumnInfo

  • name
  • typeAffinity
  • index
  • collate
  • defaultValue

@Ignore

  • Skip columns annotated with @Ignore

@ForeignKey

  • entity
  • parentColumns
  • childColumns
  • onDelete
  • onUpdate
  • deferred

@Index

  • columns
  • orders
  • name
  • unique

@Relation

  • entity
  • parentColumn
  • entityColumn
  • associateBy
  • projection
  • Detect entity from property type
  • Detect entity from list property type
  • Insert entities automatically when inserting Compound classes with @Embedded entities

@Junction

  • value
  • parentColumn
  • entityColumn
  • Retrieve data using @Junction table
  • Create and insert @Junction entities automatically when inserting classes with @Relation

@Fts4

  • contentEntity
  • tokenizerArgs
  • languageId
  • notIndexed
  • prefix
  • order
  • Create virtual table with triggers

@Dao

  • Use coroutines and suspend functions
  • Support Collection and Flow return types
  • Execute operations on Dispatcher.IO
  • Interfaces annotated with @Dao
  • Abstract classes annotated with @Dao

@Insert

  • entity
  • onConflict
  • Insert single entity, multiple entities as distinct parameters or lists of entities
  • Insert Compound classes with @Embedded entities including their @Relation and @Junction

@Delete

  • entity
  • Delete single entity, multiple entities as distinct parameters or lists of entities
  • Delete Compound classes with @Embedded entities including their @Relation and @Junction

@Update

  • entity
  • onConflict
  • Update single entity, multiple entities as distinct parameters or lists of entities
  • Update Compound classes with @Embedded entities including their @Relation and @Junction

@Upsert

Caution

This annotation is currently treated as @Insert with REPLACE strategy

  • entity
  • Use Upsert logic instead of simple insert with REPLACE strategy
  • Upsert single entity, multiple entities as distinct parameters or lists of entities
  • Upsert Compound classes with @Embedded entities including their @Relation and @Junction

@RawQuery

  • observedEntities
  • Detect observed entities by return type

@Query

  • value
  • Detect observed entities by return type
  • Detect observed entities by queried tables
  • Named parameters declared as :parameter
  • Nullable parameters
  • List and nullable list parameters
  • Parameters declared as ?
  • Highlight SQL Syntax
  • Validate SQL Syntax
  • Auto complete SQL Syntax and named parameters

@Transaction

  • Functions with @Transaction annotation
  • Functions working with multiple entity parameters, collections and compounds

@Database

  • entities
  • views
  • version
  • exportSchema
  • autoMigrations
  • Interfaces annotated with @Database
  • Abstract classes annotated with @Database
  • Generate adapters for primitive and enum classes
  • Manual migration
  • Destructive migration
  • Validate Schema

@TypeConverters

Caution

This annotation can only accept converter object that implement app.cash.sqldelight.ColumnAdapter

  • value
  • builtInTypeConverters

@BuiltInTypeConverters

  • enums (Enums are supported by default)
  • uuid

@AutoMigration

  • from
  • to
  • spec
  • Support auto migration functionality

Additional Features

@Mappers

  • Used to map results returned by a dao to data classes that are not entities or primitives
  • This annotation is meant to be used with Database class
  • value accepts object that implements KabinMapper<T>

Compound

  • Classes that use @Embedded and @Relation annotations can be used with @Insert, @Upsert, @Delete and @Update
  • @Junction inside a compound is automatically created and inserted as well

Plans and Priorities

  1. Add Tests
  2. Clean and refactor compiler and processor logic, make it more flexible and maintainable
  3. Generate more optimized code
  4. Fix bugs and issues
  5. Implement more Room features, especially the essential ones for basic and simple apps
  6. Add more features to make working with SQL easier and more interesting
  7. Add multiplatform sample with UI
  8. Make a stable release

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.