Git Product home page Git Product logo

sqlite.net-pcl's Introduction

Build status

This project is no longer actively maintained!

Fork

This is a fork of the original sqlite-net library (https://github.com/praeclarum/sqlite-net), which aims to improve the code quality by using modern technologies such as PCL (portable class library).

The project will avoid the use of #if-based conditional code and use platform-specific code injection instead.

I welcome pull requests, but keep in mind that this library is in heavy use and all changes must be:

  • Backwards-compatible (don't change database defaults).
  • Well tested (please add unit tests).

Versioning

This project uses semantic versioning.

API Changes

As part of the cleanup there are now some API changes. For the most part I hope these are self-explanatory, but here is a non-exhaustive list of changes.

SQLiteConnection

You now have to pass in an implementation of ISQlitePlatform in the SQLiteConnectionWithLock and SQLiteConnection constructors. The correct platform implementation is automatically added to the project.

At the moment these platforms are supported:

  • Win32 (bundles sqlite binaries for windows, works on both x86 and x64 automatically) (very well tested)
  • XamarinIOS and XamarinIOS.Unified
  • XamarinAndroid
  • WindowsPhone8 (contributed by Nick Cipollina, thanks!)
  • WinRT (Windows 8 and Windows Phone 8.1+) (contributed by Nick Cipollina and Micah Lewis, thanks!)
  • Generic (net4 project without any sqlite3 binaries, requires sqlite installed in the OS) (contributed by James Ottaway)

Note: To use the WP8.1/WinRT platform you must install the "SQLite for Windows Phone"/"SQLite for Windows" VSIX extension. Then, in the project, add a reference to the extension (in the Extensions section of the Add Reference dialog) If you have problems with signed apps take a look here: #25

SQliteAsyncConnection

The SQLiteAsyncConnection class now takes a Func in the constructor instead of a path. This is done because the async classes are now just meant to be wrappers around the normal sqlite connection.

To use SQLiteAsyncConnection just create an instance of a SQLiteConnectionWithLock and pass in that through a func, e.g.: new SQLiteAsyncConnection(()=>_sqliteConnectionWithLock);

Please be aware that the Task.Run pattern used in SQLiteAsyncConnection can be considered an anti-pattern (libraries should not provide async methods unless they are truly async). This class is maintained for backwards compatability and for use-cases where async-isolation is handy.

DateTime serialization

DateTime serialization is changed, in order to be consistent. When using the storeDateTimeAsTicks option, the DateTime is now serialized as Utc, and the returned DateTime is also in Utc. You can get the local time by using dateTime.ToLocalTime()

SQLite.Net

SQLite.Net is an open source, minimal library to allow .NET and Mono applications to store data in [http://www.sqlite.org SQLite 3 databases]. It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, Azure, etc.).

SQLite.Net was designed as a quick and convenient database layer. Its design follows from these goals:

  • Very easy to integrate with existing projects and with MonoTouch projects.

  • Thin wrapper over SQLite and should be fast and efficient. (The library should not be the performance bottleneck of your queries.)

  • Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.

  • Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)

  • 0 dependencies aside from a compiled form of the sqlite2 library.

Non-goals include:

License

This projected is licensed under the terms of the MIT license. See LICENSE.TXT

Meta

This is an open source project that welcomes contributions/suggestions/bug reports from those who use it. If you have any ideas on how to improve the library, please post an issue here on github. Please check out the How to Contribute.

Example Time!

Please consult the source code (see unit tests) for more examples.

The library contains simple attributes that you can use to control the construction of tables. In a simple stock program, you might use:

public class Stock
{
	[PrimaryKey, AutoIncrement]
	public int Id { get; set; }
	[MaxLength(8)]
	public string Symbol { get; set; }
}

public class Valuation
{
	[PrimaryKey, AutoIncrement]
	public int Id { get; set; }
	[Indexed]
	public int StockId { get; set; }
	public DateTime Time { get; set; }
	public decimal Price { get; set; }
}

Once you've defined the objects in your model you have a choice of APIs. You can use the "synchronous API" where calls block one at a time, or you can use the "asynchronous API" where calls do not block. You may care to use the asynchronous API for mobile applications in order to increase reponsiveness.

Both APIs are explained in the two sections below.

Synchronous API

Once you have defined your entity, you can automatically generate tables in your database by calling CreateTable:

var db = new SQLiteConnection(sqlitePlatform, "foofoo");
db.CreateTable<Stock>();
db.CreateTable<Valuation>();

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:

public static void AddStock(SQLiteConnection db, string symbol) {
	var s = db.Insert(new Stock() {
		Symbol = symbol
	});
	Console.WriteLine("{0} == {1}", s.Symbol, s.Id);
}

Similar methods exist for Update and Delete.

The most straightforward way to query for data is using the Table method. This can take predicates for constraining via WHERE clauses and/or adding ORDER BY clauses:

	var conn = new SQLiteConnection(sqlitePlatform, "foofoo");
	var query = conn.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));

	foreach (var stock in query)
		Debug.WriteLine("Stock: " + stock.Symbol);

