コード例 #1
0
        protected internal int ExecuteNonQuery(string sqlQuery, CSParameterCollection parameters)
        {
            long logId = Log(sqlQuery, parameters);


            try
            {
                using (ICSDbCommand dbCommand = CreateCommandInternal(sqlQuery, parameters))
                    dbCommand.ExecuteNonQuery();

                return(1);
            }
            catch (InvalidOperationException)
            {
                return(-1);
            }
            catch (Exception ex)
            {
                throw new CSSQLException("ExecuteNonQuery exception", ex, sqlQuery, parameters);
            }
            finally
            {
                LogEnd(logId);

                CSNameGenerator.Reset();
            }
        }
コード例 #2
0
        internal object GetScalar(string sqlQuery, CSParameterCollection parameters)
        {
            long logId = Log(sqlQuery, parameters);

            try
            {
                using (ICSDbCommand dbCommand = CreateCommandInternal(sqlQuery, parameters))
                {
                    using (ICSDbReader reader = dbCommand.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            object r = reader[0];

                            return((r is DBNull) ? null : r);
                        }
                    }
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw new CSSQLException("GetScalar exception", ex, sqlQuery, parameters);
            }
            finally
            {
                LogEnd(logId);

                CSNameGenerator.Reset();
            }
        }
コード例 #3
0
        protected override ICSDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            SqliteCommand sqlCommand = ((CSSqliteCommand)Connection.CreateCommand()).Command;

            if (CurrentTransaction != null)
            {
                sqlCommand.Transaction = ((CSSqliteTransaction)CurrentTransaction).Transaction;
            }

            sqlCommand.CommandType = CommandType.Text;

            sqlCommand.CommandText = Regex.Replace(sqlQuery, @"@(?<name>[a-z0-9A-Z_]+)", "@${name}");

            if (parameters != null && !parameters.IsEmpty)
            {
                foreach (CSParameter parameter in parameters)
                {
                    IDbDataParameter dataParameter = sqlCommand.CreateParameter();

                    dataParameter.ParameterName = "@" + parameter.Name.Substring(1);
                    dataParameter.Direction     = ParameterDirection.Input;
                    dataParameter.Value         = ConvertParameter(parameter.Value);

                    sqlCommand.Parameters.Add(dataParameter);
                }
            }

            return(new CSSqliteCommand(sqlCommand));
        }
コード例 #4
0
        protected override IDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            VistaDBCommand sqlCommand = (VistaDBCommand)Connection.CreateCommand();

            sqlCommand.Transaction = (VistaDBTransaction)CurrentTransaction;

            if (sqlQuery.StartsWith("!"))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                sqlCommand.CommandText = sqlQuery.Substring(1);
            }
            else
            {
                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.CommandText = sqlQuery;
            }

            if (parameters != null && !parameters.IsEmpty)
            {
                foreach (CSParameter csParameter in parameters)
                {
                    IDbDataParameter dataParameter = sqlCommand.CreateParameter();

                    dataParameter.ParameterName = csParameter.Name;
                    dataParameter.Direction     = ParameterDirection.Input;
                    dataParameter.Value         = ConvertParameter(csParameter.Value);

                    sqlCommand.Parameters.Add(dataParameter);
                }
            }

            return(sqlCommand);
        }
コード例 #5
0
ファイル: CSFilter.cs プロジェクト: activa/vici.coolstorage
        public CSFilter(CSFilter filter1, string andOr, CSFilter filter2)
        {
            if (filter1.IsBlank && filter2.IsBlank)
            {
                _expression = "";
                _parameters = new CSParameterCollection();
            }
            else if (filter1.IsBlank)
            {
                _expression = "(" + filter2.Expression + ")";
                _parameters = new CSParameterCollection(filter2.Parameters);
                return;
            }
            else if (filter2.IsBlank)
            {
                _expression = "(" + filter1.Expression + ")";
                _parameters = new CSParameterCollection(filter1.Parameters);
            }
            else
            {
                _expression = "(" + filter1._expression + ") " + andOr + " (" + filter2.Expression + ")";

                _parameters = new CSParameterCollection(filter1.Parameters);
                _parameters.Add(filter2.Parameters);
            }
        }
コード例 #6
0
        protected static long Log(string cmd, CSParameterCollection parameters)
        {
            _numQueries++;
            _lastQuery = cmd;

            long logId;

            lock (_logLock)
            {
                logId = ++_lastLogId;

                if (!CSConfig.Logging)
                {
                    return(logId);
                }

                _logTimings.Add(logId, DateTime.Now);

                try
                {
                    using (StreamWriter writer = File.AppendText(CSConfig.LogFileName))
                    {
                        writer.WriteLine("{0} | {2:000000} | {1}", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff"), cmd, logId);

                        if (parameters != null && parameters.Count > 0)
                        {
                            StringBuilder p = new StringBuilder();

                            foreach (CSParameter csParameter in parameters)
                            {
                                string value = "<null>";

                                if (csParameter.Value != null)
                                {
                                    value = csParameter.Value + "(" + csParameter.Value.GetType().Name + ")";
                                }

                                if (value.Length > 30)
                                {
                                    value = value.Substring(0, 30) + "...";
                                }

                                p.Append(csParameter.Name + "=" + ((csParameter.Value is string) ? "\"" : "") + value + ((csParameter.Value is string) ? "\"" : "") + " | ");
                            }

                            writer.WriteLine("{0} | {2:000000} | {1}", new string(' ', 23), p, logId);
                        }
                    }
                }
                // ReSharper disable EmptyGeneralCatchClause
                catch
                {
                    // Couldn't care less
                }
                // ReSharper restore EmptyGeneralCatchClause
            }

            return(logId);
        }
コード例 #7
0
        public static CSList <T> OrderedList(string orderBy, string filter, CSParameterCollection parameters)
        {
            CSList <T> list = List(filter, parameters);

            list.OrderBy = orderBy;

            return(list);
        }
コード例 #8
0
ファイル: CSDatabase.cs プロジェクト: BRychlik/coolstorage
        private T[] RunQuery <T>(string sql, CSParameterCollection parameters, int maxRows) where T : new()
        {
            Type objectType = typeof(T);

            List <T> list = new List <T>();

            if (maxRows == 0)
            {
                maxRows = int.MaxValue;
            }

            using (new CSTransaction(DB))
            {
                using (ICSDbReader reader = DB.CreateReader(sql ?? CSHelper.GetQueryExpression <T>(), parameters))
                {
                    int rowNum = 0;

                    while (rowNum < maxRows && reader.Read())
                    {
                        rowNum++;

                        T obj = new T();

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            string columnName = reader.GetName(i);

                            PropertyInfo propertyInfo = objectType.GetProperty(columnName);

                            object columnValue = reader[i];

                            if (columnValue is DBNull)
                            {
                                columnValue = null;
                            }

                            if (propertyInfo != null)
                            {
                                propertyInfo.SetValue(obj, columnValue.Convert(propertyInfo.PropertyType), null);
                            }
                            else
                            {
                                FieldInfo fieldInfo = objectType.GetField(columnName);

                                if (fieldInfo != null)
                                {
                                    fieldInfo.SetValue(obj, columnValue.Convert(fieldInfo.FieldType));
                                }
                            }
                        }

                        list.Add(obj);
                    }
                }
            }

            return(list.ToArray());
        }
コード例 #9
0
 public void Add(CSParameterCollection parameters)
 {
     if (parameters != null)
     {
         foreach (CSParameter param in parameters)
         {
             Add(param.Name, param.Value);
         }
     }
 }
コード例 #10
0
        protected internal ICSDbCommand CreateCommandInternal(string sqlQuery, CSParameterCollection parameters)
        {
            ICSDbCommand command = CreateCommand(sqlQuery, parameters);

            if (CSConfig.CommandTimeout.HasValue)
            {
                command.CommandTimeout = CSConfig.CommandTimeout.Value;
            }

            return(command);
        }
コード例 #11
0
        private List <TObjectType> GetObjects(string sqlQuery, CSParameterCollection parameters, Dictionary <string, string> aliasMap, IEnumerable <PrefetchField> prefetchFields)
        {
            using (CSTransaction csTransaction = new CSTransaction(Schema))
            {
                List <TObjectType> objectList = new List <TObjectType>();

                using (ICSDbReader reader = DB.CreateReader(sqlQuery, parameters))
                {
                    while (reader.Read())
                    {
                        TObjectType csObject = CSObject <TObjectType> .New();

                        csObject.Fire_ObjectReading();

                        csObject.FromDataReader(reader, aliasMap);

                        foreach (PrefetchField prefetchField in prefetchFields)
                        {
                            csObject.ReadRelationToOne(prefetchField.SchemaField, reader, prefetchField.AliasMap);
                        }

                        if (FilterPredicate != null)
                        {
                            bool shouldAdd = true;

                            foreach (Predicate <TObjectType> predicate in FilterPredicate.GetInvocationList())
                            {
                                if (!predicate(csObject))
                                {
                                    shouldAdd = false;
                                    break;
                                }
                            }

                            if (!shouldAdd)
                            {
                                continue;
                            }
                        }

                        csObject.ObjectDeleted += OnObjectDeleted;

                        objectList.Add(csObject);

                        csObject.Fire_ObjectRead();
                    }
                }

                csTransaction.Commit();

                return(objectList);
            }
        }
コード例 #12
0
        protected override ICSDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            OracleCommand oracleCommand = ((CSOracleCommand)Connection.CreateCommand()).Command;

            if (CurrentTransaction != null)
            {
                oracleCommand.Transaction = ((CSOracleTransaction)CurrentTransaction).Transaction;
            }

            oracleCommand.BindByName = true;

            if (sqlQuery.StartsWith("!"))
            {
                oracleCommand.CommandType = CommandType.StoredProcedure;
                oracleCommand.CommandText = sqlQuery.Substring(1);
            }
            else
            {
                oracleCommand.CommandType = CommandType.Text;
                oracleCommand.CommandText = sqlQuery;
            }

            oracleCommand.CommandText = Regex.Replace(sqlQuery, @"@(?<name>[a-z0-9A-Z_]+)", ":${name}");

            if (parameters != null && !parameters.IsEmpty)
            {
                foreach (CSParameter parameter in parameters)
                {
                    OracleParameter dataParameter = oracleCommand.CreateParameter();

                    dataParameter.ParameterName = ":" + parameter.Name.Substring(1);
                    dataParameter.Direction     = ParameterDirection.Input;

                    if (parameter.Value is Guid)
                    {
                        dataParameter.Value = ((Guid)parameter.Value).ToByteArray();
                    }
                    else if (parameter.Value is Boolean)
                    {
                        dataParameter.Value = ((Boolean)parameter.Value) ? 1 : 0;
                    }
                    else
                    {
                        dataParameter.Value = ConvertParameter(parameter.Value);
                    }

                    oracleCommand.Parameters.Add(dataParameter);
                }
            }

            return(new CSOracleCommand(oracleCommand));
        }
コード例 #13
0
        protected CSFilter BuildRelationFilter(string tableAlias)
        {
            if (tableAlias == null)
            {
                tableAlias = "";
            }
            else
            {
                tableAlias += ".";
            }

            if (Relation != null)
            {
                CSParameterCollection parameters = new CSParameterCollection();

                switch (Relation.RelationType)
                {
                case CSSchemaRelationType.OneToMany:
                {
                    CSParameter csParameter = parameters.Add();

                    csParameter.Value = RelationObject.Data["#" + Relation.LocalKey].Value;

                    return(new CSFilter("{" + tableAlias + Relation.ForeignKey + "}=" + csParameter.Name, parameters));
                }

                case CSSchemaRelationType.ManyToMany:
                {
                    if (Relation.ForeignKey == null)
                    {
                        Relation.ForeignKey = Schema.KeyColumns[0].Name;
                    }

                    if (Relation.ForeignLinkKey == null)
                    {
                        Relation.ForeignLinkKey = Relation.ForeignKey;
                    }

                    CSParameter csParameter = parameters.Add();

                    csParameter.Value = RelationObject.Data["#" + Relation.LocalKey].Value;

                    return(new CSFilter("{" + tableAlias + Relation.ForeignKey + "} $in ($select {" + Relation.ForeignLinkKey + "} $from [" + Relation.LinkTable + "] where {" + Relation.LocalLinkKey + "}=" + csParameter.Name + ")", parameters));
                }
                }
            }

            return(CSFilter.None);
        }
コード例 #14
0
ファイル: CSDatabase.cs プロジェクト: BRychlik/coolstorage
        public T[] GetScalarList <T>(string sql, CSParameterCollection parameters)
        {
            List <T> list = new List <T>();

            using (new CSTransaction(DB))
            {
                using (ICSDbReader reader = DB.CreateReader(sql, parameters))
                {
                    while (reader.Read())
                    {
                        list.Add(reader[0].Convert <T>());
                    }
                }
            }

            return(list.ToArray());
        }
コード例 #15
0
        protected override ICSDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            OleDbCommand dbCommand = ((CSAccessCommand)Connection.CreateCommand()).Command;

            dbCommand.Transaction = ((CSAccessTransaction)CurrentTransaction).Transaction;

            foreach (Match m in Regex.Matches(sqlQuery, "(?<!@)@[a-z_0-9]+", RegexOptions.IgnoreCase))
            {
                dbCommand.Parameters.AddWithValue(m.Value, ConvertParameter(parameters[m.Value].Value));
            }

            sqlQuery = Regex.Replace(sqlQuery, "(?<!@)@[a-z_0-9]+", "?", RegexOptions.IgnoreCase);

            dbCommand.CommandType = CommandType.Text;
            dbCommand.CommandText = sqlQuery;

            return(new CSAccessCommand(dbCommand));
        }
コード例 #16
0
        protected internal ICSDbReader CreateReader(string sqlQuery, CSParameterCollection parameters)
        {
            long logId = Log(sqlQuery, parameters);

            try
            {
                using (ICSDbCommand dbCommand = CreateCommandInternal(sqlQuery, parameters))
                    return(dbCommand.ExecuteReader());
            }
            catch (Exception ex)
            {
                throw new CSSQLException("Error executing query. Possible syntax error", ex, sqlQuery, parameters);
            }
            finally
            {
                LogEnd(logId);

                CSNameGenerator.Reset();
            }
        }
コード例 #17
0
ファイル: CSDatabase.cs プロジェクト: BRychlik/coolstorage
        public CSGenericRecord RunSingleQuery(string sql, CSParameterCollection parameters)
        {
            CSGenericRecord rec = new CSGenericRecord();

            using (new CSTransaction(DB))
            {
                using (ICSDbReader reader = DB.CreateReader(sql, parameters))
                {
                    if (reader.Read())
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            rec[reader.GetName(i)] = (reader[i] is DBNull) ? null : reader[i];
                        }

                        return(rec);
                    }
                }
            }

            return(null);
        }
