Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Friday, 9 September 2011

Attaching multiple sqlite databases in WP7

Posted on 09:25 by Unknown
Following on from my previous post Rich & I are developing an app which has 2 versions - one has only a single sqlite database but the other could use multiple sqlite databases to store the data - in effect the data is partitioned (sharded) alphabetically for the second version.

Our existing code used for the single database version uses a Simple ORM to do our data access. The primary reason being the code is 2 lines and importantly the performance cost of using the Simple ORM is not an issue at the moment. If it ever becomes an issue we'll switch it out.

What follows is how we approached attaching multiple databases together. Sqlite allows multiple databases to be used under the same connection. The databases don't have to share the same schema at all, all that is required to use the attached databases is to use the syntax database-name.table-name. More info can be found at the sqlite.org website here.

The first attempt was to do this from Vici CoolStorage, I didn't expect this to work because it only has the notion of setting the database you are about to access, I couldn't find anyway to attach a second database. The code is shown below and the runtime exception afterwards, as I said this was hopeful and failed.

    private void databaseAttach_Click(object sender, RoutedEventArgs e)
{
CSConfig.SetDB("database1.sql", SqliteOption.None);
CSDatabase.ExecuteNonQuery("ATTACH 'database2.sql' AS db2;");

var results = CSDatabase.RunQuery
<search_db_column_names>("SELECT db2.search_db_column_names.pk FROM db2.search_db_column_names");

Debug.WriteLine(results.ToString());
}

Blew up with the following exception:

The second attempt was to use C# Sqlite For WP7 of codeplex. Vici CoolStorage is written on top of this so my thought were it would be less of an abstraction and therefore more likely to succeed. This time the code has more traditional DAL feel about - the use of connection, command & reader objects.

Success this worked!

The code is shown below and it's pretty much the same as for a single database call apart from the execute no  query to attach the second database and the modified SQL statement.

As stated earlier the statement is now explicit about which columns and tables are being referenced:

"SELECT * FROM main.PostCodes UNION SELECT * FROM db2.PostCodes"

In this case all I'm doing is the union between 2 tables as they have the same structure and none over lapping data.

        private IList<PostCode> ExecuteAllDatabase1()
{
var postcodes = new List<PostCode>();
using (var conn = new SqliteConnection("Version=3,uri=file:" + Database1))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "ATTACH '" + Database2 + "' AS db2;";
cmd.ExecuteNonQuery();

cmd.CommandText = "SELECT * FROM main.PostCodes UNION SELECT * FROM db2.PostCodes";

using (var reader = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
while (reader.Read())
{
var postCode = new PostCode
{
Value = reader.GetString(1),
District = reader.GetString(2),
Latitude = reader.GetDouble(3),
Longitude = reader.GetDouble(4),
};

postcodes.Add(postCode);
}
}

conn.Close();
}
}

return postcodes;
}

Okay got it working but what about if I got as close to the metal as possible - C# Sqlite For WP7 is written using the csharp-sqlite project up on google code. Shown below is the same functionality written using the C style sqlite.org API.

        private IList<PostCode> ExecuteAllDatabase2()
{
var postcodes = new List<PostCode>();
var database1 = new Sqlite3.sqlite3();

if (Sqlite3.sqlite3_open(Database1, ref database1) == Sqlite3.SQLITE_OK)
{
var attachSql = string.Format("ATTACH DATABASE '{0}' AS db2", Database2);
var errorMessage = string.Empty;

if (Sqlite3.sqlite3_exec(database1, attachSql, null, null, ref errorMessage) == Sqlite3.SQLITE_OK)
{
var selectStmt = new Sqlite3.Vdbe();
var selectSql = @"SELECT * FROM main.PostCodes UNION SELECT * FROM db2.PostCodes";
var stringTail = string.Empty;

if (Sqlite3.sqlite3_prepare_v2(database1, selectSql, -1, ref selectStmt, ref stringTail) == Sqlite3.SQLITE_OK)
{
var n = 0;
while (Sqlite3.sqlite3_step(selectStmt) == Sqlite3.SQLITE_ROW)
{
var col1 = Sqlite3.sqlite3_column_int(selectStmt, 0);
var postCode = Sqlite3.sqlite3_column_text(selectStmt, 1);
var district = Sqlite3.sqlite3_column_text(selectStmt, 2);
var latitude = Sqlite3.sqlite3_column_double(selectStmt, 3);
var longitude = Sqlite3.sqlite3_column_double(selectStmt, 4);

postcodes.Add(new PostCode { District = district, Value = postCode, Latitude = latitude, Longitude = longitude});
}
}
}
else {}
}
else {}

Sqlite3.sqlite3_close(database1);

return postcodes;
}

The only thing left to do was compare the performance of the 2 working solutions. Interestingly it appears the C# Sqlite For WP7 gives better performance than the sqlite API.

C# Sqlite For WP7 average = 85 ms
sqlite API average = 95 ms


I suggest this is probably due to the fact I haven't tweaked the sqlite API code to be as per-formant as possible. Again I have ignored the first result for both implementations.



Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in WP7 sqlite performance development | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Understanding RefCount in Reactive Extensions
    A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • Bad developers love 'The Daily WTF'
    When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
  • Using CompositeDisposable in base classes
    To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
  • Implementing a busy indicator using a visual overlay in MVVM
    This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
    Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the dec...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ▼  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ▼  September (7)
      • WP7Contrib: Criterion Factory - calculating a Route
      • Geo-location on WP7 - don't trust the first value ...
      • How many pins can Bing Maps handle in a WP7 app - ...
      • Attaching multiple sqlite databases in WP7
      • Using a simple ORM with sqlite on WP7
      • Supported cultures in Windows Phone 7 and showing ...
      • WP7Contrib: Criterion Factory - Location by address
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile