Search code examples
sqlitekotlinkotlin-interop

How to use SQLite in Kotlin/Native?


For a multi-platform project, I consider Kotlin/Native, with the hope to have a common code base at least for business logic and saving of data.

For saving of data I would like to use a database like SQLite. However, according to another stackoverflow thread, if I want to compile to Kotlin/Native, I cannot use any Java file. If I understand this correctly, it also means that any SQLite library I include is not allowed to import from Java.

On the search for such a library, I found two interesting database projects by Jetbrain, namely Anko SQLite and Exposed. However, when digging in their source code, at the time of this writing both import from Java (e.g. java.sql). Which probably means I cannot use them.

One idea I had was to use a c-based sqlite library, since according to mentioned thread, Kotlin/Native code is allowed to use c libraries. This may be possible, but I wondered if there isn't a suggested more Kotlin like way of using SQLite or another database in Kotlin/Native?


Solution

  • You do need to use the C SQLite library, but most of your code shouldn't work with it directly. Instead you write a wrapper which will be the more Kotlin-like way you are asking about.

    I haven't seen such a wrapper done as a separate maintained project (there are very few libraries for Kotlin/Native yet), but Jetbrains actually has a basic one in https://github.com/Kotlin/kotlinconf-spinner/tree/b1e66920ac7216d3dbc4b6b4625fb77efe23cff8/sql which you can use as base for your own.