Beispiel #1
0
		/// <summary>
		/// Default constructor
		/// </summary>
		/// <param name="date">DateTime of error</param>
		/// <param name="instance">Server instance of error</param>
		/// <param name="queryItem">Query</param>
		/// <param name="error">Thrown exception</param>
		public ErrorLogItem(DateTime date, InstanceInfo instance, QueryItemInfo queryItem, Exception error)
		{
			this._date      = date;
			this._instance  = instance;
			this._queryItem = queryItem;
			this._error     = error;
		}
        public abstract long? GetQueryId(
			TemplateNodeInfo      node,
			TemplateNodeQueryInfo templateNodeQuery,
			InstanceInfo          instance,
			DateTime              dateCreated,
			bool                  onlyFind
		);
        /// <summary>
        /// Get Id for data
        /// </summary>
        /// <param name="connectionGroup">Connection group</param>
        /// <param name="instance">Instance</param>
        /// <returns></returns>
        public Int64? GetId(ConnectionGroupInfo connectionGroup, InstanceInfo instance)
        {
            connectionGroup.ReadGroupIdFrom(Storage.ConnectionGroupDirectory);

            Int64?           loginId    = Storage.LoginDirectory.GetId(instance);
            ServerProperties props      = instance.ServerProperties;
            string           serverName = null;
            string           serverVers = null;

            if (props != null)
            {
                serverName = props.Name;
                serverVers = props.Version.ToString();
            }

            return this.GetRecordIdByFields(
                this.CreateField(ConnectionGroupIdFn,     connectionGroup.Identity),
                this.CreateField(LoginIdFn,               loginId),
                this.CreateField(ConnectionNameFn,        instance.Name),
                this.CreateField(ServerInstanceNameFn,    serverName),
                this.CreateField(ServerInstanceVersionFn, serverVers),
                this.CreateField(DbTypeFn,                instance.DbType),
                this.CreateField(IsOdbcFn,                instance.IsODBC),
                this.CreateField(IsDynamicConnectionFn,   instance.IsDynamicConnection)
            );
        }
			public static Func<InstanceInfo, bool> MatchesTo(InstanceInfo instance)
			{
				Func<InstanceInfo, bool> matchingPredicate =
					x => x.GetConnectionString() == instance.GetConnectionString();

				return matchingPredicate;
			}
		public static ServerProperties Load(
			InstanceInfo        instance,
			CurrentStorage      storage
		)
		{
			ServerProperties storedProps = storage.ServerInstanceDirectory
				.GetServerProperties(instance);

			return storedProps;
		}
		private static ServerProperties QueryMssql(
			InstanceInfo instance,
			int          timeout = 0
		)
		{
			string   sqlString  = string.Empty;
			string   serverName = string.Empty;
			DateTime serverDate = DateTime.MaxValue;

			using (DbConnection dbConnection = CreateMssqlConnection(instance))
			{
				dbConnection.Open();

				InstanceVersion version = new InstanceVersion(dbConnection.ServerVersion);

				bool isNewServer = version.Major >= 8;  // MS SQL Server 2000

				if (isNewServer)
				{
					sqlString = "SELECT SERVERPROPERTY(N'ServerName') AS [ServerName], " +
					            "SERVERPROPERTY(N'InstanceName') AS [InstanceName], " +
					            "GetDate() AS [InstanceDate];";
				}
				else
				{
					sqlString = "SELECT GetDate() AS [InstanceDate];";
				}

				using (DbCommand command = dbConnection.CreateCommand())
				{
					command.CommandText = sqlString;

					if (timeout != 0)
					{
						command.CommandTimeout = timeout;
					}

					using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
					{
						if (reader.Read())
						{
							serverName = isNewServer
								? reader["ServerName"].ToString()
								: dbConnection.DataSource;

							serverDate = DateTime.Parse(reader["InstanceDate"].ToString());
						}
					}
				}

				return new ServerProperties(version, serverName, serverDate);
			}
		}
		/// <summary>
		/// Get Row id for data
		/// </summary>
		/// <param name="instance">Instance</param>
		/// <returns></returns>
		public Int64? GetId(InstanceInfo instance)
		{
			AuthenticationInfo auth = instance.Authentication;

			ICryptoService cipher = this.Storage.CryptoService;

			return this.GetRecordIdByFields(
				this.CreateField(LoginFn,     auth.GetCurrentLogin()),
				this.CreateField(PasswordFn,  cipher.Encrypt(auth.Password)),
				this.CreateField(IsWinAuthFn, auth.IsWindows)
			);
		}
		public static ServerProperties Query(
			InstanceInfo instance,
			int          timeout = 0
		)
		{
			switch (instance.Type)
			{
				case QuerySource.MSSQL:
					return QueryMssql(instance, timeout);
				case QuerySource.TDSQL:
					return QueryTeradata(instance, timeout);
				default:
					return GetBlackProperties(instance);
			}
		}
