Convert Figma logo to code with AI

cashapp logosqldelight

SQLDelight - Generates typesafe Kotlin APIs from SQL

6,119
512
6,119
577

Top Related Projects

A lightweight wrapper around SQLiteOpenHelper which introduces reactive stream semantics to SQL operations.

3,139

requery - modern SQL based query & persistence for Java / Kotlin / Android

12,626

greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.

Realm is a mobile database: a replacement for SQLite & ORMs

Android Database - first and fast, lightweight on-device vector database

8,207

Kotlin SQL Framework

Quick Overview

SQLDelight is a Kotlin-based SQL code generator for Android, iOS, and JVM applications. It generates typesafe Kotlin APIs from SQL statements, allowing developers to write raw SQL and benefit from compile-time verification, IDE autocompletion, and refactoring support.

Pros

  • Cross-platform support for Android, iOS, and JVM
  • Compile-time SQL verification and type-safe Kotlin APIs
  • Seamless integration with Kotlin Multiplatform projects
  • Excellent IDE support with autocompletion and refactoring

Cons

  • Learning curve for developers unfamiliar with SQL or Kotlin
  • Limited to SQL databases, not suitable for NoSQL solutions
  • May require additional setup compared to ORM solutions

Code Examples

  1. Defining a table and query:
CREATE TABLE hockey_player (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  number INTEGER NOT NULL
);

selectAll:
SELECT *
FROM hockey_player;

insertPlayer:
INSERT INTO hockey_player (name, number)
VALUES (?, ?);
  1. Using generated Kotlin code:
val database = Database(driver)

// Insert a player
database.hockeyPlayerQueries.insertPlayer("Wayne Gretzky", 99)

// Query all players
val players = database.hockeyPlayerQueries.selectAll().executeAsList()
  1. Custom query with parameters:
getPlayerByNumber:
SELECT *
FROM hockey_player
WHERE number = ?;

// Usage
val player = database.hockeyPlayerQueries.getPlayerByNumber(99).executeAsOne()

Getting Started

  1. Add SQLDelight to your project's build.gradle:
plugins {
  id 'com.squareup.sqldelight' version '1.5.4'
}

sqldelight {
  Database { // This will be the name of the generated database class
    packageName = "com.example.db"
  }
}
  1. Create a .sq file in src/main/sqldelight with your SQL statements:
-- src/main/sqldelight/com/example/Player.sq
CREATE TABLE player (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL
);

insertPlayer:
INSERT INTO player (name)
VALUES (?);

selectAll:
SELECT *
FROM player;
  1. Build your project to generate Kotlin code, then use it in your application:
val database = Database(driver)
database.playerQueries.insertPlayer("Alice")
val players = database.playerQueries.selectAll().executeAsList()

Competitor Comparisons

A lightweight wrapper around SQLiteOpenHelper which introduces reactive stream semantics to SQL operations.

Pros of SQLBrite

  • Lightweight and flexible, allowing for more customization
  • Easier integration with existing SQLite databases
  • Supports reactive queries with RxJava

Cons of SQLBrite

  • Requires more manual work for query management
  • Less type-safe compared to SQLDelight
  • Limited code generation capabilities

Code Comparison

SQLBrite:

val query = db.createQuery("users", "SELECT * FROM users WHERE age > ?", "18")
query.mapToList { cursor ->
    User(cursor.getString(cursor.getColumnIndex("name")))
}

SQLDelight:

val users = database.userQueries.selectUsersOlderThan(age = 18)
    .executeAsList()

SQLDelight generates type-safe Kotlin APIs from SQL statements, providing a more robust and less error-prone approach. SQLBrite, on the other hand, requires manual mapping of cursor results to objects, which can be more flexible but also more prone to errors.

SQLDelight offers stronger compile-time guarantees and better IDE integration, while SQLBrite provides a lighter-weight solution that may be easier to adopt in existing projects. SQLDelight's code generation can lead to cleaner and more maintainable code in the long run, but SQLBrite's simplicity and flexibility may be preferred for smaller projects or those with specific requirements.

3,139

requery - modern SQL based query & persistence for Java / Kotlin / Android

Pros of requery

  • Supports multiple database types (SQLite, MySQL, PostgreSQL, etc.)
  • Offers both ORM and SQL query capabilities
  • Provides runtime code generation for improved flexibility

Cons of requery

  • Less active development and community support
  • More complex setup and configuration
  • Steeper learning curve for beginners

Code Comparison

SQLDelight:

CREATE TABLE User (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL
);

val users = database.userQueries.selectAll().executeAsList()

requery:

@Entity
data class User(
    @get:Key @get:Generated val id: Int = 0,
    val name: String
)

val users = data.select(User::class).get().toList()

Both SQLDelight and requery are SQL libraries for Kotlin, but they have different approaches. SQLDelight focuses on type-safe SQL generation and multiplatform support, while requery offers a more traditional ORM experience with additional SQL capabilities. SQLDelight has gained more popularity and active development recently, making it a preferred choice for many developers. However, requery's support for multiple database types and its combination of ORM and SQL features may be advantageous in certain scenarios.

12,626

greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.

Pros of greenDAO

  • Mature and well-established ORM with a large user base
  • Supports database encryption out of the box
  • Offers a simple and intuitive API for database operations

