Posts Tagged ‘mass insert’

Magiq: New release and API Changes

April 28, 2011 Leave a comment

New release of Magiq, supporting Linq-to-sql. This should be the last one for Linq-to-sql, the next one I hope will have the minimal support for Entity Framework. You can download it from here.

For those reading this for the first time (?), Magiq is a framework that let you do mass operation in a Linq fashion.

So… as Magiq will be supporting Entity Framework soon, it made sense to change the API to make it support Entity Framework limitations. Also, I found a better Insert API (the one that always made me doubt!). The changes are:

Query extension method changes
The new method looks like this:

country.Query(x => x.Cities); 

It will return an IQueryable that will let you do all the Magiq stuff.

No more IEnumerable support
This is a hard one. You can only do Magiq stuff between IQueryables. If you have an IEnumerable collection, use the Query extension method of it parent entity.

New Insert API

destination.Insert( source.Where( condition ).Select( new Item{ ... } ));

Cool, isn’t it? 🙂

Entities extension methods
Because we no longer support extension methods over collections but over the entity, there are some extension methods for improving the code readavility.


entity.Delete(x => x.Collection.Where( condition ));
//Instead of 
entity.Query(x => x.Collection).Where( condition ).Delete();


entity.Update(x => x.Collection.Where( condition ).Set(x => x.Prop, value));
//Instead of 
entity.Query(x => x.Collection).Where( condition ).Set(x => x.Prop, value).Update();


entity.Query(x => x.Collection.Where( condition ));
//Instead of 
entity.Query(x => x.Collection).Where( condition );


entity.InsertInto( x => x.Collection, source.Where( condition ).Select( new Item{ ... } ));
//Instead of
entity.Query(x => x.Collection)
      .Insert( source.Where( condition ).Select( new Item{ ... } ));

Magiq-to-NHibernate: Collection filtering and moving to NHibernate 3

February 25, 2010 1 comment

Few days ago I started having troubles with Linq-to-NHibernate from the current release 2.1.2. The main problem cames when I design the collection filtering strategy. Basically, my idea was to go from:



session.Linq<Child>().Single( x=>x.Id == parent.Id ).SelectMany( x=>x.ChildCollection );

Having this, we could add many expressions to that queryable as we want.

The thing is, as Chadly posted, Linq-to-nhibernate 1.0 uses the query parameter (the x in the previous expression) as the criteria alias, so this works:

       .Single( x=>x.Id == parent.Id )
       .SelectMany( x=>x.ChildCollection, (p,x) => x )
       .Where( x => x.Something );

but this doen’t:

       .Single( x=>x.Id == parent.Id )
       .SelectMany( x=>x.ChildCollection, (p,x) => x )
       .Where( z => z.Something );

Since the chosen strategy for dynamically generating the query involved the definition of the “alias” parameter, and the user will need to know which is, I gave up. So I tried NHibernate 3. And it worked 🙂

It was really painful to change what I’ve done for the old linq provider, because it uses criteria and the new one uses hql. It’s not easy at all to get a IDbCommand from a HQL, but not impossible.

By now, deletes, updates, inserts and bulkinserts are working properly for linq-to-nhibernate 2.0 with the same limitation as before: no inheritance, no collections.
In the next days I will be working on collection support, composite ids and mappings.

Magiq: BulkCopy support

February 19, 2010 Leave a comment

With all the behavior stuff, I have normalized the design in favor of new Magiq providers. Now there’s a MagiqToDatabases abstract class that only needs a few methods to implement. Also, there is a normalization in the operations: Now Magiq have the classes DatabaseInsert, DatabaseUpdate, DatabaseQuery and DatabaseDelete, which contains properties like the columns to update, the expressions of the values, etc.

For implementing BuilkCopy, there was only two things needed to override:

  • The way Magiq-to-objects inserts into a SqlServer based destination: For example, for a Linq-to-Sql table, the way Magiq-to-objects inserts is using the Insert method of Table. The idea is to override that with a SqlBulkCopy. Note: this “way Magiq-to-objects inserts” is called IInsertDestination.
  • Use magiq-to-objects instead any SqlServer insert strategy defined: For using BulkCopy when the source belongs to the same provider, avoiding the regular insert…select… statement

