iOS and Android (Java) sdk framework (#643)

Documents the FFI layer for Mentat, and provides transaction functionality via an EDN string. Creates two native libraries for iOS (Swift) and Android (Java) and fully tests the FFI for both platforms.

Closes #619 #614 #611
This commit is contained in:
Emily Toop 2018-05-14 16:20:36 +01:00 committed by GitHub
parent 60cb5d2432
commit 013629dec6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
76 changed files with 6545 additions and 288 deletions

25
.gitignore vendored
View file

@ -54,3 +54,28 @@ pom.xml.asc
/fixtures/*.db-shm
/fixtures/*.db-wal
/query-parser/out/
## Build generated
/sdks/swift/Mentat/build/
DerivedData
build.xcarchive
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
/sdks/swift/Mentat/*.xcodeproj/project.xcworkspace/xcuserdata
## Other
*.xccheckout
*.moved-aside
*.xcuserstate
*.xcscmblueprint
## Obj-C/Swift specific
*.hmap
*.ipa

4
android_build_all.sh Executable file
View file

@ -0,0 +1,4 @@
# This will eventually become a complete build script, not just for Android
cargo build -p mentat_ffi --target i686-linux-android --release
cargo build -p mentat_ffi --target armv7-linux-androideabi --release
cargo build -p mentat_ffi --target aarch64-linux-android --release

View file

@ -19,7 +19,7 @@ use rustc_version::{
/// MIN_VERSION should be changed when there's a new minimum version of rustc required
/// to build the project.
static MIN_VERSION: &'static str = "1.24.0";
static MIN_VERSION: &'static str = "1.25.0";
fn main() {
let ver = version().unwrap();

View file

@ -755,6 +755,27 @@ impl Binding {
_ => None,
}
}
pub fn into_c_string(self) -> Option<*mut c_char> {
match self {
Binding::Scalar(v) => v.into_c_string(),
_ => None,
}
}
pub fn into_kw_c_string(self) -> Option<*mut c_char> {
match self {
Binding::Scalar(v) => v.into_kw_c_string(),
_ => None,
}
}
pub fn into_uuid_c_string(self) -> Option<*mut c_char> {
match self {
Binding::Scalar(v) => v.into_uuid_c_string(),
_ => None,
}
}
}
#[test]

View file

@ -1,10 +1,14 @@
[package]
name = "mentat_ffi"
version = "0.1.0"
version = "0.0.1"
authors = ["Emily Toop <etoop@mozilla.com>"]
[lib]
name = "mentat_ffi"
crate-type = ["lib", "staticlib", "cdylib"]
[dependencies]
libc = "0.2"
[dependencies.mentat]
path = ".."
path = "../"

File diff suppressed because it is too large Load diff

View file

@ -19,19 +19,18 @@ pub mod strings {
Keyword,
};
pub fn c_char_to_string(cchar: *const c_char) -> String {
pub fn c_char_to_string(cchar: *const c_char) -> &'static str {
let c_str = unsafe { CStr::from_ptr(cchar) };
let r_str = c_str.to_str().unwrap_or("");
r_str.to_string()
c_str.to_str().unwrap_or("")
}
pub fn string_to_c_char<T>(r_string: T) -> *mut c_char where T: Into<String> {
CString::new(r_string.into()).unwrap().into_raw()
}
pub fn kw_from_string(keyword_string: &'static str) -> Keyword {
// TODO: validate. The input might not be a keyword!
pub fn kw_from_string(mut keyword_string: String) -> Keyword {
let attr_name = keyword_string.split_off(1);
let attr_name = keyword_string.trim_left_matches(":");
let parts: Vec<&str> = attr_name.split("/").collect();
Keyword::namespaced(parts[0], parts[1])
}

9
sdks/android/Mentat/.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Mentat</name>
<comment>Project Mentat created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,27 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.60'
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View file

@ -0,0 +1,17 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

View file

@ -0,0 +1,6 @@
#Thu Mar 29 09:07:24 BST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

160
sdks/android/Mentat/gradlew vendored Executable file
View file

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
sdks/android/Mentat/gradlew.bat vendored Normal file
View file

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

View file

@ -0,0 +1 @@
/build

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,42 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 26
defaultConfig {
minSdkVersion 26
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
androidTest.assets.srcDirs += '../../../../fixtures'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation 'com.android.support:support-annotations:24.0.0'
androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test:rules:0.5'
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:26.1.0'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'net.java.dev.jna:jna:4.5.1'
}
repositories {
mavenCentral()
}

View file

@ -0,0 +1,25 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ~/.android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View file

@ -0,0 +1,27 @@
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* Copyright 2018 Mozilla
* 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. */
package com.mozilla.mentat;
import java.util.EventListener;
interface ExpectationEventListener extends EventListener {
public void fulfill();
}
public class Expectation implements ExpectationEventListener {
public boolean isFulfilled = false;
public void fulfill() {
this.isFulfilled = true;
synchronized (this) {
notifyAll( );
}
}
}

View file

@ -0,0 +1,725 @@
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* Copyright 2018 Mozilla
* 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. */
package com.mozilla.mentat;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.UUID;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*/
@RunWith(AndroidJUnit4.class)
public class FFIIntegrationTest {
Mentat mentat = null;
@Test
public void openInMemoryStoreSucceeds() throws Exception {
Mentat mentat = new Mentat();
assertNotNull(mentat);
}
@Test
public void openStoreInLocationSucceeds() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
String path = context.getDatabasePath("test.db").getAbsolutePath();
Mentat mentat = new Mentat(path);
assertNotNull(mentat);
}
public String readFile(String fileName) {
Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
AssetManager assetManager = testContext.getAssets();
try {
InputStream inputStream = assetManager.open(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line + "\n");
}
return out.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public TxReport transactCitiesSchema(Mentat mentat) {
String citiesSchema = this.readFile("cities.schema");
return mentat.transact(citiesSchema);
}
public TxReport transactSeattleData(Mentat mentat) {
String seattleData = this.readFile("all_seattle.edn");
return mentat.transact(seattleData);
}
public Mentat openAndInitializeCitiesStore() {
if (this.mentat == null) {
this.mentat = new Mentat();
this.transactCitiesSchema(mentat);
this.transactSeattleData(mentat);
}
return this.mentat;
}
public TxReport populateWithTypesSchema(Mentat mentat) {
String schema = "[\n" +
" [:db/add \"b\" :db/ident :foo/boolean]\n" +
" [:db/add \"b\" :db/valueType :db.type/boolean]\n" +
" [:db/add \"b\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"l\" :db/ident :foo/long]\n" +
" [:db/add \"l\" :db/valueType :db.type/long]\n" +
" [:db/add \"l\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"r\" :db/ident :foo/ref]\n" +
" [:db/add \"r\" :db/valueType :db.type/ref]\n" +
" [:db/add \"r\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"i\" :db/ident :foo/instant]\n" +
" [:db/add \"i\" :db/valueType :db.type/instant]\n" +
" [:db/add \"i\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"d\" :db/ident :foo/double]\n" +
" [:db/add \"d\" :db/valueType :db.type/double]\n" +
" [:db/add \"d\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"s\" :db/ident :foo/string]\n" +
" [:db/add \"s\" :db/valueType :db.type/string]\n" +
" [:db/add \"s\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"k\" :db/ident :foo/keyword]\n" +
" [:db/add \"k\" :db/valueType :db.type/keyword]\n" +
" [:db/add \"k\" :db/cardinality :db.cardinality/one]\n" +
" [:db/add \"u\" :db/ident :foo/uuid]\n" +
" [:db/add \"u\" :db/valueType :db.type/uuid]\n" +
" [:db/add \"u\" :db/cardinality :db.cardinality/one]\n" +
" ]";
TxReport report = mentat.transact(schema);
Long stringEntid = report.getEntidForTempId("s");
String data = "[\n" +
" [:db/add \"a\" :foo/boolean true]\n" +
" [:db/add \"a\" :foo/long 25]\n" +
" [:db/add \"a\" :foo/instant #inst \"2017-01-01T11:00:00.000Z\"]\n" +
" [:db/add \"a\" :foo/double 11.23]\n" +
" [:db/add \"a\" :foo/string \"The higher we soar the smaller we appear to those who cannot fly.\"]\n" +
" [:db/add \"a\" :foo/keyword :foo/string]\n" +
" [:db/add \"a\" :foo/uuid #uuid \"550e8400-e29b-41d4-a716-446655440000\"]\n" +
" [:db/add \"b\" :foo/boolean false]\n" +
" [:db/add \"b\" :foo/ref "+ stringEntid +"]\n" +
" [:db/add \"b\" :foo/long 50]\n" +
" [:db/add \"b\" :foo/instant #inst \"2018-01-01T11:00:00.000Z\"]\n" +
" [:db/add \"b\" :foo/double 22.46]\n" +
" [:db/add \"b\" :foo/string \"Silence is worse; all truths that are kept silent become poisonous.\"]\n" +
" [:db/add \"b\" :foo/uuid #uuid \"4cb3f828-752d-497a-90c9-b1fd516d5644\"]\n" +
" ]";
return mentat.transact(data);
}
@Test
public void transactingVocabularySucceeds() {
Mentat mentat = new Mentat();
TxReport schemaReport = this.transactCitiesSchema(mentat);
assertNotNull(schemaReport);
assertTrue(schemaReport.getTxId() > 0);
}
@Test
public void transactingEntitiesSucceeds() {
Mentat mentat = new Mentat();
this.transactCitiesSchema(mentat);
TxReport dataReport = this.transactSeattleData(mentat);
assertNotNull(dataReport);
assertTrue(dataReport.getTxId() > 0);
Long entid = dataReport.getEntidForTempId("a17592186045605");
assertEquals(65733, entid.longValue());
}
@Test
public void runScalarSucceeds() throws InterruptedException {
Mentat mentat = openAndInitializeCitiesStore();
String query = "[:find ?n . :in ?name :where [(fulltext $ :community/name ?name) [[?e ?n]]]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindString("?name", "Wallingford").runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals("KOMO Communities - Wallingford", value.asString());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void runCollSucceeds() throws InterruptedException {
Mentat mentat = openAndInitializeCitiesStore();
String query = "[:find [?when ...] :where [_ :db/txInstant ?when] :order (asc ?when)]";
final Expectation expectation = new Expectation();
mentat.query(query).runColl(new CollResultHandler() {
@Override
public void handleList(CollResult list) {
assertNotNull(list);
for (int i = 0; i < 3; ++i) {
assertNotNull(list.asDate(i));
}
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void runCollResultIteratorSucceeds() throws InterruptedException {
Mentat mentat = openAndInitializeCitiesStore();
String query = "[:find [?when ...] :where [_ :db/txInstant ?when] :order (asc ?when)]";
final Expectation expectation = new Expectation();
mentat.query(query).runColl(new CollResultHandler() {
@Override
public void handleList(CollResult list) {
assertNotNull(list);
for(TypedValue value: list) {
assertNotNull(value.asDate());
}
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void runTupleSucceeds() throws InterruptedException {
Mentat mentat = openAndInitializeCitiesStore();
String query = "[:find [?name ?cat]\n" +
" :where\n" +
" [?c :community/name ?name]\n" +
" [?c :community/type :community.type/website]\n" +
" [(fulltext $ :community/category \"food\") [[?c ?cat]]]]";
final Expectation expectation = new Expectation();
mentat.query(query).runTuple(new TupleResultHandler() {
@Override
public void handleRow(TupleResult row) {
assertNotNull(row);
String name = row.asString(0);
String category = row.asString(1);
assert(name == "Community Harvest of Southwest Seattle");
assert(category == "sustainable food");
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void runRelIteratorSucceeds() throws InterruptedException {
Mentat mentat = openAndInitializeCitiesStore();
String query = "[:find ?name ?cat\n" +
" :where\n" +
" [?c :community/name ?name]\n" +
" [?c :community/type :community.type/website]\n" +
" [(fulltext $ :community/category \"food\") [[?c ?cat]]]]";
final LinkedHashMap expectedResults = new LinkedHashMap<String, String>();
expectedResults.put("InBallard", "food");
expectedResults.put("Seattle Chinatown Guide", "food");
expectedResults.put("Community Harvest of Southwest Seattle", "sustainable food");
expectedResults.put("University District Food Bank", "food bank");
final Expectation expectation = new Expectation();
mentat.query(query).run(new RelResultHandler() {
@Override
public void handleRows(RelResult rows) {
assertNotNull(rows);
int index = 0;
for (TupleResult row: rows) {
String name = row.asString(0);
assertNotNull(name);
String category = row.asString(1);
assertNotNull(category);
String expectedCategory = expectedResults.get(name).toString();
assertNotNull(expectedCategory);
assertEquals(expectedCategory, category);
++index;
}
assertEquals(expectedResults.size(), index);
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void runRelSucceeds() throws InterruptedException {
Mentat mentat = openAndInitializeCitiesStore();
String query = "[:find ?name ?cat\n" +
" :where\n" +
" [?c :community/name ?name]\n" +
" [?c :community/type :community.type/website]\n" +
" [(fulltext $ :community/category \"food\") [[?c ?cat]]]]";
final LinkedHashMap expectedResults = new LinkedHashMap<String, String>();
expectedResults.put("InBallard", "food");
expectedResults.put("Seattle Chinatown Guide", "food");
expectedResults.put("Community Harvest of Southwest Seattle", "sustainable food");
expectedResults.put("University District Food Bank", "food bank");
final Expectation expectation = new Expectation();
mentat.query(query).run(new RelResultHandler() {
@Override
public void handleRows(RelResult rows) {
assertNotNull(rows);
for (int i = 0; i < expectedResults.size(); ++i) {
TupleResult row = rows.rowAtIndex(i);
assertNotNull(row);
String name = row.asString(0);
assertNotNull(name);
String category = row.asString(1);
assertNotNull(category);
String expectedCategory = expectedResults.get(name).toString();
assertNotNull(expectedCategory);
assertEquals(expectedCategory, category);
}
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingLongValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?e . :in ?long :where [?e :foo/long ?long]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindLong("?long", 25).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingRefValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
long stringEntid = mentat.entIdForAttribute(":foo/string");
final Long bEntid = report.getEntidForTempId("b");
String query = "[:find ?e . :in ?ref :where [?e :foo/ref ?ref]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?ref", stringEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(bEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingRefKwValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
String refKeyword = ":foo/string";
final Long bEntid = report.getEntidForTempId("b");
String query = "[:find ?e . :in ?ref :where [?e :foo/ref ?ref]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindKeywordReference("?ref", refKeyword).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(bEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingKwValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?e . :in ?kw :where [?e :foo/keyword ?kw]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindKeyword("?kw", ":foo/string").runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingDateValueSucceeds() throws InterruptedException, ParseException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
Date date = new Date(1523896758000L);
String query = "[:find [?e ?d] :in ?now :where [?e :foo/instant ?d] [(< ?d ?now)]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindDate("?now", date).runTuple(new TupleResultHandler() {
@Override
public void handleRow(TupleResult row) {
assertNotNull(row);
TypedValue value = row.get(0);
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingStringValueSucceeds() throws InterruptedException {
Mentat mentat = this.openAndInitializeCitiesStore();
String query = "[:find ?n . :in ?name :where [(fulltext $ :community/name ?name) [[?e ?n]]]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindString("?name", "Wallingford").runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals("KOMO Communities - Wallingford", value.asString());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingUuidValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?e . :in ?uuid :where [?e :foo/uuid ?uuid]]";
UUID uuid = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
final Expectation expectation = new Expectation();
mentat.query(query).bindUUID("?uuid", uuid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingBooleanValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?e . :in ?bool :where [?e :foo/boolean ?bool]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindBoolean("?bool", true).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void bindingDoubleValueSucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?e . :in ?double :where [?e :foo/double ?double]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindDouble("?double", 11.23).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToLong() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/long ?v]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(25, value.asLong().longValue());
assertEquals(25, value.asLong().longValue());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToRef() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?e . :where [?e :foo/long 25]]";
final Expectation expectation = new Expectation();
mentat.query(query).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(aEntid, value.asEntid());
assertEquals(aEntid, value.asEntid());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToKeyword() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/keyword ?v]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(":foo/string", value.asKeyword());
assertEquals(":foo/string", value.asKeyword());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToBoolean() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/boolean ?v]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(true, value.asBoolean());
assertEquals(true, value.asBoolean());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToDouble() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/double ?v]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(new Double(11.23), value.asDouble());
assertEquals(new Double(11.23), value.asDouble());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToDate() throws InterruptedException, ParseException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/instant ?v]]";
final Expectation expectation = new Expectation();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ENGLISH);
format.parse("2017-01-01T11:00:00+00:00");
final Calendar expectedDate = format.getCalendar();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(expectedDate.getTime(), value.asDate());
assertEquals(expectedDate.getTime(), value.asDate());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToString() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/string ?v]]";
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals("The higher we soar the smaller we appear to those who cannot fly.", value.asString());
assertEquals("The higher we soar the smaller we appear to those who cannot fly.", value.asString());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void typedValueConvertsToUUID() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
String query = "[:find ?v . :in ?e :where [?e :foo/uuid ?v]]";
final UUID expectedUUID = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
final Expectation expectation = new Expectation();
mentat.query(query).bindEntidReference("?e", aEntid).runScalar(new ScalarResultHandler() {
@Override
public void handleValue(TypedValue value) {
assertNotNull(value);
assertEquals(expectedUUID, value.asUUID());
assertEquals(expectedUUID, value.asUUID());
expectation.fulfill();
}
});
synchronized (expectation) {
expectation.wait(1000);
}
assertTrue(expectation.isFulfilled);
}
@Test
public void valueForAttributeOfEntitySucceeds() throws InterruptedException {
Mentat mentat = new Mentat();
TxReport report = this.populateWithTypesSchema(mentat);
final Long aEntid = report.getEntidForTempId("a");
TypedValue value = mentat.valueForAttributeOfEntity(":foo/long", aEntid);
assertNotNull(value);
assertEquals(25, value.asLong().longValue());
}
@Test
public void entidForAttributeSucceeds() {
Mentat mentat = new Mentat();
this.populateWithTypesSchema(mentat);
long entid = mentat.entIdForAttribute(":foo/long");
assertEquals(65540, entid);
}
}

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mozilla.mentat">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

View file

@ -0,0 +1,48 @@
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* Copyright 2018 Mozilla
* 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