SurrealDB Kotlin implementation.

Overview

logo

Kotlin Surreal Database API

KSDB | by Necrosis

SurrealDB framework for Kotlin

contributors last update forks stars open issues license

Documentation · Report Bug · Request Feature


📔 Table of Contents

🗒️ Kotlin SurrealDB

This implementation has 2 parts, one is responsible for connection and requests, the other is a framework.

API

me.necrosis.surrealdb.api.SurrealDB is an abstract class, used to handle sync, and async functions.
Because this, every function returns a new me.necrosis.surrealdb.api.util.Task.

🌟 Create SurrealDB

📑 Synchronized

/**
 * SYNCHRONIZED
 */
val syncSurrealDB = SyncSurrealDB(
  "localhost:8000",     //  Host
  "test",               //  Database
  "test",               //  Namespace
  User("root","root")   //  User
)
syncSurrealDB.connect().get { isConnected /* Is connected boolean */ ->
    if(isConnected) println("Connected")
    else println("Error")
}
println("After connected")

//  Output :
//  ---------------
//  Connected
//  After connected

📑 Asynchronous

/**
 * ASYNCHRONOUS
 */
val asyncSurrealDB = AsyncSurrealDB(
    "localhost:8000",     //  Host
    "test",               //  Database
    "test",               //  Namespace
    User("root","root")   //  User
)
asyncSurrealDB.connect().get { isConnected /* Is connected boolean */ ->
    if(isConnected) println("Connected")
    else println("Error")
}
println("Before connected")

//  Output :
//  ---------------
//  Before connected
//  Connected

API only can perform simple requests to server, for more info see the official documentation.

Possible functions with API

SurrealDB#sql(query: String) // Allows custom SurrealQL queries
SurrealDB#select(table: String) // Selects all records in a table from the database
SurrealDB#select(record: Record) // Selects the specific record from the database
SurrealDB#create(table: String, data: JSONObject) // Creates a records in a table in the database
SurrealDB#create(record: Record, data: JSONObject) // Creates a records in a table in the database
SurrealDB#delete(table: String) // Deletes all records in a table from the database
SurrealDB#delete(record: Record) // Deletes the specified record from the database
SurrealDB#update(record: Record, data: JSONObject) // Updates the specified record in the database
SurrealDB#modify(record: Record, data: JSONObject) // Modifies the specified record in the database

🖼️ KSDB (framework)

KSDB is the framework for the library. Automatically create records to database, and create objects, which parameters match with the record data.

📚 Table Handler

KSDB main tool is the me.necrosis.surrealdb.framework.component.table.TableHandler. This connects object mapper and the table entity, to make object mapping automatic.
Table handler needs a table entity, in generic type, or with table entity class, in get parameter.

Create entity

This function automatically run in asynchronous, but you can set wait param to true, then the thread is wait for the job end.
You can get the JSONObject callback if you want, with the callback param, which is follows the format (JSONObject)->Unit.
The wait, and the callback params, is optional, because params have default values.

val KSDB = KSDB(
  SyncSurrealDB("localhost:8000","test","test", User("root","root"))
)

val testEntityTableHandler = KSDB.get<TestEntity>()

testEntityTableHandler.create(
    TestEntity(id="entityID",name="testName",age=16),
    wait = true
  ){ json ->
      println(json.toString())
  }

Find entity

You can find table entity from ID, or with Query object.
Results is created with the object mapper automatically.
All find function return a new CompletableFuture, to handle asynchronous methods.

val KSDB = KSDB(
  SyncSurrealDB("localhost:8000","test","test", User("root","root"))
)

val testEntityTableHandler = KSDB.get<TestEntity>()

testEntityTableHandler.find("entityID") //  This will return a new CompletableFuture with TestEntity object, with the database values.
                                        //  If record not exist with this ID, then return null.
Query

Query object responsible to create filter, to find entities, in the database.
This object holds the QueryFields. QueryField contains 4 parameters

  • QueryType
  • Field Name
  • Field Value
  • Or state, which is a new QueryField, but this field is optional