You can also query the database at a low-level using the Query method:

public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock)
{
	return db.Query<Valuation> ("select * from Valuation where StockId = ?", stock.Id);
}

The generic parameter to the Query method specifies the type of object to create for each row. It can be one of your table classes, or any other class whose public properties match the column returned by the query. For instance, we could rewrite the above query as:

public class Val {
	public decimal Money { get; set; }
	public DateTime Date { get; set; }
}
public static IEnumerable<Val> QueryVals (SQLiteConnection db, Stock stock)
{
	return db.Query<Val> ("select 'Price' as 'Money', 'Time' as 'Date' from Valuation where StockId = ?", stock.Id);
}

You can perform low-level updates of the database using the Execute method.

Asynchronous API

The asynchronous library uses the Task Parallel Library (TPL). As such, normal use of Task objects, and the async and await keywords will work for you.

Once you have defined your entity, you can automatically generate tables by calling CreateTableAsync:

var conn = new SQLiteAsyncConnection(()=>sqliteConnection, "foofoo");
conn.CreateTableAsync<Stock>().ContinueWith((results) =>
{
	Debug.WriteLine("Table created!");
});

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:

	Stock stock = new Stock()
	{
		Symbol = "AAPL"
	};

	var conn = new SQLiteAsyncConnection(()=>sqliteConnection, "foofoo");
	conn.InsertAsync(stock).ContinueWith((t) =>
	{
		Debug.WriteLine("New customer ID: {0}", stock.Id);
	});

Similar methods exist for UpdateAsync and DeleteAsync.

Querying for data is most straightforwardly done using the Table method. This will return an AsyncTableQuery instance back, whereupon you can add predictates for constraining via WHERE clauses and/or adding ORDER BY. The database is not physically touched until one of the special retrieval methods - ToListAsync, FirstAsync, or FirstOrDefaultAsync - is called.

	var conn = new SQLiteAsyncConnection(()=>sqliteConnection, "foofoo");
	var query = conn.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));
		
	query.ToListAsync().ContinueWith((t) =>
	{
		foreach (var stock in t.Result)
			Debug.WriteLine("Stock: " + stock.Symbol);
	});

There are a number of low-level methods available. You can also query the database directly via the QueryAsync method. Over and above the change operations provided by InsertAsync etc you can issue ExecuteAsync methods to change sets of data directly within the database.

Another helpful method is ExecuteScalarAsync. This allows you to return a scalar value from the database easily:

	var conn = new SQLiteAsyncConnection("foofoo");
	conn.ExecuteScalarAsync<int>("select count(*) from Stock", null).ContinueWith((t) =>
	{
		Debug.WriteLine(string.Format("Found '{0}' stock items.", t.Result));
	});

sqlite.net-pcl's People

Contributors

damirarh avatar dellis1972 avatar fcy avatar fstokke avatar haf avatar ianmercer avatar jamesottaway avatar jstedfast avatar koush avatar lextm avatar micahl avatar migueldeicaza avatar nberardi avatar ncipollina avatar oysteinkrog avatar peterhuene avatar praeclarum avatar prasannavl avatar ravensorb avatar roufamatic avatar rubenv avatar seancross avatar tah9m9 avatar thomaslevesque avatar thornley-touchstar avatar timheuer avatar tofutim avatar tyrongower avatar vermiceli avatar wilsonmeier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sqlite.net-pcl's Issues

Question: Is that how Select is supposed to work?

I have a table of these :)

public class MyData
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Value { get; set; }
}

and when I do this

db.Table<MyData>.Select(d => d.Value).ToList();

I get back a

List<MyData>

But I was kind of expecting a

List<string>

What's that about?

Question: Why construct `SQLiteAsyncConnection` with a function?

I ran into an issue where I was creating my app's sole SQLiteAsyncConnection in the following manner:

var conn = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(...));

