Xamarin.iOS 中的自定义 SQLite 函数

Custom SQLite functions in Xamarin.iOS

我正在 Xamarin.iOS 上开发 Sqlite 的自定义函数。我从这里得到了答案:Show markers on map within a given radius (Xamarin.Android) 但我 运行 进入

的问题

Attempting to JIT compile method '(wrapper native-to-managed) Mono.Data.Sqlite.SqliteFunction:ScalarCallback (intptr,int,intptr)' while running with --aot-only.

在堆栈上搜索后,我发现这里有一个解决方案:custom functions SQLite with Mono但是提到解决方案对我来说很难理解。

我不确定如何使用 MonoPInvokeCallbackAttribute 注释方法并将其设为静态,因为 SqliteFunction class 中的方法已被覆盖,因此无法将其设为静态。 如果有人可以帮助我理解该解决方案或提供该解决方案的缺失步骤,那就太好了。

我使用流行的 sqlite-net(Frank A. Krueger),它又使用 SQLitePCLRaw.bundle_greenSQLitePCL.raw(均由 Eric Sink)。

因此,您可以使用基于 SQLitePCLRaw.ugly 的 API 轻松设置和访问 SQLite UDF。

一个基于Xamarin.iOSSQLite用户定义函数(UDF):

delegate void SQLiteCallback(sqlite3_context ctx, object user_data, sqlite3_value[] args);
[MonoPInvokeCallback(typeof(SQLiteCallback))]
static void UDFDistanceFunction(sqlite3_context ctx, object user_data, sqlite3_value[] args)
{
    double radius = 6367;
    var lat1 = raw.sqlite3_value_double(args[0]);
    var lng1 = raw.sqlite3_value_double(args[1]);
    var lat2 = raw.sqlite3_value_double(args[2]);
    var lng2 = raw.sqlite3_value_double(args[3]);
    var result = radius * 2 * Math.Asin(Math.Min(1, Math.Sqrt((Math.Pow(Math.Sin((lat2 * (Math.PI / 180) - lat1 * (Math.PI / 180)) / 2.0), 2.0) + Math.Cos(lat1 * (Math.PI / 180)) * Math.Cos(lat2 * (Math.PI / 180)) * Math.Pow(Math.Sin((lng2 * (Math.PI / 180) - lng1 * (Math.PI / 180)) / 2.0), 2.0)))));
    raw.sqlite3_result_double(ctx, result);
}

用法:

使用sqlite-net-pcl设置表,load/update数据,.....

SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
var dbName = Path.Combine(Path.GetTempPath(), "Whosebug.db");
var db = new SQLiteConnection(dbName, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, true);
db.CreateTable<BarLocations>();
db.Insert(new BarLocations()
{
    name = "FOOBAR", lat = 47.60357, lng = -122.3295
});

使用 SQLitePCLRaw.ugly 通过 SQLite UDF 创建和查询

SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
var dbName = Path.Combine(Path.GetTempPath(), "Whosebug.db");
using (sqlite3 dbRaw = ugly.open(dbName))
{
    dbRaw.create_function("distance", 4, null, UDFDistanceFunction);
    double currentLatitude = 47.0;
    double currentLongitude = -122.0;
    var sql = $"SELECT * FROM barlocations WHERE distance('{currentLatitude.ToString()}', '{currentLongitude.ToString()}', barlocations.lat, barlocations.lng) <= 100 ;";
    var locs = dbRaw.query<BarLocations>(sql);
    foreach (var loc in locs)
    {
        Console.WriteLine(loc.name);
    }
}