So, following the behavior schema, Magiq provides two interfaces for all this: IObjectsInsertBehavior and IInsertBehavior.

  • IObjectsInsertBehavior provides the way for overriding the IInsertDestination.
  • IInsertBehavior provides the way for overriding the strategy to use, so we can avoid using the default strategy

Also, it needed a way to know if the destination is a SqlServer. Well… all the database operations and strategies implements an interface called IDatabaseBasedExecution that provides a IDatabaseAdapter. And this last interface give us a IDialect that could be a SqlServerDialect.

Ok, ok, but show me some code!!

public class BulkCopy : MagiqBehavior, IObjectsInsertBehavior, IInsertBehavior
	public int BatchSize { get; set; }
	public int Timeout { get; set; }

	public BulkCopy()
		BatchSize = 0;
		Timeout = 30;

	private static bool Applies(IDatabaseBasedExecution execution)
		return execution != null && execution.DatabaseAdapter.Dialect is SqlServerDialect;
	public IInsertDestination<TNew> GetInsertDestination<TSource, TDestination, TNew>(IInsert<TSource, TDestination, TNew> insert)
		where TDestination : class
		where TNew : class, TDestination, new()
		var insertDestination = Next<IObjectsInsertBehavior>().Call(x => x.GetInsertDestination(insert));
		var databaseOperation = insertDestination as IDatabaseBasedExecution;

		if (Applies(databaseOperation))
			return new BulkCopyDestination<TSource, TDestination, TNew>(insert, databaseOperation.DatabaseAdapter)
						   BatchSize = BatchSize,
						   Timeout = Timeout

		return insertDestination;

	public IInsertStrategy GetInsertStrategy<TSource, TDestination, TNew>(IInsert<TSource, TDestination, TNew> insert) where TDestination : class where TNew : class, TDestination, new()
		var strategy = Next<IInsertBehavior>().Call(x => x.GetInsertStrategy(insert));
		var databaseOperation = strategy as IDatabaseBasedExecution;

		if (Applies(databaseOperation))
			return new InsertStrategy<TSource, TDestination, TNew>(insert);

		//overrides the strategy with magiq-to-objects
		return strategy;

	public int Execute(IInsertStrategy strategy)
		//default behavior
		return Next<IInsertBehavior>().Call(x => x.Execute(strategy));

And the way to use it:

var sellsFromSomeRepository = ...;

       .Insert(x => new Record
                        Type = RecordType.Sell,
                        Description = "Sell from " + x.Date,
                        Amount = x.Total

And of course, if you use BulkCopy for inserting into a non SqlServer repository, the plugin continues without changes, so it could be used in a testing environment in which the repositories are setted to a List.

Magiq 0.3.0 available!

February 17, 2010 Leave a comment

I’m glad to announce that the new version of Magiq is available.
Magiq now support:

  • Plugin model
  • BulkCopy as a Plugin for using SqlBulkCopy when inserting into sql server from any source.

And also there was a huge refactoring in order to have simplicity when implementing new providers.

You can download this version from here.

Magiq: Plugin support & the insert API changes

January 30, 2010 Leave a comment

The the main feature of Magiq 0.3.0 is sql server bulk insert support, we needed to improve Magiq with plugins.
These plugins would act as interceptors, and they could be applied at configuration level (for example, logging) and query level (bulk insert).

What I wanted is to have a natural way to assign plugins that would work the same for the four operations: insert, update, delete and query.
Ok, what I wanted was actually complicated.
Since I thougth this for Bulk insert, I tried an API for Inserts:

source.Insert( x => new Item{ Name = x.Name })
      .Using( new BulkInsert() )
      .Into( destination );

Same could work for Updates, but no for Deletes and Queries, because those doesn’t have “intermediate” class. Let me explain: insert and update are performed using several calls. Insert have one for declaring the new expression ( x => new Item{ Name = x.Name }) and one for declaring the destination. The same happens with update, we have several for declaring the “sets” and one Update() to finish de operation. Delete and Query, however, works with one single call (They doesn’t need anything else in order to work), so I don’t have a place to put the “Using” method :(.

So, how could it be implemented for Delete and Query? I thought it should be before calling the operation, something like

source.Using( new BulkInsert() )
      .Insert( x => new Item{ Name = x.Name })
      .Into( destination );

The issue with this approach is that the plugin should be for all the operations and not the specific one. But I’m ok with that, I suppose It could be implemented like NHibernate listeners.
So… the idea is to wrap the IEnumerable or IQueryable with another one that is plugged to one or more plugins. Later, I could check for the type of the collection and make use of the plugins. The problem with this solution is that nothing ensures that collection to be the one used in the magiq operations. For example, something like this:

source.Using( new BulkInsert() )
      .Where( somecondition )
      .Insert( x => new Item{ Name = x.Name }).Into( destination );

Magiq will work with the last queryable and not the plugged one. I know, I could check all the chain but, again, nothing ensures that the plugged collection is there.

Talking to my friend Rezlaj, we got to a solution I don’t like a lot but… it’s a solution. The idea is to have all the stuff inside a interface IMagiq that could be getted using an extension method Magiq applied to a collection. It would look like:

      .Where( somecondition )
      .Insert( x => new Item{ Name = x.Name }).Into( destination );

This IMagiq interface have the methods to add plugins and could have another methods to interact with the operation in the future. Of course, there still are the extensions methods Delete, Set, ToQueryable (well, not this last one, because I changed it to Query because I think is better). But they delegates all to the IMagiq interface.
I think I should change the blog title to “The problem with that…”. You may ask way…

The problem with that (the previous that, actually. I mean, the new API) is that all the operations are applied to a T where T : class except Insert. Why? WHY?! because the source of an insert operation could be a colection of int’s, date’s, whatever. For example, this should be supported (and it is!):

sells.Where( x => x.Date == DateTime.Now)
     .Select( x => x.Total )
     .Insert( x => new SellRecord{ Total = x.Name, Date = DateTime.Now })
     .Into( records );

(I know, the example is not the happiest one, but it’s helpful for explaining my point)
So… the source collection is a collection of decimals. Ok, how could it be solved? because IMagiq needs the T : class constraint. Well, there was an idea in my head for the last couple of days about how linq and all the magiq operations except insert reverses the analogous sql structure. So… It makes more sense to have the insert reversed. Something like:

records.Insert( x => new SellRecord{ Total = x.Name, Date = DateTime.Now })
       .From( sells.Where( x => x.Date == DateTime.Now) )

Ok, it’s just an example, it won’t compile (but It will complain… cuak). I need the source type before the NewExpression, so it have no choice that be:

records.From( sells.Where( x => x.Date == DateTime.Now) )
       .Insert( x => new SellRecord{ Total = x.Name, Date = DateTime.Now })

Now, the collection wrapped by IMagiq is the destination and it could have the constraint.

So, summarizing:

  • Magiq() Extension method was added
  • IMagiq adds support to plugins
  • Insert API changed to destination.From( source ).Insert( new )

Magiq-0.2.0 is avaliable!

January 26, 2010 Leave a comment

I’m glad to annunce that the new version of Magiq is out. You can download it here.

Magiq 0.2.0 supports:

  • Mass operations to Linq-to-sql collections (EntitySet)
  • Collection filterig support for Linq-to-sql
  • Support to sorting and grouping
  • Supports when you want to insert into a repository from another one (for example, insert a lot of entities from a string collection). In this case, it uses the same approach as using a foreach, but it works 😉

First release of Magiq: 0.1.0

January 5, 2010 2 comments

I’m glad to annunce that the first version of Magiq is finished. It fully supports Magiq-to-objects and Magiq-to-sql.
The future plan includes Magiq-to-NHibernate and Magiq-to-Entities.
You can download it here. Also, you can read the brief documentation.