Looking at the source code for SQLiteAsyncConnection, the function passed in as a constructor parameter is called in GetConnection(), which is called any time the SQLiteAsyncConnection needs to read or write to the database.

So this caused a new connection to be instantiated any time conn performed a read or write. In effect, even though I was being very deliberate to only have one database connection for the entire app, the "hidden" inner workings (I am using the Nuget packages) of SQLiteAsyncConnection were causing my app to have multiple connections at any given time, which caused database locking issues once I reached a critical mass of database read/write operation calls.

My question: why is SQLiteAsyncConnection designed this way? Why not simply pass in a SQLiteConnectionWithLock to the constructor, instead of a function that returns one? Or have SQLiteAsyncConnection call the function once, store its result in a private member variable, and then return that variable in GetConnection() instead of running the constructor function parameter every time?

I guess the issue, once realized, is easy to get around -- I simply instantiated a SQLiteConnectionWithLock outside of the function and then passed in that object's accessor as the construction function parameter -- but it's still an unnecessary "gotcha" in my opinion.

WP8: The specified module could not be found

Using code like this:

using (SQLiteConnection connection = new SQLiteConnection(SqlitePlatform, SqliteConnectionString.DatabasePath))

which is in a PCL, but being called from a WP8 project, I get:

The specified module could not be found. (Exception from HRESULT: 0x8007007E)

and the stack trace looks like this:

   at System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD)
   at Sqlite.Sqlite3.sqlite3_open_v2(String filename, Database& db, Int32 flags, String zVfs)
   at SQLite.Net.Platform.WindowsPhone8.SQLiteApiWP8.Open(Byte[] filename, IDbHandle& db, Int32 flags, IntPtr zVfs)
   at SQLite.Net.SQLiteConnection..ctor(ISQLitePlatform sqlitePlatform, String databasePath, SQLiteOpenFlags openFlags, Boolean storeDateTimeAsTicks, IBlobSerializer serializer)
   at SQLite.Net.SQLiteConnection..ctor(ISQLitePlatform sqlitePlatform, String databasePath, Boolean storeDateTimeAsTicks, IBlobSerializer serializer)
   at Division42.PropertyManager.Data.SqliteManager.VerifyDatabaseIsCurrent(Version versionApplicationExpects)
   at Division42.PropertyManager.WP8.UI.App.<InitializeViewModels>d__0.MoveNext()

My packages.config for the WP8 project looks like this:

  <package id="SQLite.Net.Platform.WindowsPhone8" version="2.3.0" targetFramework="wp80" />
  <package id="SQLite.Net-PCL" version="2.3.0" targetFramework="wp80" />
  <package id="sqlite-net-wp8" version="3.8.5" targetFramework="wp80" />

I have verified that the SQLite database file really does exist, but this seems to be failing internally. Any ideas on how to resolve?

Using SQLite-Net-PCL in Universal App

Hi,
I want to use SQLite-Net-PCL in Universal App. Few day ago I could create connection using: _sqlLiteConnection = new SQLiteConnection(_pathOfDatabase); , but after install this extension https://bitbucket.org/twincoders/sqlite-net-extensions SQLiteConnection expected from me SQLitePlatform. I have two problems connected with this issue:

The first:
When I install "SQLite.Net.Platform.WindowsPhone8" I still get "Install-Package : Could not install package 'sqlite-net-wp8 3.8.5'. You are trying
to install this package into a project that targets 'WindowsPhoneApp,Version=v8.1',
but the package does not contain any assembly references or content files that are
compatible with that framework. For more information, contact the package author."

The second:
I save database in roaming data and initialize connection in Shared code. So, if I set platform as "WindowsPhone", I can't use this code in Windows App ?

Thanks

Could not install package 'SQLite.Net-PCL 2.3.0'

I'm trying to install SQLite.Net-PCL in to a portable class library that it's used from a WIndows 8.1 project a WP8.1 project and a WPF .net 4.5.1 app. I have this error while installing the nuget package:

Could not install package 'SQLite.Net-PCL 2.3.0'. You are trying to install this package into a project that targets 'portable-net451+win81+wpa81'

Any Help?

No ability to specify relational constraints against string columns

Because System.String does not define operators <, >, <=, or >=, it is not possible to define a constraint such as:

conn.Table<FooDTO>()
    .Where(x => x.Name > "abc")

This may seem contrived, but this is critical to being able to correctly page through data per the SQLite recommendations.

In my fork I plan on adding some extension methods to string such as GreaterThan and LessThanOrEqual, and then checking for invocations against those extension methods in addition to the existing checks against the operators. It's not exactly elegant, but I can't think of a better way to handle this right now.

Additional DeleteAll methods to delete a list of objects

Hi

Rather than to have to fork the lib to integrate this functionality, I'd like to propose to add it to the mainline.

In SQLiteconnection.cs, I've added two methods allowing me to delete more than one item in a transaction, and the item either being identified by its PK, or the object itself. I found that sqlite-net is not very effective when performing mass operations, and those two delete methods allow significant performance gains over doing it one by one.

    public int DeleteAll<T>(System.Collections.IEnumerable keys)
    {
        var c = 0;
        RunInTransaction(() => 
        {
            foreach (var r in keys)
                c += Delete<T>(r);
        });
        return c;
    }

    /// <summary>
    /// deletes all specified objects
    /// </summary>
    /// <param name="objects">
    /// An <see cref="IEnumerable"/> of the bojects to delete
    /// </param>
    /// <returns>
    /// The number of rows deleted
    /// </returns>
    public int DeleteAll(System.Collections.IEnumerable objects)
    {
        var c = 0;
        RunInTransaction(() => 
        {
            foreach(var r in objects) {
                c += Delete(r);
            }
        });
        return c;
    }

perhaps they should be named DeleteMany instead of DeleteAll..

Unable to resume activity android.database.StaleDataException: Attempted to access a cursor after it has been closed.

I have a problem when running on Android when resume from an activity like this. I don't know why it happens. I just hide app and then resume it from background.
I used mvvmcross for develop my app.

AndroidRuntime] Shutting down VM
[System.err] java.lang.RuntimeException: Unable to resume activity {xxx.xxx.xxx}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
[System.err] at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2575)
[System.err] at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2603)
[System.err] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
[System.err] at android.os.Handler.dispatchMessage(Handler.java:99)
[System.err] at android.os.Looper.loop(Looper.java:137)
[System.err] at android.app.ActivityThread.main(ActivityThread.java:4745)
[System.err] at java.lang.reflect.Method.invokeNative(Native Method)
[System.err] at java.lang.reflect.Method.invoke(Method.java:511)
[System.err] at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
[System.err] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
[System.err] at dalvik.system.NativeStart.main(Native Method)
[System.err] Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
[System.err] at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:64)
[System.err] at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:133)
[System.err] at android.database.CursorWrapper.requery(CursorWrapper.java:186)
[System.err] at android.app.Activity.performRestart(Activity.java:5048)
[System.err] at android.app.Activity.performResume(Activity.java:5074)
[System.err] at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2565)
[System.err] ... 10 more
[AndroidRuntime] FATAL EXCEPTION: main
[AndroidRuntime] java.lang.RuntimeException: Unable to resume activity {vn.me.mobo/mobo.droid.ChatDetailsView}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
[AndroidRuntime] at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2575)
[AndroidRuntime] at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2603)
[AndroidRuntime] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
[AndroidRuntime] at android.os.Handler.dispatchMessage(Handler.java:99)
[AndroidRuntime] at android.os.Looper.loop(Looper.java:137)
[AndroidRuntime] at android.app.ActivityThread.main(ActivityThread.java:4745)
[AndroidRuntime] at java.lang.reflect.Method.invokeNative(Native Method)
[AndroidRuntime] at java.lang.reflect.Method.invoke(Method.java:511)
[AndroidRuntime] at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
[AndroidRuntime] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
[AndroidRuntime] at dalvik.system.NativeStart.main(Native Method)
[AndroidRuntime] Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
[AndroidRuntime] at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:64)
[AndroidRuntime] at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:133)
[AndroidRuntime] at android.database.CursorWrapper.requery(CursorWrapper.java:186)
[AndroidRuntime] at android.app.Activity.performRestart(Activity.java:5048)
[AndroidRuntime] at android.app.Activity.performResume(Activity.java:5074)
[AndroidRuntime] at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2565)
[AndroidRuntime] ... 10 more
[Process] Sending signal. PID: 16827 SIG: 9

WinRT should support Windows Phone 8.1

The WinRT assembly should be able to support Windows 8.1 and Windows Phone 8.1 WinRT apps - it should just work if wpa81 is added as being supported in the .nuspec, though this would need to be tested, obviously.

Cannot instantiate DatabaseConnector on Xamarin.Android platform