val query = Query()
val request = query.add(
            QueryField(
                QueryType.EQUALS,   //  Query Type
                "name",             //  Field name
                "Michael",          //  Field value
                QueryField(         //  Or state
                    QueryType.EQUALS,
                    "name",
                    "Thomas"
                )
            ),
            QueryField(QueryType.GREATER,"age",16)
        )

val requestGetOutput = "(name = \"Michael\" OR name = \"Thomas\") AND age > 16 "
testEntityTableHandler.find(request)
Delete

Delete entire table with TableHandler#deleteTable(wait,callback)
Delete record with id TableHandler#delete(id,wait,callback)
Delete with where case TableHandler#delete(where,wait,callback)

Update

Update entity use a table entity, and his ID field.

TableHandler#update(entity,wait,callback)

📇 Create table entity

To use object mapping, you must create a table entity, which must contains an empty constructor constructor() ,an ID field, and a @Table(tableName) annotation.

@Table("testTable") //  Table name, to save the record
data class TestEntity(
    @Id val id:String? = null,  //  ID field
    val name:String? = null,
    val age:Int? = null
)

🪢 Relation

KSDB make relations easier, just add table entity to an already created table entity.

@Table("Person") //  Table name, to save the record
data class Person(
    @Id val id:String? = null,  //  ID field
    val name:String? = null,
    val age:Int? = null,
    val params:PersonParams? = null   //  Relation field
)

@Table("PersonParams") //  Table name, to save the record
data class PersonParams(
    @Id val id:String? = null,  //  ID field
    val height:Int? = null,
    val weight:Int? = null
)

📝 Database function annotations

SurrealQL has built-in functions, for more information see the official documentation. You can use some functions, with field annotations.

🔐 Crypto

Crypto function is a hashing function. Use on String fields, and it's automatically saves the hashed value, to the database.

Warning The real value travels once to the database to return the hashed value!

All crypto function is implemented, except compare functions, see the CRYPTO function documentation.

@Table("testTable") //  Table name, to save the record
data class TestEntity(
    @Id val id:String? = null,  //  ID field
    val name:String? = null,

    @Crypto(CryptoType.SHA256)  //  Crypto function
    val password:String?=null,

    val age:Int? = null
)

TestEntity(id="test",name="testName",password="StrongPassword",age=19)
//  The saved record is:
//      id: testTable:test
//      name=testName
//      password=05a181f00c157f70413d33701778a6ee7d2747ac18b9c0fbb8bd71a62dd7a223
//      age=19

Note When requesting an entity, it returns with the already hashed value, and the original value is not returned anywhere.

🔣 Random

Random functions, to generate random value, and save to field value.
Random annotation has 4 parameters

  • Random tye
    • RAND - Generates and returns a random floating point number
    • BOOL - Generates and returns a random boolean
    • FLOAT - Generates and returns a random floating point number
    • RFLOAT - Generates and returns a random floating point number, in a specific range
    • GUID - Generates and returns a random guid
    • LGUID - Generates and returns a random guid, with length
    • INT - Generates and returns a random integer
    • RINT - Generates and returns a random integer, in a specific range
    • STRING - Generates and returns a random string
    • LSTRING - Generates and returns a random string, with length
    • RSTRING - Generates and returns a random string, in a specific range
    • TIME - Generates and returns a random datetime
    • RTIME - Generates and returns a random datetime, in a specific range
    • UUID - Generates and returns a random UUID
  • Min
  • Max
  • Length

If random type value start with R, means RANGE, if start with L, means Length. So if you use random type, which start with R, then set min and max value in annotation. If random type start with L, then set Length value in annotation.

Note Parameters have default values,
min = 0,
max = 100,
length = 15

Session

Session annotation is responsible for database sessions. This annotation set the field value, to selected session.

  • DB - Returns the currently selected database
  • ID - Returns the current user's session ID
  • IP - Returns the current user's session IP address
  • NS - Returns the currently selected namespace
  • ORIGIN - Returns the current user's HTTP origin
  • SC - Returns the current user's authentication scope

🧮 Math

Math annotation allows to run math functions, even if the function require an array. This annotation has two type of query

  • Default
  • ARR_