Beispiel #9
0
        private static ServerProperties QueryTeradata(
            InstanceInfo instance,
            int timeout = 0
            )
        {
            using (DbConnection dbConnection = CreateTeradataConnection(instance))
            {
                dbConnection.Open();

                InstanceVersion version    = new InstanceVersion(dbConnection.ServerVersion);
                DateTime        serverDate = DateTime.MaxValue;

                using (DbCommand command = dbConnection.CreateCommand())
                {
                    command.CommandText = "SELECT CURRENT_DATE AS InstanceDate";

                    if (timeout != 0)
                    {
                        command.CommandTimeout = timeout;
                    }

                    using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
                    {
                        if (reader.Read())
                        {
                            serverDate = DateTime.Parse(reader["InstanceDate"].ToString());
                        }
                    }
                }

                return(new ServerProperties(
                           version,
                           dbConnection.DataSource,
                           serverDate));
            }
        }
		public ITableRow ReadLastMeta(
			TemplateNodeInfo      node,
			InstanceInfo          instance,
			TemplateNodeQueryInfo templateNodeQuery
		)
		{
			Int64? queryId = this.QueryDirectory.GetQueryId(
				node,
				templateNodeQuery,
				instance,
				new DateTime(),
				true
			);

			return queryId != null
				? this.ReadLastMeta(queryId.Value)
				: null;
		}
		private static DbConnection CreateTeradataConnection(InstanceInfo instance)
		{
			if (instance.IsODBC)
			{
				return ConnectionFactory.CreateOdbcConnection(instance);
			}

			return ConnectionFactory.CreateTdConnection(instance);
		}
		private static DbConnection CreateMssqlConnection(InstanceInfo instance)
		{
			if (instance.IsODBC)
			{
				return ConnectionFactory.CreateOdbcConnection(instance);
			}

			return ConnectionFactory.CreateSqlConnection(instance);
		}
		private static ServerProperties QueryTeradata(
			InstanceInfo instance,
			int          timeout = 0
		)
		{
			using (DbConnection dbConnection = CreateTeradataConnection(instance))
			{
				dbConnection.Open();

				InstanceVersion version = new InstanceVersion(dbConnection.ServerVersion);
				DateTime  serverDate    = DateTime.MaxValue;

				using (DbCommand command = dbConnection.CreateCommand())
				{
					command.CommandText = "SELECT CURRENT_DATE AS InstanceDate";

					if (timeout != 0)
					{
						command.CommandTimeout = timeout;
					}

					using (DbDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
					{
						if (reader.Read())
						{
							serverDate = DateTime.Parse(reader["InstanceDate"].ToString());
						}
					}
				}

				return new ServerProperties(
					version,
					dbConnection.DataSource,
					serverDate);
			}
		}
		private void SelectInstance(InstanceInfo instanceInfo)
		{
			IEnumerable<InstanceInfo> instances =
				this.cmbConnection.Items.OfType<InstanceInfo>();

			InstanceInfo firstConnection = instances.FirstOrDefault(
				x => x.GetConnectionString() == instanceInfo.GetConnectionString() && x.IsODBC == instanceInfo.IsODBC);

			if (firstConnection == null)
			{
				this.cmbConnection.Items.Add(instanceInfo);
				this.cmbConnection.SelectedItem = instanceInfo;
			}
			else
			{
				this.cmbConnection.SelectedItem = firstConnection;
			}
		}
		private static void GenerateResultDefinition(
			XmlElement            rootNode,
			TemplateNodeQueryInfo templateNodeQueryInfo,
			ErrorInfo             errorInfo,
			InstanceInfo          instance,
			long                  rowCount,
			Int64                 recordSets
		)
		{
			string     errorCode   = string.Empty;
			string     errorNumber = "0";
			XmlElement node        = rootNode.OwnerDocument.CreateElement(QueryResultNodeName);

			node.SetAttribute("instance",   instance.Name);
			node.SetAttribute("name",       templateNodeQueryInfo.QueryName);
			node.SetAttribute("RecordSets", recordSets.ToString());
			node.SetAttribute("RowCount",   rowCount.ToString());

			if (errorInfo != null)
			{
				XmlElement errorNode = rootNode.OwnerDocument.CreateElement("SqlErrorMessage");

				errorNode.InnerText = errorInfo.Message;
				node.AppendChild(errorNode);
				errorCode = errorInfo.Code;
				errorNumber = errorInfo.Number;
			}

			node.SetAttribute("SqlErrorCode",   errorCode);
			node.SetAttribute("SqlErrorNumber", errorNumber);
			node.SetAttribute("hierarchy",      templateNodeQueryInfo.ResultHierarchy);

			rootNode.AppendChild(node);
		}
		private long SaveDatabaseResult(
			TemplateNodeQueryInfo   templateNodeQuery,
			InstanceInfo            instance,
			QueryDatabaseResultInfo dbResult,
			Int64?                  queryId
		)
		{
			long  totalRows = 0L;
			Int64 recordSet = 1L;

			foreach (DataTable table in dbResult.DataTables)
			{
				Debug.Assert(table != null);

				long? savedRows = this.SaveResults(
					instance,
					templateNodeQuery,
					recordSet,
					table,
					queryId
				);

				if (savedRows.HasValue)
				{
					totalRows += savedRows.Value;
				}

				recordSet++;
			}

			this.UpdateHistory(
				instance,
				templateNodeQuery,
				queryId.Value
			);

			return totalRows;
		}
		internal DataTable[] ExecuteSql(
			InstanceInfo                    instance,
			QueryItemInfo                   sql,
			string                          database = null,
			IEnumerable<QueryParameterInfo> parameters = null,
			IEnumerable<ParameterValue>     parameterValues = null,
			ProgressItem                    progress = null,
			bool                            fromGroupSelect = false
		)
		{
			Exception       gotException    = null;
			List<DataTable> tables          = new List<DataTable>();

			this._cancellationToken.ThrowIfCancellationRequested();

			try
			{
				if (sql == null)
				{
					throw new Exception("There is no sql statement to execute (QueryItemInfo == null).");
				}

				List<Tuple<int, string>> parametersQueueForODBC;

				using (IQueryConnection connection = _queryConnectionFactory.CreateQueryConnection(sql.ParentQuery.Source, instance))
				{
					using (IQueryCommand sqlCommand = connection.GetCommand(sql.Text, this._model.Settings.SqlTimeout, parameters, out parametersQueueForODBC))
					{
						using (new TryFinally(connection.Open, connection.Close))
						{
							connection.ChangeDatabase(database);

							var shouldExecute = true;

							if (sql.ExecuteIfSqlText != null)
							{
								var clone = sql.Clone();

								clone.ExecuteIfSqlText = null;
								clone.Text             = sql.ExecuteIfSqlText;

								DataTable[] tt = ExecuteSql(
									instance,
									clone,
									database,
									parameters,
									parameterValues,
									progress,
									fromGroupSelect
								);

								if (tt.Length > 0 && tt[0].Rows.Count > 0)
								{
									shouldExecute = (int)(tt[0].Rows[0][0]) == 1;
								}
							}

							if (shouldExecute)
							{
								var executionFinishedEvent = new AutoResetEvent(false);

								IQueryCommand command = null;

								Action<IAsyncResult> handleCallback = result =>
								{
									command = (IQueryCommand)result.AsyncState;

									try
									{
										using (var reader = command.EndExecuteReader(result))
										{
											while (!reader.IsClosed)
											{
												DataTable table = new DataTable();

												table.Load(reader, LoadOption.OverwriteChanges, ExecuteSqlFillErrorHandler);
												tables.Add(table);
											}
										}
									}
									catch (Exception ex)
									{
										log.Error(ex);

										gotException = ex;

										if (fromGroupSelect)
										{
											log.ErrorFormat(
												"Instance:'{0}';Authentication:'{1}';SQL:'{2}';Exception:'{3}'",
												instance.Instance,
												instance.Authentication,
												sql,
												ex
											);
										}
									}
									finally
									{
										if (command != null)
										{
											command.Cancel();
										}

										executionFinishedEvent.Set();
									}
								};

								sqlCommand.AssignParameters(parameters, parameterValues, parametersQueueForODBC);
								var callback = new AsyncCallback(handleCallback);
								var asyncResult = sqlCommand.BeginExecuteReader(callback);

								if (WaitHandle.WaitAny(new[] { asyncResult.AsyncWaitHandle, this._cancellationToken.WaitHandle }) == 1)
								{
									if (command != null)
									{
										command.Cancel();
									}

									this._cancellationToken.ThrowIfCancellationRequested();
								}

								executionFinishedEvent.WaitOne();
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				log.Error(ex);

				if (gotException == null)
				{
					gotException = ex;

					if (fromGroupSelect)
					{
						log.ErrorFormat(
							"Instance:'{0}';Authentication:'{1}';Exception:'{2}'",
							instance.Instance,
							instance.Authentication,
							ex
						);
					}
				}
			}
			finally
			{
				if (progress != null)
				{
					progress.SetProgressDone();
				}
			}

			if (gotException != null)
			{
				if (!fromGroupSelect)
				{
					gotException.Data.Add("IgnoreLog", true);
				}

				throw gotException;
			}

			return tables.ToArray();
		}
		private Int64? SaveResults(
			InstanceInfo          instance,
			TemplateNodeQueryInfo templateNodeQuery,
			Int64                 recordSet,
			DataTable             dataTable,
			Int64?                queryId
		)
		{
			Int64? lSavedRows = 0L;

			NormalizeInfo dbStructure = this.GetDbStucture(
				templateNodeQuery,
				recordSet,
				instance,
				dataTable
			);

			// Log.InfoFormat("Instance:'{0}';templateNode:'{1}';templateNodeQuery:'{2}';Table:'{3}';PrimaryKey:'{4}'",
			//    instance.Name,
			//    templateNode,
			//    templateNodeQuery,
			//    dbStructure.TableName,
			//    queryId
			// );

			if (queryId != null)
			{
				this.CurrentStorage.QueryResultsDirectory.GetId(
					queryId.Value,
					recordSet,
					dbStructure.TableName
				);

				lSavedRows = this.ReportStorage.SaveResults(
					queryId.Value,
					dbStructure,
					dataTable
				);
			}

			return lSavedRows;
		}
		public NormalizeInfo GetDbStucture(
			TemplateNodeQueryInfo templateNodeQueryInfo,
			Int64                 recordSet,
			InstanceInfo          instance,
			DataTable             dataTable = null
		)
		{
			List<QueryInfo> queries      = Model.GetQueryByTemplateNodeQueryInfo(templateNodeQueryInfo);
			QueryInfo       query        = queries.FirstOrDefault(x => x.Source == instance.Type || x.Source == QuerySource.SQLite);
			string          tableName    = this.GetTableName(templateNodeQueryInfo, recordSet);
			string          tableIndexes = string.Empty;

			if (query != null)
			{
				tableIndexes = query.QueryIndexFileds;
			}

			lock (this._dbStructures)
			{
				if (!this._dbStructures.ContainsKey(tableName))
				{
					NormalizeInfo definedRecordSet = query.GetDbStructureForRecordSet(recordSet);

					if (definedRecordSet != null)
					{
						var clone = definedRecordSet.Clone();
						clone.TableName = tableName;
						this._dbStructures.Add(tableName, clone);
					}
					else
					{
						if (dataTable == null)
						{
							NormalizeInfo result     = new NormalizeInfo();
							NormalizeFieldInfo field = new NormalizeFieldInfo();

							result.TableName = tableName;
							result.Fields    = new List<NormalizeFieldInfo>();
							field.Name       = "*";
							field.Type       = SqlDbType.NVarChar;

							result.Fields.Add(field);

							result.TableIndexFileds = tableIndexes;

							return result;
						}

						NormalizeInfo dbStructure = new NormalizeInfo
						{
							TableName        = tableName,
							IsAutoGenerated  = true,
							Fields           = new List<NormalizeFieldInfo>(),
							ChildDirectories = new List<NormalizeInfo>(),
							RecordSet        = recordSet,
							QueryName        = query.Name,
							TableIndexFileds = tableIndexes
						};

						foreach (DataColumn column in dataTable.Columns)
						{
							NormalizeFieldInfo field = new NormalizeFieldInfo();

							field.Name     = column.ColumnName;
							field.Type     = column.DataType.ToSqlDbType();
							field.IsUnique = true;

							dbStructure.Fields.Add(field);
						}

						this._dbStructures.Add(tableName, dbStructure);
					}
				}
			}

			NormalizeInfo structure = this._dbStructures[tableName];

			return structure;
		}
		internal DataTable[] ExecuteSql(
			InstanceInfo                    instance,
			QueryItemInfo                   sql,
			IEnumerable<QueryParameterInfo> parameters = null,
			IEnumerable<ParameterValue>     parameterValues = null
		)
		{
			bool shouldExecute = true;

			if (sql == null)
			{
				throw new Exception("There is no sql statement to execute (QueryItemInfo == null).");
			}

			// Log.InfoFormat("instance:'{0}';sql.Text:'{1}'",
			// 	instance,
			// 	sql.Text
			// );

			if (sql.ExecuteIfSqlText != null)
			{
				var clone = sql.Clone();

				clone.ExecuteIfSqlText = null;
				clone.Text             = sql.ExecuteIfSqlText;

				DataTable[] tt = ExecuteSql(
					instance,
					clone,
					parameters,
					parameterValues
				);

				if (tt.Length > 0 && tt[0].Rows.Count > 0)
				{
					shouldExecute = (int)(tt[0].Rows[0][0]) == 1;
				}
			}

			if (shouldExecute)
			{
				return this.CurrentStorage.ExecuteSql(
					sql.Text,
					parameters,
					parameterValues,
					instance
				);
			}

			return new DataTable[0];
		}
		private void SaveHistoryData(
			QueryInfo             query,
			InstanceInfo          instance,
			long                  queryId,
			TemplateNodeQueryInfo templateNodeQuery
		)
		{
			QueryInfo queryInfo            = new QueryInfo { Source = QuerySource.SQLite };
			Regex     regex                = new Regex(@"\[\$\{(?<QueryName>[\w]+)\}\$_\$\{(?<RecordSetNumber>[\w]+)\}\$\]");
			string    strQueryName         = String.Empty;
			Int64     intRecordSetNumber   = 0L;
			string    strReplacedTableName = String.Empty;

			if (query.FillStatementList == null)
			{
				return;
			}

			List<HistoryFillStatement> list = query.FillStatementList.GetSortedStatements();

			List<QueryParameterInfo> parameters = new List<QueryParameterInfo>
			{
				new QueryParameterInfo
				{
					Name = _QueryIdParameterName,
					Type = SqlDbType.BigInt
				}
			};

			List<ParameterValue> paramterValues = new List<ParameterValue>
			{
				new ParameterValue
				{
					Name        = _QueryIdParameterName,
					StringValue = queryId.ToString()
				}
			};

			// string newTableName = String.Format("[{0}]",
			//    this.GetTableName(templateNodeQuery, recordSet) ?? "_unknown_table_"
			// );

			// string oldTableName = "[${" + query.Name + "}$_${" + recordSet + "}$]";

			// string oldTableName = String.Format("[${{{0}}}$_${{{1}}}$]",
			//   query.Name ?? "_unknown_table_",
			//   recordSet
			//);

			// Log.DebugFormat("oldTableName:'{0}',newTableName:'{1}'",
			//    oldTableName,
			//    newTableName
			//);

			foreach (HistoryFillStatement statement in list)
			{
				QueryItemInfo queryItem = new QueryItemInfo();

				queryItem.ParentQuery = queryInfo;
				queryItem.Text        = statement.Text;

				// queryItem.Text        = statement.Text.Replace(oldTableName, newTableName);

				// Regex regex = new Regex("[\$\{([\w]+)\}\$_\$\{([\w]+)\}\$]");

				// Log.InfoFormat("regex:'{0}'",
				//    regex
				// );

				var results = regex.Matches(statement.Text);

				foreach (Match match in results)
				{
					// Log.InfoFormat("match:'{0}';match.Value:'{1}'",
					// 	match,
					// 	match.Value
					// );

					strQueryName       = match.Groups["QueryName"].Value;
					intRecordSetNumber = Int64.Parse(match.Groups["RecordSetNumber"].Value);

					// Log.InfoFormat("strQueryName:'{0}';intRecordSetNumber:'{1}'",
					//    strQueryName,
					//    intRecordSetNumber
					// );

					if (String.Equals(strQueryName, query.Name, StringComparison.OrdinalIgnoreCase))
					{
						// Log.InfoFormat("matches:strQueryName:'{0}';query.Name:'{1}'",
						//    strQueryName,
						//    query.Name
						// );

						strReplacedTableName = string.Format(
							"[{0}]",
							this.GetTableName(
								templateNodeQuery,
								intRecordSetNumber
							)
						);

						// Log.InfoFormat("strReplacedTableName:'{0}'",
						//    strReplacedTableName
						// );

						// Log.InfoFormat("queryItem.Text:'{0}'",
						//    queryItem.Text
						// );

						queryItem.Text = queryItem.Text.Replace(
							match.Value,
							strReplacedTableName
						);

						// Log.InfoFormat("queryItem.Text:'{0}'",
						//    queryItem.Text
						// );
					}
				}

				this.ExecuteSql(
					instance,
					queryItem,
					parameters,
					paramterValues
				);
			}
		}
		private void UpdateHistory(
			InstanceInfo          instance,
			TemplateNodeQueryInfo templateNodeQuery,
			long                  queryId
		)
		{
			if (this.HistoryStorage != null && this._updateHistory)
			{
				List<QueryInfo> queries = Model.GetQueryByTemplateNodeQueryInfo(templateNodeQuery);
				QueryInfo       query   = queries.FirstOrDefault(
					x =>
						x.Source == instance.Type
						||
						x.Source == QuerySource.SQLite
				);

				try
				{
					this.SaveHistoryData(
						query,
						instance,
						queryId,
						templateNodeQuery
					);
				}
				catch (Exception ex)
				{
					Log.ErrorFormat("Update History exception:{0};query:{1}",
						ex,
						query
					);

					if (!ex.Data.Contains("IgnoreLog"))
					{
						Log.ErrorFormat("Update History exception:{0};query:{1}",
							ex,
							query
						);
					}
				}
			}
		}
		private static ServerProperties GetBlackProperties(InstanceInfo instance)
		{
			return new ServerProperties(new InstanceVersion(), instance.Name, DateTime.Now);
		}
		public SQLiteParameter[] GetParameters(
			IEnumerable<QueryParameterInfo> parameters,
			IEnumerable<ParameterValue>     parameterValues,
			InstanceInfo                    instance
		)
		{
			var result = new List<SQLiteParameter>();

			if (parameters != null)
			{
				foreach (var parameter in parameters)
				{
					result.Add(
						new SQLiteParameter
						{
							ParameterName = parameter.Name,
							IsNullable    = true,
							DbType        = parameter.Type.ToDbType(),
							Value         = parameter.GetDefaultValue()
						}
					);
				}
			}

			if (parameterValues != null)
			{
				foreach (var value in parameterValues)
				{
					var parameter = (
							from
								SQLiteParameter p
							in
								result
							where
								p.ParameterName == value.Name
							select
								p
						).FirstOrDefault();

					if (parameter != null)
					{
						parameter.Value = value.GetValue(parameter.DbType.ToSqlDbType());
					}
				}
			}

			result.AddRange(this.GetDefaultParameters(instance));

			return result.ToArray();
		}
		private InstanceInfo CreateFromRow(ServerInstanceRow instanceRow)
		{
			long     loginId  = instanceRow.LoginId;
			LoginRow loginRow = this._loginManager.GetLogin(loginId);

			AuthenticationInfo authInfo = new AuthenticationInfo
			{
				Username  = loginRow.Login,
				Password  = loginRow.Password,
				IsWindows = loginRow.IsWinAuth
			};

			string conName = instanceRow.ConnectionName;

			InstanceInfo instanceInfo = new InstanceInfo(instanceRow.IsDynamicConnection)
			{
				Authentication = authInfo,
				IsODBC         = instanceRow.IsOdbc,
				DbType         = instanceRow.DbType,
				IsEnabled      = true,
				Name           = conName,
				Instance       = conName
			};

			instanceInfo.SetServerProperties(
				new ServerProperties(
					new InstanceVersion(instanceRow.ServerInstanceVersion),
					instanceRow.ServerInstanceName,
					DateTime.Now
				)
			);

			return instanceInfo;
		}
		internal DataTable[] ExecuteSql(
			InstanceInfo                    instance,
			QueryInfo                       query,
			string                          database = null,
			IEnumerable<QueryParameterInfo> parameters = null,
			IEnumerable<ParameterValue>     parameterValues = null,
			ProgressItem                    progress = null,
			bool                            fromGroupSelect = false
		)
		{
			InstanceVersion ver           = instance.ServerProperties.Version;
			QueryItemInfo exactSqlVersion = query.Items.GetQueryItemForVersion(ver);

			if (exactSqlVersion == null)
			{
				throw new InvalidOperationException("No <sql-select-text> found for version " + ver + " in <sql-select name=" + query.Name);
			}

			return ExecuteSql(
				instance,
				exactSqlVersion,
				database,
				parameters,
				parameterValues,
				progress,
				fromGroupSelect
			);
		}
		public DataTable[] ExecuteSql(
			string                          sql,
			IEnumerable<QueryParameterInfo> parameters,
			IEnumerable<ParameterValue>     parameterValues,
			InstanceInfo                    instance
		)
		{
			var result = new List<DataTable>();

			var selectCommand = new SqlSelectCommand(
				this.Connection,
				sql,
				reader =>
				{
					var table = new DataTable();

					table.Load(reader, LoadOption.OverwriteChanges);

					result.Add(table);
				},
				this.GetParameters(parameters, parameterValues, instance)
			);

			selectCommand.Execute(100);

			return result.ToArray();
		}
		private QueryInstanceResultInfo GetInstanceResult(
			MultyQueryResultInfo  result,
			InstanceInfo          instance,
			Int64                 queryId,
			TemplateNodeQueryInfo templateNodeQueryInfo,
			List<QueryInfo>       queries
		)
		{
			QueryInstanceResultInfo instanceResult = null;
			Int64                   recordSetCount = 0L;
			ITableRow               meta           = Storage.ReadLastMeta(queryId);

			if (meta != null)
			{
				DateTime timestamp = (DateTime)meta.Values[TableDefinition.DateCreated];

				result.RefreshTimestamp(timestamp);

				if (!string.IsNullOrEmpty(meta.Values[MetaResultTable.ErrorMessageFieldName].ToString()))
				{
					instanceResult = new QueryInstanceResultInfo(
						new ErrorInfo(
							meta.Values[MetaResultTable.ErrorIdFieldName].ToString(),
							meta.Values[MetaResultTable.ErrorCodeFieldName].ToString(),
							meta.Values[MetaResultTable.ErrorMessageFieldName].ToString(),
							(DateTime)meta.Values[TableDefinition.DateCreated]
						),
						instance
					);
				}
				else
				{
					instanceResult = new QueryInstanceResultInfo(instance);
				}

				recordSetCount = (Int64) meta.Values[MetaResultTable.RecordSetCountFieldName];

				DataTable[] dataTables = GetDataTables(
					recordSetCount,
					queryId,
					instance,
					templateNodeQueryInfo
				);

				QueryInfo query = queries.FirstOrDefault(x => x.Source == instance.Type || x.Source == QuerySource.SQLite);

				if (query != null)
				{
					QueryDatabaseResultInfo databaseResult = new QueryDatabaseResultInfo(
						dataTables,
						query.Items.GetQueryItemForVersion(instance.GetServerPropertiesSafe().Version),
						base.GroupDefinition.Name,
						base.GroupDefinition.Id
					);

					instanceResult.AddDatabaseResult(databaseResult);
				}
			}

			return instanceResult;
		}
		private IEnumerable<SQLiteParameter> GetDefaultParameters(InstanceInfo instance)
		{
			List<SQLiteParameter> result = new List<SQLiteParameter>();

			ConnectionGroupInfo connectionGroup = instance.ConnectionGroup;
			connectionGroup.ReadGroupIdFrom(this.ConnectionGroupDirectory);

			long? instanceId = this.ServerInstanceDirectory.GetId(connectionGroup, instance);
			long? loginId    = this.LoginDirectory.GetId(instance);
			long? templateId = this.TemplateDirectory.GetId(connectionGroup);

			result.Add(
				SQLiteHelper.GetParameter(ConnectionGroupDirectory.TableName.AsFk(), connectionGroup.Identity)
			);
			result.Add(
				SQLiteHelper.GetParameter(ServerInstanceDirectory.TableName.AsFk(), instanceId)
			);
			result.Add(
				SQLiteHelper.GetParameter(LoginDirectory.TableName.AsFk(), loginId)
			);
			result.Add(
				SQLiteHelper.GetParameter(TemplateDirectory.TableName.AsFk(), templateId)
			);

			return result;
		}
		private DataTable[] GetDataTables(
			Int64                 recordSetCount,
			Int64                 queryId,
			InstanceInfo          instance,
			TemplateNodeQueryInfo templateNodeQueryInfo
		)
		{
			var dataTables = new DataTable[recordSetCount];

			for (Int64 recordSet = 1L; recordSet <= recordSetCount; recordSet++)
			{
				NormalizeInfo db = StorageManager.GetDbStucture(templateNodeQueryInfo, recordSet, instance);

				if (db != null)
				{
					if (this._histTable.ContainsKey(templateNodeQueryInfo))
					{
						dataTables[recordSet - 1L] = this._histTable[templateNodeQueryInfo];
					}
					else
					{
						dataTables[recordSet - 1L] = base.ReportStorage.ReadResult(db, queryId);
					}
				}
			}

			return dataTables;
		}
Beispiel #31
0
 private static ServerProperties GetBlackProperties(InstanceInfo instance)
 {
     return(new ServerProperties(new InstanceVersion(), instance.Name, DateTime.Now));
 }
		public override long? GetQueryId(
			TemplateNodeInfo      node,
			TemplateNodeQueryInfo templateNodeQuery,
			InstanceInfo          instance,
			DateTime              dateCreated,
			bool                  onlyFind
		)
		{
			Int64? queryId = 0L;

			Debug.Assert(node.IsInstance);

			if (node.TemplateNodeId == null)
			{
				throw new InvalidOperationException();
			}

			Int64? templateNodeQueryId = Storage.TemplateNodeQueryDirectory
				.GetId(node.ConnectionGroup, node.Template, templateNodeQuery);

			Int64? serverId = Storage.ServerInstanceDirectory
				.GetId(node.ConnectionGroup, instance);

			if (onlyFind)
			{
				Tuple<long, long, long> key = new Tuple<Int64, Int64, Int64>(
					(long) node.TemplateNodeId.Value,
					(long) templateNodeQueryId,
					(long) serverId
				);

				return this.Cache.GetOrAdd(
					key, () =>
					{
						ITableRow row = this.NewRow();

						row.Values.Add(NodeInstanceIdFn,      node.TemplateNodeId.Value);
						row.Values.Add(TemplateNodeQueryIdFn, templateNodeQueryId);
						row.Values.Add(ServerInstanceIdFn,    serverId);

						queryId = this.GetRow(row);

						Log.InfoFormat("ServerId:'{0}';NodeInstanceId:'{1}';TemplateNodeQueryId:'{2}';PrimaryKey:'{3}'",
							serverId,
							node.TemplateNodeId.Value,
							templateNodeQueryId,
							queryId
						);

						return queryId;
					}
				);
			}

			List<Field> customFields = new List<Field>
			{
				this.CreateField(DefaultDatabaseNameFn,       node.GetDefaultDatabase()),
				this.CreateField(TableDefinition.DateCreated, dateCreated),
				this.CreateField(NodeInstanceIdFn,            node.TemplateNodeId.GetValueOrDefault()),
				this.CreateField(TemplateNodeQueryIdFn,       templateNodeQueryId),
				this.CreateField(ServerInstanceIdFn,          serverId)
			};

			queryId = this.GetRecordIdByFields(customFields.ToArray());

			Log.InfoFormat("ServerId:'{0}';NodeInstanceId:'{1}';TemplateNodeQueryId:'{2}';id:'{3}'",
				serverId,
				node.TemplateNodeId.GetValueOrDefault(),
				templateNodeQueryId,
				queryId
			);

			return queryId;
		}