I'm using SQLite.NET PCL on cross-platform Xamarin project. All works fine on Xamarin.iOS and Windows Store 8 app, but when I try to instantiate DatabaseConnector on Xamarin.Android platform (for example var db = new DatabaseConnector(new SQLitePlatformAndroid(), "test.db3") in Activity.OnCreate), it throws exception: System.MissingMethodException: Method not found: 'SQLite.Net.SQLiteConnection..ctor'.

(I'm using latest versions of NuGets - SQLite.Net 2.2.0 and SQLite.Net.Platform.XamarinAndroid 2.2.0)

Remove Android Permissions on AssemblyInfo.cs

Hi,

In the Xamarin Android project, the AssemblyInfo.cs has two permissions: Internet and WriteExternalStorage. That has to be removed because that permissions are not necessary for this library (These are added when you create the project using Visual Studio as example, but should be commented hehe).

I would uplaod the patch but I don't know how to become a contributor :)

Thanks!

Ignore attribute is being ignored

This simple example reproduces the issue:

public class DummyClass
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Foo { get; set; }
    public string Bar { get; set; }

    [Ignore]
    public List<string> Ignored { get; set; }
}

This sample fails with an error on the CreateTable statement:

System.NotSupportedException : Don't know about System.Collections.Generic.List`1[System.String]

It shouldn't process the Ignored property at all.

Composite PK support?

I've been using this to support composite primary keys in my fork of SQLite.Net-PCL. Just wondering whether this can make its way into the official repo?

SQLite for Windows Runtime (Windows 8.1)

Hey,
the SQLite.Net.Platform.WinRT package installs an old version of the above mentioned extension.
So I'd like to ask if there's a reason for that / if it is save to update to the current version.

Version installed: 3.8.4.1
Current version: 3.8.7.2

Handling of enums/nullable enums

I've had some trouble with enums and nullable enums in the original sqlite.net. There are a few threads on the issue on praeclarum's repo - here's how I implemented it

In SQLiteCommand.cs, method public IEnumerable ExecuteDeferredQuery(TableMapping map)

I've added the following value assignment

if (cols[i].ColumnType.IsEnum)
{
if (val == null) // nullable enum handling
{
var defaultValue = Enum.GetValues(cols[i].ColumnType).GetValue(0);
cols[i].SetValue(obj, defaultValue);
//var defaultValue = Enum.GetValues(cols[i].ColumnType)[0];
}
else
{
if (Enum.IsDefined(cols[i].ColumnType, val))
{
var parsedEnum = Enum.Parse(cols[i].ColumnType, val.ToString());
cols[i].SetValue(obj, parsedEnum);
}
else
{
var defaultValue = Enum.GetValues(cols[i].ColumnType).GetValue(0);
cols[i].SetValue(obj, defaultValue);
}
}
}
else
cols[i].SetValue(obj, val);

I suppose there could be better way to doing it, but the above has been in use for the past 1.5 years and works just fine.

Use async/await keywords in SQLiteAsyncConnection?

I'm wondering why the async methods in SQLiteAsyncConnection don't use the async and await keywords.

The Microsoft.Bcl.Async package gives backwards-compatible support for async and await in .NET 4.0, so is there another reason for not using the keywords?

If not, I'll make the patch and submit a PR, but I just wanted to check there isn't a reason it won't work before I undertake any major work.

Operation Failed when adding from NuGet

Good Morning,
I am getting 'Operation Failed when adding SQLite.Net-PCL 2.3.0 from NuGet.
I am using VS2013, Xamarin 3.x. My PCL Project targets: .Net Framework 4.5, Windows 8,
Windows Phone 8.1, Xamarin.Androis, Xamarin.iOS. Please see images below:

The error is as follows:
Installing 'SQLite.Net-PCL 2.3.0'.
Successfully installed 'SQLite.Net-PCL 2.3.0'.
Adding 'SQLite.Net-PCL 2.3.0' to CA.GenPos.Shared.Sqlite.
Uninstalling 'SQLite.Net-PCL 2.3.0'.
Successfully uninstalled 'SQLite.Net-PCL 2.3.0'.
Install failed. Rolling back...
Could not install package 'SQLite.Net-PCL 2.3.0'. You are trying to install this package into a project that targets 'portable-net45+win+wpa81+MonoAndroid10+MonoTouch10', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

operationfailed
targets

Support Not Operator

Hi