コード例 #18
0
        protected override ICSDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            MySqlCommand mySqlCommand = ((CSSqlCommand)Connection.CreateCommand()).Command;

            if (CurrentTransaction != null)
            {
                mySqlCommand.Transaction = ((CSSqlTransaction)CurrentTransaction).Transaction;
            }

            if (sqlQuery.StartsWith("!"))
            {
                mySqlCommand.CommandType = CommandType.StoredProcedure;
                mySqlCommand.CommandText = sqlQuery.Substring(1);
            }
            else
            {
                mySqlCommand.CommandType = CommandType.Text;
                mySqlCommand.CommandText = sqlQuery;
            }

            mySqlCommand.CommandText = Regex.Replace(sqlQuery, @"@(?<name>[a-z0-9A-Z_]+)", "?${name}");

            if (parameters != null && !parameters.IsEmpty)
            {
                foreach (CSParameter parameter in parameters)
                {
                    IDbDataParameter dataParameter = mySqlCommand.CreateParameter();

                    dataParameter.ParameterName = "?" + parameter.Name.Substring(1);
                    dataParameter.Direction     = ParameterDirection.Input;
                    dataParameter.Value         = ConvertParameter(parameter.Value);

                    mySqlCommand.Parameters.Add(dataParameter);
                }
            }

            return(new CSSqlCommand(mySqlCommand));
        }
コード例 #19
0
        protected override ICSDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            SQLiteCommand sqlCommand = ((CSSqliteCommand)Connection.CreateCommand()).Command;

            if (CurrentTransaction != null)
            {
                sqlCommand.Transaction = ((CSSqliteTransaction)CurrentTransaction).Transaction;
            }

            if (sqlQuery.ToUpper().StartsWith("DELETE ") || sqlQuery.ToUpper().StartsWith("SELECT ") || sqlQuery.ToUpper().StartsWith("UPDATE ") || sqlQuery.ToUpper().StartsWith("INSERT ") || sqlQuery.ToUpper().StartsWith("CREATE "))
            {
                sqlCommand.CommandType = CommandType.Text;
            }
            else
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
            }

            sqlCommand.CommandText = Regex.Replace(sqlQuery, @"@(?<name>[a-z0-9A-Z_]+)", "@${name}");

            if (parameters != null && !parameters.IsEmpty)
            {
                foreach (CSParameter parameter in parameters)
                {
                    IDbDataParameter dataParameter = sqlCommand.CreateParameter();

                    dataParameter.ParameterName = "@" + parameter.Name.Substring(1);
                    dataParameter.Direction     = ParameterDirection.Input;
                    dataParameter.Value         = ConvertParameter(parameter.Value);

                    sqlCommand.Parameters.Add(dataParameter);
                }
            }

            return(new CSSqliteCommand(sqlCommand));
        }
コード例 #20
0
ファイル: CSDatabase.cs プロジェクト: BRychlik/coolstorage
        public CSGenericRecordList RunQuery(string sql, CSParameterCollection parameters)
        {
            CSGenericRecordList list = new CSGenericRecordList();

            using (new CSTransaction(DB))
            {
                using (ICSDbReader reader = DB.CreateReader(sql, parameters))
                {
                    while (reader.Read())
                    {
                        CSGenericRecord record = new CSGenericRecord();

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            record[reader.GetName(i)] = (reader[i] is DBNull) ? null : reader[i];
                        }

                        list.Add(record);
                    }
                }
            }

            return(list);
        }
コード例 #21
0
        protected override IDbCommand CreateCommand(string sqlQuery, CSParameterCollection parameters)
        {
            DB2Command dbCommand = (DB2Command)Connection.CreateCommand();

            dbCommand.Transaction = (DB2Transaction)CurrentTransaction;

            if (parameters != null && !parameters.IsEmpty)
            {
                int paramNum = 1;

                foreach (Match m in Regex.Matches(sqlQuery, "@[a-z_0-9]+", RegexOptions.IgnoreCase))
                {
                    if (parameters[m.Value] == null)
                    {
                        throw new CSException("Parameter " + m.Value + " undefined");
                    }

                    dbCommand.Parameters.Add(new DB2Parameter("@P" + (paramNum++), ConvertParameter(parameters[m.Value].Value)));
                }

                sqlQuery = Regex.Replace(sqlQuery, "@[a-z_0-9]+", "?", RegexOptions.IgnoreCase);
            }

            if (sqlQuery.StartsWith("!"))
            {
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.CommandText = sqlQuery.Substring(1);
            }
            else
            {
                dbCommand.CommandType = CommandType.Text;
                dbCommand.CommandText = sqlQuery;
            }

            return(dbCommand);
        }
コード例 #22
0
        protected override IDataReader ExecuteInsert(string tableName, string[] columnList, string[] valueList, string[] primaryKeys, string[] sequences, string identityField, CSParameterCollection parameters)
        {
            string sql = "";

            if (columnList.Length > 0)
            {
                List <string> list = new List <string>();

                for (int i = 0; i < valueList.Length; i++)
                {
                    if (sequences != null && sequences[i] != null)
                    {
                        list.Add(QuoteField(sequences[i]) + ".nextval");
                    }
                    else
                    {
                        list.Add(valueList[i]);
                    }
                }

                sql += String.Format("insert into {0} ({1}) values ({2})",
                                     QuoteTable(tableName),
                                     String.Join(",", QuoteFieldList(columnList)),
                                     String.Join(",", list.ToArray())
                                     );
            }
            else
            {
                sql += String.Format("insert into {0} () values ()", QuoteTable(tableName));
            }

            sql += " RETURNING rowid INTO :IDVAL";


            long logId = Log(sql, parameters);

            OracleString rowid;

            try
            {
                using (IDbCommand cmd = CreateCommand(sql, parameters))
                {
                    OracleParameter parameter = new OracleParameter(":IDVAL", OracleDbType.Varchar2, 18, "ROWID");

                    parameter.Direction = ParameterDirection.ReturnValue;

                    cmd.Parameters.Add(parameter);

                    cmd.ExecuteNonQuery();

                    rowid = (OracleString)parameter.Value;
                }
            }
            finally
            {
                LogEnd(logId);
            }

            if (primaryKeys == null || primaryKeys.Length == 0)
            {
                return(null);
            }

            sql = String.Format("SELECT {0} from {1} where rowid = :IDVAL", String.Join(",", QuoteFieldList(primaryKeys)), QuoteTable(tableName));

            using (IDbCommand cmd = CreateCommand(sql, null))
            {
                cmd.Parameters.Add(new OracleParameter(":IDVAL", rowid));

                return(cmd.ExecuteReader());
            }
        }
コード例 #23
0
        public object GetScalar(string fieldName, CSAggregate aggregate, string filterExpression, CSParameterCollection filterParameters)
        {
            string tableAlias = CSNameGenerator.NextTableAlias;

            CSFilter queryFilter = Filter.And(BuildRelationFilter(tableAlias));

            if (!string.IsNullOrEmpty(filterExpression))
            {
                queryFilter = queryFilter.And(filterExpression, filterParameters);
            }

            return(CSObject <TObjectType> .GetScalar(fieldName, tableAlias, aggregate, queryFilter));
        }