If MathType starts with a ARR_, then arrayFieldName field is required. If MathTye is FIXED, then fixed field is required.

All the SurrealDB Math function is implemented, see the MATH function documentation.

  • ABS Returns the absolute value of a number
  • CEIL Rounds a number up to the next largest integer
  • FIXED Returns a number with the specified number of decimal places
  • FLOOR Rounds a number down to the next largest integer
  • ARR_MAX Returns the maximum number in a set of numbers
  • ARR_MEAN Returns the mean of a set of numbers
  • ARR_MEDIAN Returns the median of a set of numbers
  • ARR_MIN Returns the minimum number in a set of numbers
  • ARR_PRODUCT Returns the product of a set of numbers
  • ROUND Rounds a number up or down to the nearest integer
  • SQRT Returns the square root of a number
  • ARR_SUM Returns the total sum of a set of numbers

Warning If you use the array function, make sure to use the same object type for the output field as the generic type of the array. Like this

   var math: Array<Int>? = null

   @Math(MathType.ARR_MAX, arrayFieldName = "math")
   var mathArrayMax: Int? = null

   @Math(MathType.ARR_MIN, arrayFieldName = "math")
   var mathArrayMin: Int? = null

In this case, you can't use Double field on mathArrayMax or mathArrayMin field, only Int, like the array type.

🗺️ Mapper

🧭 Todos

  • Rules to specify input data
  • Extend annotation functions
  • Bug fixing
  • Date time adapter

👋 Contributing

Contributions are always welcome!

⚠️ License

Distributed under the MIT License. See LICENSE for more information.

You might also like...
Starter code for Android Kotlin Fundamentals Codelab 6.1 Room

TrackMySleepQuality - Starter Code Starter code for Android Kotlin Fundamentals Codelab 6.1 Room Introduction TrackMySleepQuality is an app for record

BookSearchApp - Book Search App With Kotlin
BookSearchApp - Book Search App With Kotlin

BookSearchApp IT Book Search App Search IT books with keyword and view informati

Memory objects for Kotlin/JVM and Java

Memoria Why should an object care about where to store their bytes? Examples Basics RAM can used as a memory storage: val ram: BytesMemory = RamMemory

JAKO: Just Another Kotlin Orm (PostgreSQL)
JAKO: Just Another Kotlin Orm (PostgreSQL)

JAKO: Just Another Kotlin Orm (PostgreSQL) JAKO is a simple, minimal, no-dependency library to build and execute postgresql statements using a fluent

A MySQL connector wrapper that supports mapping to Kotlin classes.

Racoon Racoon is a wrapper for the MySQL connector. It makes communicating with the database easier by providing a bunch of functionalities: Mapping q

Room Database Queries with Kotlin Flow

Room Database Queries with Flow This app displays a list of bus stops and arrival times. Tapping a bus stop on the first screen will display a list of

Code samples for the second edition of "Kotlin in Action".

Code samples for Kotlin in Action, Second Edition This project contains the code samples from book "Kotlin in Action, Second Edition" by Roman Elizaro

[] Action bar implementation which uses the native action bar on Android 4.0+ and a custom implementation on pre-4.0 through a single API and theme.
[] Action bar implementation which uses the native action bar on Android 4.0+ and a custom implementation on pre-4.0 through a single API and theme.

DEPRECATED ActionBarSherlock is deprecated. No more development will be taking place. For an up-to-date action bar backport use AppCompat. Thanks for

LifecycleMvp 1.2 0.0 Kotlin  is MVP architecture implementation with Android Architecture Components and Kotlin language features
LifecycleMvp 1.2 0.0 Kotlin is MVP architecture implementation with Android Architecture Components and Kotlin language features