I've already implemented this in an older build of the main sqlite-net, but I'm sure it would help some others, so here goes (I'm sorry I'm not really a git user so I've never done a pull request)

In TableQuery.cs, method private CompileResult CompileExpr(Expression expr, List queryArgs), before else if (expr.NodeType == ExpressionType.MemberAccess) you add another else if containing the following code

else if (expr.NodeType == ExpressionType.Not) {

            var n = (UnaryExpression)expr;
            var ty = n.Type;
            var valn = CompileExpr(n.Operand, queryArgs);
            switch (n.Operand.NodeType)
            {
                case ExpressionType.MemberAccess:
                    valn.CommandText += " = 0";
                    break;
                case ExpressionType.Call:
                    valn.CommandText = valn.CommandText.Replace(" like ", " not like ");
                    valn.CommandText = valn.CommandText.Replace(" in ", " not in ");
                    valn.CommandText = valn.CommandText.Replace(" = ", " <> ");
                    break;
                default:
                    break;
            }
            return new CompileResult { CommandText = valn.CommandText };
}

Do that and you get your standard NOT operator support working for booleans, strings, collections and values you can compare with = and <>.

Rather than having to keep my own copy of the lib, I think it would be easier to just mainline it.

NuGet installation error for stable version 2.4.1

Hi,

I'm currently using the SQLite.Net-PCL assembly (version: 2.3.0) and I want to update to the latest stable release version 2.4.1.

I got an error, if a try to install the nuget package into my PCL project using the command
"Install-Package SQLite.Net-PCL" where the old version can be installed without any errors
(command: "Install-Package SQLite.Net-PCL -Version 2.3.0").

It seems, that the new version 2.4.1 isn't longer compatible to PCL Profile5, where the old version 2.3.0 is. Meanwhile I was able to install the newer version, but only using PCL Profile78. The problem is, that this profile includes .NET 4.5, but I need .NET 4.0.

Is it possible to use the new version of SQL.Net-PCL for .NET 4.0, .NET for Windows Store apps, Xamarin.Android and Xamarin.iOS?

pcl

Thanks a lot!

Error when installing from nuget

Hi,
I'm recieving an error when installing the Xamarin Android platform PCL from nuget into a new custom PCL to contain my shared code.

The profile of the custom PCL is .Net Framework 4.5 and higher, Silverlight 5, Xamarin.Android and Xamarin.iOS. In addition, there is already a reference to SQLite.Net and SQLite.Net.Async.

The full error is:
Could not install package 'SQLite.Net.Platform.XamarinAndroid 2.3.0'. You are trying to install this package into a project that targets 'portable-net40+sl50+MonoAndroid10+MonoTouch10', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

And ideas what I'm doing wrong here?

Ant

Clean install on WP8 not working

Created a new project, added the SQLite.PCL-net nuget package for WindowsPhone8. Added code to create a connection (see attachment).

Probably lack of setup documentation.

capture

ISerializable issues

I believe there is a fundamental error on the ISerializable interface and its implementation. It seems to assume any class implementing the interface has a constructor that takes in the serializable type as a parameter. This of course cannot be enforced since interfaces cannot define constructors. In my opinion a better way would be to create an interface that exposes something like this:

public interface ISerializableAlternative<T>
{
    T SerializedValue { get; set; }
}

The problem is easy to reproduce with this unit test:

sami1971@2bbfb79

SQLLite.Net.Test.Win32 failing in CreateTwice() - failed to deserialize an enum

Test FullName: SQLite.Net.Tests.CreateTableTest.CreateTwice
Result Message: System.NotSupportedException : Don't know how to read SQLite.Net.Tests.OrderLineStatus

This appears to occur because the test for an enum contains an extra GetType():

        if (clrType.GetType().GetTypeInfo().IsEnum)
        {
            return _sqlitePlatform.SQLiteApi.ColumnInt(stmt, index);
        }

But changing it to:

        if (clrType.GetTypeInfo().IsEnum)
        {
            return _sqlitePlatform.SQLiteApi.ColumnInt(stmt, index);
        }

works.

?? Why are these unit tests failing on a clean fetch from GitHub ??
This line was changed recently by a pull request.

NuGet install error in Windows 8.1 Store app

Installing into 8.1 project (it's a store 8.1 class library project):

If I grab the Github WinRT project and add it to my solution as code it all works fine so hopefully it's just a NuGet thing :)

PM> install-package SQLite.Net.Platform.WinRT
Attempting to resolve dependency 'SQLite.Net-PCL'.
Attempting to resolve dependency 'SQLite.WinRT.redist'.
Installing 'SQLite.WinRT.redist 1.0.2.0'.
Successfully installed 'SQLite.WinRT.redist 1.0.2.0'.
Installing 'SQLite.Net.Platform.WinRT 2.3.0'.
Successfully installed 'SQLite.Net.Platform.WinRT 2.3.0'.
Adding 'SQLite.WinRT.redist 1.0.2.0' to MyApp.WindowDataStorage.
Successfully added 'SQLite.WinRT.redist 1.0.2.0' to MyApp.WindowDataStorage.
You have a newer version of SQLite for Windows Runtime (Windows 8.1).
Adding a project reference to SQLite.
Uninstalling 'SQLite.WinRT.redist 1.0.2.0'.
Successfully uninstalled 'SQLite.WinRT.redist 1.0.2.0'.
Install failed. Rolling back...
install-package : Something unexpected happened. Failed to install SQLite for Windows Runtime (Windows 8.1).
At line:1 char:1

  • install-package SQLite.Net.Platform.WinRT
  • - CategoryInfo          : NotSpecified: (:) [Install-Package], RuntimeException
    - FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
    

db3 file not found

Hi I am building an xamarin form pcl app with sqlite for ios and android and I came across 2 problems. The first is that I get a system.io.filenotfoundexception in my ios project when I start my app:
[assembly: Dependency (typeof (SQLite_iOS))]

namespace Oxaco_BBC.iOS
{
public class SQLite_iOS : ISQLite
{
public SQLite_iOS ()
{
}

    public SQLite.Net.SQLiteConnection GetConnection ()
    {
        var sqliteFilename = "SQLite.db3";
        string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder
        string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
        var path = Path.Combine(libraryPath, sqliteFilename);

        // This is where we copy in the prepopulated database
        Console.WriteLine (path);
        if (!File.Exists (path)) {
            File.Copy (sqliteFilename, path); //error is on this line!!!
        }

        var plat = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
        var conn = new SQLite.Net.SQLiteConnection(plat, path);

        // Return the database connection 
        return conn;
    }
}

}

The second issue I came across was that my recource is not found where the db3 file should be stored when I start up my android project:
[assembly: Dependency (typeof (SQLite_Android))]

namespace Oxaco_BBC.Android
{
public class SQLite_Android : ISQLite
{
public SQLite_Android ()
{
}

    public SQLite.Net.SQLiteConnection GetConnection ()
    {
        var sqliteFilename = "SQLite.db3";
        string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); // Documents folder
        var path = Path.Combine(documentsPath, sqliteFilename);

        // This is where we copy in the prepopulated database
        Console.WriteLine (path);
        if (!File.Exists(path))
        {
            var s = Forms.Context.Resources.OpenRawResource(Resource.Raw.SQLite);  //error on this line!!!

            // create a write stream
            FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            // write to the stream
            ReadWriteStream(s, writeStream);
        }

        var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
        var conn = new SQLite.Net.SQLiteConnection(plat, path);

        // Return the database connection 
        return conn;
    }

    /// <summary>
    /// helper method to get the database out of /raw/ and into the user filesystem
    /// </summary>
    void ReadWriteStream(Stream readStream, Stream writeStream)
    {
        int Length = 256;
        Byte[] buffer = new Byte[Length];
        int bytesRead = readStream.Read(buffer, 0, Length);
        // write the required bytes
        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = readStream.Read(buffer, 0, Length);
        }
        readStream.Close();
        writeStream.Close();
    }
}

}