コード例 #24
0
        public override bool Save()
        {
            if (!Populated)
            {
                return(true);
            }

            using (CSTransaction csTransaction = new CSTransaction(Schema, CSIsolationLevel.ReadUncommitted))
            {
                UpdateForeignKeys();

                foreach (TObjectType obj in _objectArray.ToArray())
                {
                    if (obj.IsDirty)
                    {
                        if (!obj.Save())
                        {
                            return(false);
                        }
                    }
                }

                if (Relation != null && Relation.PureManyToMany)
                {
                    if (_removedObjects != null)
                    {
                        foreach (TObjectType obj in _removedObjects)
                        {
                            CSParameterCollection parameters = new CSParameterCollection();

                            parameters.Add("@LocalKey").Value   = RelationObject.Data["#" + Relation.LocalKey].Value;
                            parameters.Add("@ForeignKey").Value = obj.Data["#" + Relation.ForeignKey].Value;

                            string deleteSql = DB.BuildDeleteSQL(Relation.LinkTable, null, DB.QuoteField(Relation.LocalLinkKey) + "=@LocalKey and " + DB.QuoteField(Relation.ForeignLinkKey) + "=@ForeignKey");

                            DB.ExecuteNonQuery(deleteSql, parameters);
                        }

                        _removedObjects = null;
                    }

                    if (_addedObjects != null)
                    {
                        foreach (TObjectType obj in _addedObjects)
                        {
                            CSParameterCollection parameters = new CSParameterCollection();

                            parameters.Add("@LocalKey").Value   = RelationObject.Data["#" + Relation.LocalKey].Value;
                            parameters.Add("@ForeignKey").Value = obj.Data["#" + Relation.ForeignKey].Value;

                            DB.ExecuteInsert(Relation.LinkTable,
                                             new[] { Relation.LocalLinkKey, Relation.ForeignLinkKey },
                                             new[] { "@LocalKey", "@ForeignKey" },
                                             null, null, null, parameters);

//                            string insertSql =
//                                DB.BuildInsertSQL(Relation.LinkTable,
//                                                new[] { Relation.LocalLinkKey, Relation.ForeignLinkKey },
//                                                new[] { "@LocalKey", "@ForeignKey" },
//                                                null, null, null);

                            //DB.ExecuteNonQuery(insertSql, parameters);
                        }
                    }
                }

                csTransaction.Commit();

                return(true);
            }
        }
コード例 #25
0
 public CSList <TObjectType> FilteredBy(string filter, CSParameterCollection parameters)
 {
     return(FilteredBy(new CSFilter(filter, parameters)));
 }
コード例 #26
0
 public CSList(string filterExpression, CSParameterCollection parameters)
     : this(new CSFilter(filterExpression, parameters))
 {
 }
コード例 #27
0
 public CSParameterCollection(CSParameterCollection sourceCollection)
 {
     Add(sourceCollection);
 }
コード例 #28
0
        /// <summary>
        /// Physically deletes the object from the database
        /// </summary>
        /// <returns><c>true</c> if the object was deleted successfully. Otherwise <c>false</c></returns>
        public bool Delete()
        {
            if (_dataState == CSObjectDataState.Deleted || _dataState == CSObjectDataState.New)
            {
                return(false);
            }

            bool cancel = false;

            Fire_ObjectDeleting(ref cancel);

            if (cancel)
            {
                return(false);
            }

            StringBuilder whereClause = new StringBuilder();

            CSParameterCollection parameters = new CSParameterCollection();

            foreach (CSSchemaColumn schemaColumn in _schema.Columns)
            {
                if (!schemaColumn.IsKey)
                {
                    continue;
                }

                CSParameter parameter = parameters.Add();

                parameter.Value = _fieldData["#" + schemaColumn.Name].ValueDirect;

                if (whereClause.Length > 0)
                {
                    whereClause.Append(" and ");
                }

                whereClause.Append(_schema.DB.QuoteField(schemaColumn.Name) + "=@" + parameter.Name.Substring(1));
            }

            if (whereClause.Length == 0)
            {
                throw new CSException("No key fields");
            }

            using (CSTransaction csTransaction = new CSTransaction(_schema))
            {
                string deleteSql = _schema.DB.BuildDeleteSQL(_schema.TableName, null, whereClause.ToString());

                int numDeleted = _schema.DB.ExecuteNonQuery(deleteSql, parameters);

                if (numDeleted == 1)
                {
                    csTransaction.Commit();
                }
                else
                {
                    return(false);
                }
            }

            _dataState = CSObjectDataState.Deleted;

            Fire_ObjectDeleted();

            return(true);
        }
