/// <summary>
        /// Executes a sql statement on a given table in local SQLCe database.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="sql">The SQL query to execute.</param>
        /// <param name="parameters">The query parameters.</param>
        /// <returns>The result of query.</returns>
        protected virtual IList <JObject> ExecuteQuery(string tableName, string sql, IDictionary <string, object> parameters)
        {
            TableDefinition table = GetTable(tableName);

            return(this.ExecuteQuery(table, sql, parameters));
        }
        private Task UpsertAsyncInternal(string tableName, IEnumerable <JObject> items, bool fromServer)
        {
            TableDefinition table = GetTable(tableName);

            var first = items.FirstOrDefault();

            if (first == null)
            {
                return(Task.FromResult(0));
            }

            // Get the columns which we want to map into the database.
            var columns = new List <ColumnDefinition>();

            foreach (var prop in first.Properties())
            {
                ColumnDefinition column;

                // If the column is coming from the server we can just ignore it,
                // otherwise, throw to alert the caller that they have passed an invalid column
                if (!table.TryGetValue(prop.Name, out column) && !fromServer)
                {
                    throw new InvalidOperationException(string.Format(Properties.Resources.SqlCeStore_ColumnNotDefined, prop.Name, tableName));
                }

                if (column != null)
                {
                    columns.Add(column);
                }
            }

            if (columns.Count == 0)
            {
                // no query to execute if there are no columns in the table
                return(Task.FromResult(0));
            }

            var insertSqlBase = String.Format(
                "INSERT INTO {0} ({1}) VALUES ",
                SqlHelpers.FormatTableName(tableName),
                String.Join(", ", columns.Select(c => c.Name).Select(SqlHelpers.FormatMember))
                );

            var updateSqlBase = String.Format("UPDATE {0} SET ", SqlHelpers.FormatTableName(tableName));

            // Use int division to calculate how many times this record will fit into our parameter quota
            int batchSize = MaxParametersPerUpsertQuery / columns.Count;

            if (batchSize == 0)
            {
                throw new InvalidOperationException(string.Format(Properties.Resources.SqlCeStore_TooManyColumns, MaxParametersPerUpsertQuery));
            }

            foreach (var batch in items.Split(maxLength: batchSize))
            {
                StringBuilder sql = new StringBuilder();

                var parameters = new Dictionary <string, object>();

                foreach (JObject item in batch)
                {
                    // there's no upsert in SQL CE so we'll settle if an 'If Not Exist, Insert' approach
                    if (!RowExists(SqlHelpers.FormatTableName(tableName),
                                   item.GetValue(MobileServiceSystemColumns.Id, StringComparison.OrdinalIgnoreCase).ToString()))
                    {
                        sql = new StringBuilder(insertSqlBase);
                        AppendInsertValuesSql(sql, parameters, columns, item);
                    }
                    else
                    {
                        sql = new StringBuilder(updateSqlBase);
                        AppendUpdateValuesSql(sql, parameters, columns, item);
                        string updateCondition = string.Format(" WHERE {0} = '{1}'", MobileServiceSystemColumns.Id, item.GetValue(MobileServiceSystemColumns.Id, StringComparison.OrdinalIgnoreCase).ToString());
                        sql.Append(updateCondition);
                    }

                    if (parameters.Any())
                    {
                        this.ExecuteNonQuery(sql.ToString(), parameters);
                    }
                }
            }

            return(Task.FromResult(0));
        }