Cons of greenDAO

  • Requires more boilerplate code compared to SQLDelight
  • Limited support for complex queries and custom SQL statements
  • Less flexibility in terms of database schema changes

Code Comparison

greenDAO:

@Entity
public class User {
    @Id private Long id;
    private String name;
    private int age;
}

DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();
UserDao userDao = daoSession.getUserDao();

SQLDelight:

CREATE TABLE User (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  age INTEGER NOT NULL
);

data class User(
  val id: Long,
  val name: String,
  val age: Int
)

val database = Database(driver)
val userQueries: UserQueries = database.userQueries

SQLDelight offers a more type-safe approach with generated Kotlin code, while greenDAO relies on annotations and runtime code generation. SQLDelight provides better integration with Kotlin coroutines and multiplatform projects, making it a more modern choice for Android development.

Realm is a mobile database: a replacement for SQLite & ORMs

Pros of Realm

  • Object-oriented database with real-time synchronization capabilities
  • Supports encryption and offline-first architecture
  • Faster query performance for complex data structures

Cons of Realm

  • Steeper learning curve due to its unique object-oriented approach
  • Limited SQL support, which may be challenging for developers familiar with traditional SQL databases
  • Larger app size due to the inclusion of the Realm runtime

Code Comparison

SQLDelight:

CREATE TABLE Person (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL
);

val person = Person(name = "John Doe")
database.personQueries.insert(person)

Realm:

open class Person : RealmObject() {
    var name: String = ""
}

realm.executeTransaction { realm ->
    realm.createObject(Person::class.java).apply {
        name = "John Doe"
    }
}

SQLDelight generates type-safe Kotlin APIs from SQL statements, while Realm uses an object-oriented approach with its own query language. SQLDelight provides more flexibility for complex SQL queries, whereas Realm offers a more intuitive object-based model for simpler data structures. The choice between the two depends on the specific requirements of your project, such as real-time synchronization needs, query complexity, and your team's familiarity with SQL or object-oriented databases.

Android Database - first and fast, lightweight on-device vector database

Pros of ObjectBox

  • High performance: ObjectBox is designed for speed and efficiency, often outperforming SQLite-based solutions
  • Object-oriented approach: Works directly with objects, eliminating the need for complex ORM mappings
  • Multiplatform support: Offers native implementations for various platforms, including Android, iOS, and desktop

Cons of ObjectBox

  • Learning curve: Requires understanding a new database paradigm, which may be challenging for developers familiar with SQL
  • Limited ecosystem: Fewer third-party tools and integrations compared to SQL-based solutions
  • Potential lock-in: Migrating away from ObjectBox can be more complex due to its unique data model

Code Comparison

ObjectBox:

@Entity
public class User {
    @Id long id;
    String name;
    int age;
}

Box<User> userBox = store.boxFor(User.class);
userBox.put(new User(0, "Alice", 25));

SQLDelight:

CREATE TABLE User (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  age INTEGER NOT NULL
);

INSERT INTO User (name, age) VALUES (?, ?);

Both ObjectBox and SQLDelight offer efficient database solutions for mobile and desktop applications. ObjectBox focuses on object-oriented persistence with high performance, while SQLDelight provides type-safe SQL queries with code generation. The choice between them depends on project requirements, team expertise, and performance needs.

8,207

Kotlin SQL Framework

Pros of Exposed

  • Supports multiple database types (MySQL, PostgreSQL, SQLite, etc.)
  • Offers both type-safe DSL and raw SQL query support
  • Provides advanced features like batch inserts and upserts

Cons of Exposed

  • Steeper learning curve due to more complex API
  • Requires more boilerplate code for entity definitions
  • May have slightly higher runtime overhead

Code Comparison

SQLDelight:

CREATE TABLE Person (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL
);

selectAll:
SELECT * FROM Person;

Exposed:

object Persons : Table() {
    val id = integer("id").autoIncrement()
    val name = varchar("name", 50)
    override val primaryKey = PrimaryKey(id)
}

val allPersons = Persons.selectAll()

SQLDelight generates type-safe Kotlin APIs from SQL statements, while Exposed uses a DSL to define tables and queries in Kotlin. SQLDelight is more SQL-centric, whereas Exposed provides a more Kotlin-native approach to database interactions.

SQLDelight excels in multiplatform projects and compile-time SQL validation, while Exposed offers more flexibility with database types and advanced querying features. The choice between them depends on project requirements, team expertise, and whether SQL-first or Kotlin-first approach is preferred.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

SQLDelight

See the project website for documentation and APIs

SQLDelight generates typesafe Kotlin APIs from your SQL statements. It verifies your schema, statements, and migrations at compile-time and provides IDE features like autocomplete and refactoring which make writing and maintaining SQL simple.

SQLDelight understands your existing SQL schema.

CREATE TABLE hockey_player (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  number INTEGER NOT NULL
);

It generates typesafe code for any labeled SQL statements.

intro.gif


SQLDelight supports a variety of dialects and platforms:

SQLite

MySQL (JVM)

PostgreSQL (JVM)

HSQL/H2 (JVM) (Experimental)

Snapshots

Snapshots of the development version (including the IDE plugin zip) are available in Sonatype's snapshots repository. Note that the coordinates are all app.cash.sqldelight instead of com.squareup.cash for the 2.0.0+ SNAPSHOTs.

Documentation pages for the latest snapshot version can be found here.

License

Copyright 2016 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.