コード例 #29
0
        private bool Create()
        {
            CSParameterCollection parameters = new CSParameterCollection();

            List <string> fieldNames    = new List <string>();
            List <string> fieldValues   = new List <string>();
            List <string> sequenceNames = new List <string>();

            foreach (CSSchemaColumn schemaColumn in _schema.Columns)
            {
                CSFieldValue fieldValue = _fieldData["#" + schemaColumn.Name];

                if (fieldValue == null)
                {
                    continue;
                }

                CSSchemaField schemaField = fieldValue.SchemaField;

                if (schemaField.ClientGenerated && schemaColumn.IsKey)
                {
                    if (schemaField.FieldType == typeof(Guid))
                    {
                        fieldValue.Value = Guid.NewGuid();
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(schemaField.SequenceName) && (!fieldValue.IsDirty || schemaField.ReadOnly || schemaField.NoCreate || schemaColumn.Identity))
                    {
                        continue;
                    }
                }

                if (schemaField.ServerGenerated && schemaColumn.IsKey)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(schemaField.SequenceName))
                {
                    sequenceNames.Add(schemaField.SequenceName);
                    fieldValues.Add(null);
                }
                else
                {
                    CSParameter parameter = parameters.Add();

                    parameter.Value = fieldValue.ValueDirect;

                    fieldValues.Add("@" + parameter.Name.Substring(1));
                    sequenceNames.Add(null);
                }

                fieldNames.Add(schemaColumn.Name);
            }

            string[] primaryKeys = new string[_schema.KeyColumns.Count];

            for (int i = 0; i < _schema.KeyColumns.Count; i++)
            {
                primaryKeys[i] = _schema.KeyColumns[i].Name;
            }


            using (ICSDbReader reader = _schema.DB.ExecuteInsert(_schema.TableName, fieldNames.ToArray(), fieldValues.ToArray(), primaryKeys, sequenceNames.ToArray(), (_schema.IdentityColumn != null && _schema.IdentityColumn.MappedField != null) ? _schema.IdentityColumn.Name : null, parameters))
            {
                if (reader != null && !reader.IsClosed && reader.Read())
                {
                    FromDataReader(reader, null);
                }
            }

            _dataState = CSObjectDataState.Loaded;

            return(true);
        }
コード例 #30
0
        private bool Write()
        {
            if (!_fieldData.IsDirty)
            {
                return(true);
            }

            if (_dataState == CSObjectDataState.Deleted)
            {
                return(false);
            }

            List <string> fieldNames  = new List <string>();
            List <string> fieldValues = new List <string>();

            CSFilter whereClause = new CSFilter();

            CSParameterCollection parameters = new CSParameterCollection();

            foreach (CSSchemaColumn schemaColumn in _schema.Columns)
            {
                CSFieldValue fieldValue = _fieldData["#" + schemaColumn.Name];

                if (!schemaColumn.IsKey && (fieldValue == null || !fieldValue.IsDirty || fieldValue.SchemaField.ReadOnly))
                {
                    continue;
                }

                CSParameter parameter = parameters.Add();

                parameter.Value = fieldValue.ValueDirect;

                if (schemaColumn.IsKey)
                {
                    whereClause = whereClause.And(_schema.DB.QuoteField(schemaColumn.Name) + "=@" + parameter.Name.Substring(1));
                }

                if (fieldValue.IsDirty && !fieldValue.SchemaField.ReadOnly && !schemaColumn.Identity && !schemaColumn.ReadOnly)
                {
                    fieldNames.Add(schemaColumn.Name);
                    fieldValues.Add("@" + parameter.Name.Substring(1));
                }

                fieldValue.ValueState = CSFieldValueState.Read;
            }

            if (whereClause.Expression.Length == 0)
            {
                throw new CSException("No key fields");
            }

            if (fieldValues.Count > 0)
            {
                string sqlQuery = _schema.DB.BuildUpdateSQL(_schema.TableName, fieldNames.ToArray(), fieldValues.ToArray(), whereClause.Expression);

                if (_schema.DB.ExecuteNonQuery(sqlQuery, parameters) != 1)
                {
                    return(false);
                }
            }

            return(true);
        }