MinSDK 14+ Download Gradle Add to project level build.gradle allprojects { repositories { ... maven { url 'https://jitpack.io' }

Opinionated Redux-like implementation backed by Kotlin Coroutines and Kotlin Multiplatform Mobile

CoRed CoRed is Redux-like implementation that maintains the benefits of Redux's core idea without the boilerplate. No more action types, action creato

Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

HubSpot Kotlin SDK 🧺 Implementation of HubSpot API for Java/Kotlin in tiny SDK

HubSpot Kotlin SDK 🧺 Implementation of HubSpot API for Java/Kotlin in tiny SDK

📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.
📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.

NotyKT 🖊️ NotyKT is the complete Kotlin-stack note taking 🖊️ application 📱 built to demonstrate a use of Kotlin programming language in server-side

📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.
📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.

NotyKT 🖊️ NotyKT is the complete Kotlin-stack note taking 🖊️ application 📱 built to demonstrate a use of Kotlin programming language in server-side

📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.
📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.

NotyKT 🖊️ NotyKT is the complete Kotlin-stack note taking 🖊️ application 📱 built to demonstrate a use of Kotlin programming language in server-side

A Kotlin compiler plugin implementation of AutoService

auto-service-kt A Kotlin compiler plugin implementation of AutoService. Usage Simply add the auto-service-kt Gradle Plugin. plugins { id("dev.zacswe

A Zero-Dependency Kotlin Faker implementation built to leave you fully satisfied

Satisfaketion A Zero-Dependency Kotlin Faker implementation built to leave you fully satisfied 😏 ... With your fake data How to Install 🚀 Satisfaket

A kotlin implementation of commutative encryption based on ECC ElGamal encryption over Curve25519

komuta A commutative encryption implementation. This is a naive implementation of commutative encryption using the ElGamal scheme applied over Curve25

typedmap is an implementation of heterogeneous type-safe map pattern in Kotlin

Typedmap typedmap is an implementation of heterogeneous type-safe map pattern in Kotlin. It is a data structure similar to a regular map, but with two

Owner
Necrosis
Necrosis
An app with implementation of Room database for Android platform

Room Room An app with implementation of Room database for Android platform The Room persistence library provides an abstraction layer over SQLite to a

Void Hash 1 Jan 4, 2023
Kotlin-Exposed-SQL - Example of using Exposed with Kotlin for the consumption of relational SQL Databases

Kotlin Exposed SQL Sencillo ejemplo sobre el uso y abuso de Exposed ORM de Jetbr

José Luis González Sánchez 3 Jun 14, 2022
requery - modern SQL based query & persistence for Java / Kotlin / Android

A light but powerful object mapping and SQL generator for Java/Kotlin/Android with RxJava and Java 8 support. Easily map to or create databases, perfo

requery 3.1k Dec 29, 2022
A Java/Kotlin library for Android platform, to manage bean's persistence in SQLite, SharedPreferences, JSON, XML, Properties, Yaml, CBOR.

Thanks to JetBrains for support Kripton Persistence Library project! Kripton Persistence Library Kripton is a java library, for Android platform, that

xcesco 117 Nov 11, 2022
Upsert DSL extension for Exposed, Kotlin SQL framework

Exposed Upsert Upsert DSL extension for Exposed, Kotlin SQL framework. Project bases on various solutions provided by community in the official "Expos

Dzikoysk 23 Oct 6, 2022
Samples demonstrating the usage of Realm-Kotlin SDK

Realm-Kotlin Samples This repository contains a set of projects to help you learn about using Realm-Kotlin SDK Each sample demonstrates different use

Realm 52 Dec 31, 2022
Collection of Kotlin APIs/tools to make using Realm Mobile database easier

Compass Kotlin API and tools to make working with Realm easier Components Compass is designed to make working with Realm easier through collection of

Arunkumar 16 Oct 4, 2022
Upsert DSL extension for Exposed, Kotlin SQL framework

Exposed Upsert Upsert DSL extension for Exposed, Kotlin SQL framework. Project bases on various solutions provided by community in the official "Expos

Reposilite Playground 23 Oct 6, 2022
sql-delight example, a plugin by Square which is pure kotlin and it is useful in kmm

Sql-Delight-Example01 Developed by Mahdi Razzaghi Ghaleh first example of sql-delight What is SqlDelight? Kotlin Multiplatform is one of the most inte

rq_mehdi 0 Jan 24, 2022
RecordMe - Record your voice application with kotlin

RecordMe A simple voice recording app. Made Using : Kotlin, Navigation Component

Steve Waweru 2 Apr 28, 2022