Allow ExpressionType.Convert MemberExpressions

I am currently using the initial SQLite-net source, but I just checked the source on this project and see that it is the same.

On the TableQuery CompileExpr method, MemberExpressions only check for ExpressionType.Parameter. If the ExpressionType is Convert, an exception is thrown. Is there a reason for this since if the check is changed to the following, it still works in a scenario that I need it for - if (mem.Expression!=null && (mem.Expression.NodeType == ExpressionType.Parameter || mem.Expression.NodeType == ExpressionType.Convert)) {

This is also the case in the AddOrderBy method. I assume in other places also, but for now it is the only places that I picked it up according to my code.

A sample method that I use to replicate my issue:

public async Task<DateTime> GetLatestModifiedDateAsync<T>() where T : IEntity, new()
{
    var result = await db.Table<T>()
                         .OrderByDescending(e => e.ModifiedAt)
                         .FirstOrDefaultAsync();

    return result != null ? result.ModifiedAt : new DateTime(1900, 1, 1);
}

SQLLite.Net.Test.Win32 failing in CreateUniqueIndexes() at CheckIndex(db, indexes, "UX_Uno_bool", true, "Cuatro");

Trying to get the unit tests to run locally and I'm seeing several fail including the CreateUniqueIndexes test where the index uses named parameters:

        [Indexed(Name = "UX_Uno_bool", Unique = true)]
        public int Cuatro { get; set; }

The GetIndices() method fails because there are no ConstructorArguments. attribute has two NamedArguments but no ConstructorArguments.

public static IEnumerable<IndexedAttribute> GetIndices(MemberInfo p)
    {
        var indexedAttributes = new List<IndexedAttribute>();
        foreach (var attribute in p.CustomAttributes)
        {
            if (attribute.AttributeType == typeof(IndexedAttribute))
            {
                var arguments = attribute.ConstructorArguments;
                var name = (string)arguments[0].Value;                    <---- EXCEPTION HERE
                var order = (int)arguments[1].Value;
                indexedAttributes.Add(new IndexedAttribute(name, order));
            }
        }
        return indexedAttributes;
      }

Support associations?

I recently came across SQLite-Net Extensions, which is a nice library for adding support for managing associations and relations in your SQLite database.

It's designed to work with this library, the library this one if forked from, and the MvvmCross version of the library this one is forked from.

Ideally its features would be directly included so there's no need to include yet another DLL, so I was considering working on moving these addons into SQLite.Net-PCL.

As far as I can see, the licenses are compatible (both using MIT), and I'm going to ask the TwinCoders guys if they mind me including their code in your library.

Is there any reason not to include their code here? Would this go against the direction you want to take SQLite.Net-PCL in?

Issues with transactions in SQLite.Net.Platform.WinRT

if using

dbConnection.RunInTransaction(() =>
    {
         dbConnection.InsertAllWithChildren(images);
         ...
    }

I get the exception "A first chance exception of type 'SQLite.Net.SQLiteException' occurred in SQLite.Net.DLL

Additional information: SQL logic error or missing database"

But if i run it without the transaction, the same operations is fine.

Win32 parameter handling doesn't work

{SQLite.Net.SQLiteException: near "?": syntax error
at SQLite.Net.Platform.Win32.SQLiteApiWin32.Prepare2(IDbHandle db, String query)}

is thrown every-time you use parameter binding.
Same issue persists with named parameter.

My guess:

        private IDbStatement Prepare()
        {
            IDbStatement stmt = _sqlitePlatform.SQLiteApi.Prepare2(_conn.Handle, CommandText);
            BindAll(stmt);
            return stmt;
        }

BindAll is called after the IDbStatement, while the IDbStatement creation throws the error in Win32.

Question: Windows Phone 8.1 support

Hello,

This is just a little question about Windows Phone 8.1.
Do you know when it will be added to the library and nuget ?

Thanks a lot !
Cheers,
François.

Question: Setting Serialized Mode in PCL

Hi, in non PCL version of SQLite.Net I was able to do this for Android and iOS:

        SQLite.SQLite3.Shutdown();
        SQLite.SQLite3.Config(SQLite.SQLite3.ConfigOption.Serialized);
        SQLite.SQLite3.Initialize();

and this would stop the threading error.

I cannot see how to set serailize mode with the PCL. Can you explain please.

Bug: can't use NuGet for Xamarin Studio 5.4 environment

I've tryed to use SQLite.Net.Platform.XamarinIOS NuGet with a newest version of Xamarin.iOS (that's Xamarin Studio 5.4 environment and supports iOS 8 development) but got an error that my iOS class library isn't comaptible with the NuGet. I can guess the reason: the NuGet looks for MonoTouch assembly and don't find it 'cause currently this assembly has a name Xamarin.iOS. I'd like to know about plans to fix this bug.

Error assembly System.Linq.Expressions

Hi,

I have a WPF 4.5 project and I try to use SQLite-Net.
I only found PCL version so I use this package.
All is ok but when I compile I have this error on Connection.Get(object pk) method :

System.Linq.Expressions.Expression`1 is defined in assembly not referenced... Add reference to assembly 'System.Expression.Expressions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

What is wrong ?
Thanks

Add strong name to all assemblies

Assembly generation failed -- Referenced assembly 'SQLite.Net' does not have a strong name

Add some e.g ".snk" keys to project and compile assemblies with strong name, to avoid error above.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.