コード例 #1
0
        /// <summary> Generates the Sql </summary>
        /// <param name="name">        The name. </param>
        /// <param name="primaryKeys"> The item. </param>
        /// <param name="properties">  The properties. </param>
        /// <returns> The sql. </returns>
        public string GenerateSql(string name, IList<Property> primaryKeys, IList<Property> properties)
        {
            SqlGenerator generator = new SqlGenerator();
            string sql = generator.Insert(name, properties);

            return sql;
        }
コード例 #2
0
        /// <summary>
        ///     Write out the TOP part of sql select statement
        ///     It basically writes TOP (X) [WITH TIES].
        ///     The brackets around X are ommited for Sql8.
        /// </summary>
        /// <param name="writer"> </param>
        /// <param name="sqlGenerator"> </param>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            writer.Write("TOP ");

            if (sqlGenerator.SqlVersion
                != SqlVersion.Sql8)
            {
                writer.Write("(");
            }

            TopCount.WriteSql(writer, sqlGenerator);

            if (sqlGenerator.SqlVersion
                != SqlVersion.Sql8)
            {
                writer.Write(")");
            }

            writer.Write(" ");

            if (WithTies)
            {
                writer.Write("WITH TIES ");
            }
        }
コード例 #3
0
        /// <summary>
        ///     Write this symbol out as a string for sql.  This is just
        ///     the new name of the symbol (which could be the same as the old name).
        ///     We rename columns here if necessary.
        /// </summary>
        /// <param name="writer"> </param>
        /// <param name="sqlGenerator"> </param>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            if (NeedsRenaming)
            {
                int i;

                if (sqlGenerator.AllColumnNames.TryGetValue(NewName, out i))
                {
                    string newNameCandidate;
                    do
                    {
                        ++i;
                        newNameCandidate = NewName + i.ToString(CultureInfo.InvariantCulture);
                    }
                    while (sqlGenerator.AllColumnNames.ContainsKey(newNameCandidate));

                    sqlGenerator.AllColumnNames[NewName] = i;

                    NewName = newNameCandidate;
                }

                // Add this column name to list of known names so that there are no subsequent
                // collisions
                sqlGenerator.AllColumnNames[NewName] = 0;

                // Prevent it from being renamed repeatedly.
                NeedsRenaming = false;
            }
            writer.Write(SqlGenerator.QuoteIdentifier(NewName));
        }
コード例 #4
0
 /// <summary>
 ///     We delegate the writing of the fragment to the appropriate type.
 /// </summary>
 /// <param name="writer"> </param>
 /// <param name="sqlGenerator"> </param>
 public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
 {
     if (null != _sqlFragments)
     {
         foreach (var o in _sqlFragments)
         {
             var str = (o as String);
             if (null != str)
             {
                 writer.Write(str);
             }
             else
             {
                 var sqlFragment = (o as ISqlFragment);
                 if (null != sqlFragment)
                 {
                     sqlFragment.WriteSql(writer, sqlGenerator);
                 }
                 else
                 {
                     throw new InvalidOperationException();
                 }
             }
         }
     }
 }
コード例 #5
0
 public ExtractColumn(IDatabaseAdapter src, IDatabaseAdapter dest, ITableConversionRules rules)
 {
     _src = src;
     _dest = dest;
     _rules = rules;
     _destGenerator = new SqlGenerator(_dest);
     _extractedColumns = new List<ExtractedColumn>();
 }
コード例 #6
0
        /// <summary>
        /// Write out the FIRST part of sql select statement 
        /// It basically writes FIRST (X).
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="sqlGenerator"></param>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            writer.Write("FIRST (");
            this.FirstCount.WriteSql(writer, sqlGenerator);
            writer.Write(")");

            writer.Write(" ");
        }
コード例 #7
0
        /// <summary>
        /// Write out the SKIP part of sql select statement 
        /// It basically writes SKIP (X).
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="sqlGenerator"></param>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            writer.Write("SKIP (");
            this.SkipCount.WriteSql(writer, sqlGenerator);
            writer.Write(")");

            writer.Write(" ");
        }
コード例 #8
0
        // <summary>
        // Write out the OFFSET part of sql select statement
        // It basically writes OFFSET X ROWS.
        // </summary>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            writer.Write("OFFSET ");

            SkipCount.WriteSql(writer, sqlGenerator);

            writer.Write(" ROWS ");
        }
コード例 #9
0
 public ActionResult About()
 {
             
              
              var filter = new SqlGenerator(SqlGenerator.SqlTypes.Select, "Transact");
              filter.SelectStatementLimit = 1000;
              var baseModel = ModelBase.LoadModel<TransactModel>(filter);
              return View(baseModel.ToList());
             // return View();
 }
コード例 #10
0
 /// <summary>
 ///     Writes that fragment that represents the optional column
 ///     if the usage manager says it is used.
 /// </summary>
 /// <param name="writer"> </param>
 /// <param name="sqlGenerator"> </param>
 public bool WriteSqlIfUsed(SqlWriter writer, SqlGenerator sqlGenerator, string separator)
 {
     if (m_usageManager.IsUsed(m_symbol))
     {
         writer.Write(separator);
         m_builder.WriteSql(writer, sqlGenerator);
         return true;
     }
     return false;
 }
コード例 #11
0
        public ModificationCommandBatchFactory(
            [NotNull] SqlGenerator sqlGenerator,
            [NotNull] DbContextConfiguration contextConfiguration)
        {
            Check.NotNull(sqlGenerator, "sqlGenerator");
            Check.NotNull(contextConfiguration, "contextConfiguration");

            _sqlGenerator = sqlGenerator;
            _contextConfiguration = contextConfiguration;
        }
コード例 #12
0
        public static void CreateTableIfNotExists(this IDao dao, string tableName, Type entityType, params string[] pks)
        {
            //如果表已经存在则跳过
            bool existTable = ExistsTable(dao, tableName);
            if (existTable) {
                return;
            }

            var sqlGen = new SqlGenerator();
            var sql = sqlGen.CreateSqlScript(tableName, entityType, pks);
            dao.Execute(sql);
        }
コード例 #13
0
ファイル: SqlVerb.cs プロジェクト: devshorts/Atom
        private IEnumerable<GeneratorResult> FromTargetConfigs(SqlTargetConfig sqlConfig)
        {
            var args = new GeneratorArguments<SqlTargetConfig>(sqlConfig, AtomsFolder, AtomCreator.LoadDefaults(AtomsFolder));

            var sqlResult = new SqlGenerator().Generate(args);

            sqlResult.OutputPath = sqlConfig.OutputPath;

            if (Directory.Exists(sqlResult.OutputPath))
            {
                foreach (var file in Directory.EnumerateFiles(sqlResult.OutputPath, "*.generated.sql", SearchOption.AllDirectories))
                {
                    sqlResult.Deletions.Add(file);
                }
            }

            string redGateFile = Path.Combine(sqlConfig.OutputPath, "RedGateDatabaseInfo.xml");

            Log.Information("Looking for redgate database info xml at {RedGateDatabaseInfoXml}", redGateFile);

            if (sqlResult.DataFiles.Any() &&
                File.Exists(redGateFile))
            {
                Log.Information("Found redgate file, updating...");

                var regate = XDocument.Load(uri: redGateFile);
                var dataFiles = regate.Root.Elements("DataFileSet").First();
                var allDataFiles = dataFiles.Elements("DataFile")
                                            .Select(n => n.Value).Union(sqlResult.DataFiles, StringComparer.OrdinalIgnoreCase).ToList();

                dataFiles.Elements("Count")
                         .First()
                         .Value = allDataFiles.Count().ToString();

                Log.Information("DataFiles Count: {DataFileCount}", allDataFiles.Count());

                dataFiles.Elements("DataFile").Remove();

                dataFiles.Add(allDataFiles.Select(s => new XElement("DataFile", s)));

                var genResult = new GeneratorResult()
                {
                    OutputPath = _config.OutputPath
                };

                genResult.AddOutput("RedGateDatabaseInfo.xml", regate.ToString());

                yield return genResult;
            }

            yield return sqlResult;
        }
コード例 #14
0
        public DmlFunctionSqlGenerator(DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(providerManifest);

            var sqlManifest = providerManifest as SqlProviderManifest;

            if (sqlManifest == null)
            {
                throw new ArgumentException(Strings.Mapping_Provider_WrongManifestType(typeof(SqlProviderManifest)));
            }

            _sqlGenerator = new SqlGenerator(sqlManifest.SqlVersion);
        }
コード例 #15
0
 public SqlFragment Generate(DbFunctionExpression e, SqlGenerator caller)
 {
     callingGenerator = caller;
     if (bitwiseFunctions.ContainsKey(e.Function.Name))
         return BitwiseFunction(e);
     else if (dateFunctions.ContainsKey(e.Function.Name))
         return GenericFunction(dateFunctions, e);
     else if (stringFunctions.ContainsKey(e.Function.Name))
         return GenericFunction(stringFunctions, e);
     else if (mathFunctions.ContainsKey(e.Function.Name))
         return GenericFunction(mathFunctions, e);
     return null;
 }
コード例 #16
0
        /// <summary>
        /// Write out the TOP part of sql select statement 
        /// It basically writes TOP (X) [WITH TIES].
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="sqlGenerator"></param>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            writer.Write("TOP (");
            this.TopCount.WriteSql(writer, sqlGenerator);
            writer.Write(")");

            writer.Write(" ");

            if (this.WithTies)
            {
                writer.Write("WITH TIES ");
            }
        }
コード例 #17
0
        /// <summary>
        /// Write out the TOP part of sql select statement 
        /// It basically writes TOP (X) [WITH TIES].
        /// The brackets around X are ommited for Sql8.
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="sqlGenerator"></param>
        public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
        {
            writer.Write("TOP ");

            writer.Write("(");

            TopCount.WriteSql(writer, sqlGenerator);

            writer.Write(")");

            writer.Write(" ");

            Debug.Assert(!WithTies, "WITH TIES cannot be true for Top clause");
        }
コード例 #18
0
ファイル: Tests.cs プロジェクト: devshorts/Atom
        public void TestRepos()
        {
            var folder = @"..\UnitTests\TestAtoms\CareRelated";
            var args = new GeneratorArguments<CSharpTargetConfig>(new CSharpTargetConfig(), folder, AtomCreator.LoadDefaults(folder));

            var sqlArgs = new GeneratorArguments<SqlTargetConfig>(new SqlTargetConfig(), args.AtomsFolder, AtomCreator.LoadDefaults(folder));
            var sqlGenerator = new SqlGenerator().Generate(sqlArgs);

            var result = new RepositoryGenerator(sqlGenerator).Generate(args);

            foreach (var item in result)
            {
                Console.WriteLine(item.Output);
            }
        }
コード例 #19
0
ファイル: TopClause.cs プロジェクト: yingfangdu/SQLiteNet
    /// <summary>
    /// Write out the TOP part of sql select statement 
    /// It basically writes LIMIT (X).
    /// </summary>
    /// <param name="writer"></param>
    /// <param name="sqlGenerator"></param>
    public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
    {
      writer.Write(" LIMIT ");
      this.TopCount.WriteSql(writer, sqlGenerator);

      if (this.WithTies)
        throw new NotSupportedException("WITH TIES");

      //writer.Write(" ");

      //if (this.WithTies)
      //{
      //    writer.Write("WITH TIES ");
      //}
    }
コード例 #20
0
		public BasicExecutor(IStatement statement, IQueryable persister)
			: base(statement, log)
		{
			this.persister = persister;
			try
			{
				var gen = new SqlGenerator(Factory, new CommonTreeNodeStream(statement));
				gen.statement();
				sql = gen.GetSQL();
				gen.ParseErrorHandler.ThrowQueryException();
				Parameters = gen.GetCollectedParameters();
			}
			catch (RecognitionException e)
			{
				throw QuerySyntaxException.Convert(e);
			}
		}
コード例 #21
0
        public static void VisitDbIsNullExpression_variable_size_binary_parameter_without_max_length_is_cast_to_image()
        {
            var primitiveType = PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Binary);
            var typeUsage = TypeUsage.CreateBinaryTypeUsage(primitiveType, isFixedLength: false);
            var isNullExpression = typeUsage.Parameter("parameterName").IsNull();

            var sqlGenerator = new SqlGenerator();
            var sqlFragment = sqlGenerator.Visit(isNullExpression);

            var builder = new StringBuilder();
            using (var writer = new SqlWriter(builder))
            {
                sqlFragment.WriteSql(writer, sqlGenerator);
            }

            Assert.Equal("cast(@parameterName as image) IS NULL", builder.ToString());
        }
コード例 #22
0
        public static void VisitDbIsNullExpression_non_parameter_reference_expression_is_not_cast()
        {
            var primitiveType = PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String);
            var typeUsage = TypeUsage.CreateStringTypeUsage(primitiveType, isUnicode: true, isFixedLength: false);
            var isNullExpression = typeUsage.Constant("constant").IsNull();

            var sqlGenerator = new SqlGenerator();
            var sqlFragment = sqlGenerator.Visit(isNullExpression);

            var builder = new StringBuilder();
            using (var writer = new SqlWriter(builder))
            {
                sqlFragment.WriteSql(writer, sqlGenerator);
            }

            Assert.Equal("N'constant' IS NULL", builder.ToString());
        }
コード例 #23
0
        public static void VisitDbIsNullExpression_variable_size_string_parameter_with_max_length_is_not_cast()
        {
            var primitiveType = PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String);
            var typeUsage = TypeUsage.CreateStringTypeUsage(primitiveType, isUnicode: true, isFixedLength: false, maxLength: 100);
            var isNullExpression = typeUsage.Parameter("parameterName").IsNull();

            var sqlGenerator = new SqlGenerator();
            var sqlFragment = sqlGenerator.Visit(isNullExpression);

            var builder = new StringBuilder();
            using (var writer = new SqlWriter(builder))
            {
                sqlFragment.WriteSql(writer, sqlGenerator);
            }

            Assert.Equal("@parameterName IS NULL", builder.ToString());
        }
コード例 #24
0
		protected SqlString GenerateIdInsertSelect(IQueryable persister, string tableAlias, IASTNode whereClause)
		{
			var select = new SqlSelectBuilder(Factory);
			SelectFragment selectFragment = new SelectFragment(Factory.Dialect)
				.AddColumns(tableAlias, persister.IdentifierColumnNames, persister.IdentifierColumnNames);
			select.SetSelectClause(selectFragment.ToFragmentString().Substring(2));

			string rootTableName = persister.TableName;
			SqlString fromJoinFragment = persister.FromJoinFragment(tableAlias, true, false);
			select.SetFromClause(rootTableName + " " + tableAlias + fromJoinFragment);
			
			var whereJoinFragment = GetWhereJoinFragment(persister, tableAlias);

			SqlString userWhereClause = SqlString.Empty;
			if (whereClause.ChildCount != 0)
			{
				// If a where clause was specified in the update/delete query, use it to limit the
				// returned ids here...
				try
				{
					var nodes = new CommonTreeNodeStream(whereClause);
					var gen = new SqlGenerator(Factory, nodes);
					gen.whereClause();
					userWhereClause = gen.GetSQL().Substring(7);
				}
				catch (RecognitionException e)
				{
					throw new HibernateException("Unable to generate id select for DML operation", e);
				}
				if (whereJoinFragment.Length > 0)
				{
					whereJoinFragment.Append(" and ");
				}
			}

			select.SetWhereClause(whereJoinFragment + userWhereClause);

			var insert = new InsertSelect();
			if (Factory.Settings.IsCommentsEnabled)
			{
				insert.SetComment("insert-select for " + persister.EntityName + " ids");
			}
			insert.SetTableName(persister.TemporaryIdTableName);
			insert.SetSelect(select);
			return insert.ToSqlString();
		}
コード例 #25
0
ファイル: CSharpVerb.cs プロジェクト: devshorts/Atom
        private IEnumerable<GeneratorResult> FromTargetConfigs(CSharpTargetConfig targetConfig)
        {
            var args = new GeneratorArguments<CSharpTargetConfig>(targetConfig, AtomsFolder, AtomCreator.LoadDefaults(AtomsFolder));

            if(targetConfig.Repository != null){
                var sqlArgs = new GeneratorArguments<SqlTargetConfig>(new SqlTargetConfig(), args.AtomsFolder, AtomCreator.LoadDefaults(AtomsFolder));
                var sqlGenerator = new SqlGenerator().Generate(sqlArgs);

                var repoResult = new RepositoryGenerator(sqlGenerator).Generate(args);

                repoResult.OutputPath = targetConfig.Repository.OutputPath;

                yield return repoResult;
            }

            var codeResult = new CodeGenerator().Generate(args);

            codeResult.OutputPath = targetConfig.Entities.OutputPath;

            yield return codeResult;
        }
コード例 #26
0
ファイル: ADOCLS.cs プロジェクト: emerynt/Iris10ReportTesting
        public static DataSet FetchDataSet(SqlGenerator gen, string connectionName = "CountyDatabase")
        {
            DataSet tempFetchDataSet = null;
            //Changed the function to use the command object so that the connection timeout can be set for this command.
            SqlDataAdapter objDA = null;
            DataSet objDS = new DataSet();
            SqlCommand objCommand = new SqlCommand();
            SqlConnection objCon = new SqlConnection(ConnectionStringLookup(connectionName));

            try
            {
                objCommand.CommandText = gen.SqlString;

                foreach(SqlParameter param in gen.SqlVariables)
                {
                    objCommand.Parameters.Add(param);
                }

                objCommand.Connection = objCon;
                objCommand.CommandTimeout = MintCommandTimeout;
                objCommand.CommandType = CommandType.Text;

                objDA = new SqlDataAdapter(objCommand);
                objDA.Fill(objDS);

                tempFetchDataSet = objDS;

            }
            catch (Exception )
            {
                
                ////ProcessError(ex, strSQL);
            }
            finally
            {
                objCon.Close();
            }
            return tempFetchDataSet;
        }
コード例 #27
0
              // GET: Transact
              public ActionResult Transact()
              {
                     //var filter = new SqlGenerator(SqlGenerator.SqlTypes.Select, "Transact");
                     // filter.SelectStatementLimit = 200;
                     //filter.AddWhereParameter(SqlWhereAndorOptions.SqlWhereAndor.OR, "TotalResourceCost", 51.00, 100.00, SqlWhereComparison.SqlComparer.Between);
                     //filter.AddWhereParameter(SqlWhereAndorOptions.SqlWhereAndor.And, "Task_Date", "05/13/2015", "10/05/2015", SqlWhereComparison.SqlComparer.Between);
                     //filter.AddWhereParameter(SqlWhereAndorOptions.SqlWhereAndor.And, "Task_Date", "01/20/2014", "02/01/2014", SqlWhereComparison.SqlComparer.Between);
                     // var baseModel = ModelBase.LoadModel<TransactModel>();

                     var filter = new SqlGenerator(SqlGenerator.SqlTypes.Select, "Transact");
                     filter.SelectStatementLimit = 40;
                     var baseModel = ModelBase.LoadModel<TransactModel>(filter);
                     return View(baseModel.ToList());

                     //var mysql = GetSqlString();

                     //return View(mysql);



                     ////return View(baseModel.ToList<TransactModel>());
                     //return View();

              }
コード例 #28
0
 public override void Visit(DbScanExpression expression)
 {
     _commandText.Append(SqlGenerator.GetTargetSql(expression.Target));
 }
コード例 #29
0
ファイル: DiffYears_Handler.cs プロジェクト: zyj0021/Chloe
 public void Process(DbMethodCallExpression exp, SqlGenerator generator)
 {
     SqlGenerator.DbFunction_DATEDIFF(generator, "YEAR", exp.Arguments[0], exp.Arguments[1]);
 }
コード例 #30
0
 /// <summary>
 ///     Constructor
 /// </summary>
 public DapperRepository(SqlGeneratorConfig config)
 {
     SqlGenerator = new SqlGenerator <TEntity>(config);
 }
コード例 #31
0
ファイル: Count_Handler.cs プロジェクト: zr10728/Chloe
 public void Process(DbMethodCallExpression exp, SqlGeneratorBase generator)
 {
     SqlGenerator.Aggregate_Count(generator);
 }
コード例 #32
0
 public DapperRepository(IDbConnection connection)
 {
     Connection   = connection;
     SqlGenerator = new SqlGenerator <TEntity>();
 }
コード例 #33
0
        public override void CreateTable(ITable table)
        {
            var sql = SqlGenerator.GenerateCreateTableStatement(_generator, table);

            ExecuteNonQuery(sql);
        }
コード例 #34
0
ファイル: QueryFactory.cs プロジェクト: SmartCloud2025/Rafy
 internal void Generate(SqlGenerator generator, IQuery query)
 {
     generator.Generate(query as TableQuery);
 }
コード例 #35
0
        public void Process(DbMethodCallExpression exp, SqlGenerator generator)
        {
            DbSubtractExpression dbSubtract = new DbSubtractExpression(exp.Type, exp.Object, exp.Arguments[0]);

            dbSubtract.Accept(generator);
        }
コード例 #36
0
 public void Process(DbMethodCallExpression exp, SqlGenerator generator)
 {
     throw UtilExceptions.NotSupportedMethod(exp.Method);;
 }
コード例 #37
0
 public ModificationCommandBatchFake(SqlGenerator sqlGenerator = null)
     : base(sqlGenerator ?? new FakeSqlGenerator())
 {
     ShouldAddCommand  = true;
     ShouldValidateSql = true;
 }
コード例 #38
0
 public override ISqlFragment HandleFunction(SqlGenerator sqlGenerator, DbFunctionExpression e)
 {
     throw new NotSupportedException("Function " + e.Function.Name + " is not supported");
 }
コード例 #39
0
        /// <summary>
        /// Generates the SQL and C# code for the specified database.
        /// </summary>
        /// <param name="outputDirectory">The directory where the C# and SQL code should be created.</param>
        /// <param name="connectionString">The connection string to be used to connect the to the database.</param>
        /// <param name="grantLoginName">The SQL Server login name that should be granted execute rights on the generated stored procedures.</param>
        /// <param name="storedProcedurePrefix">The prefix that should be used when creating stored procedures.</param>
        /// <param name="createMultipleFiles">A flag indicating if the generated stored procedures should be created in one file or separate files.</param>
        /// <param name="projectName">The name of the project file to be generated.</param>
        /// <param name="targetNamespace">The namespace that the generated C# classes should contained in.</param>
        /// <param name="daoSuffix">The suffix to be applied to all generated DAO classes.</param>
        /// <param name="dtoSuffix">The suffix to be applied to all generated DTO classes.</param>
        public static void Generate(string outputDirectory, string connectionString, string grantLoginName, string storedProcedurePrefix, bool createMultipleFiles, string projectName, string targetNamespace, string daoSuffix, string dtoSuffix)
        {
            List <Table> tableList = new List <Table>();
            string       databaseName;
            string       sqlPath;
            string       csPath;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                databaseName = Utility.FormatPascal(connection.Database);
                sqlPath      = Path.Combine(outputDirectory, "SQL");
                csPath       = Path.Combine(outputDirectory, "CS");

                connection.Open();

                // Get a list of the entities in the database
                DataTable      dataTable   = new DataTable();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(Utility.GetTableQuery(connection.Database), connection);
                dataAdapter.Fill(dataTable);

                // Process each table
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    Table table = new Table();
                    table.Name = (string)dataRow["TABLE_NAME"];
                    QueryTable(connection, table);
                    tableList.Add(table);
                }
            }

            DatabaseCounted(null, new CountEventArgs(tableList.Count));

            // Generate the necessary SQL and C# code for each table
            int count = 0;

            if (tableList.Count > 0)
            {
                // Create the necessary directories
                Utility.CreateSubDirectory(sqlPath, true);
                Utility.CreateSubDirectory(csPath, true);
                Utility.CreateSubDirectory(Path.Combine(csPath, "Repositories"), true);
                Utility.CreateSubDirectory(Path.Combine(csPath, "FormClasses"), true);
                Utility.CreateSubDirectory(Path.Combine(sqlPath, "SaveSPs"), true);
                Utility.CreateSubDirectory(Path.Combine(sqlPath, "SaveSPScienterModel"), true);
                Utility.CreateSubDirectory(Path.Combine(csPath, "Dapper"), true);
                Utility.CreateSubDirectory(Path.Combine(csPath, "WebAPI"), true);
                Utility.CreateSubDirectory(Path.Combine(csPath, "FrontEndAngular"), true);
                Utility.CreateSubDirectory(Path.Combine(csPath, "FrontEndAngularHTML"), true);

                // Create the necessary "use [database]" statement
                SqlGenerator.CreateUseDatabaseStatement(databaseName, sqlPath, createMultipleFiles);

                // Create the necessary database logins
                SqlGenerator.CreateUserQueries(databaseName, grantLoginName, sqlPath, createMultipleFiles);
                Table table2 = new Table();
                // Create the CRUD stored procedures and data access code for each table
                foreach (Table table in tableList)
                {
                    SqlGenerator.CreateSaveStoredProcedure(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateInsertStoredProcedure(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateUpdateStoredProcedure(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateDeleteStoredProcedure(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateDeleteAllByStoredProcedures(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateSelectStoredProcedure(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateSelectAllStoredProcedure(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateSelectAllByStoredProcedures(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
                    SqlGenerator.CreateSaveStoredProcedureForSceinter(databaseName, table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);


                    CsGenerator.CreateDataTransferClass(table, targetNamespace, dtoSuffix, csPath);
                    CsGenerator.CreateDataAccessClass(databaseName, table, targetNamespace, storedProcedurePrefix, daoSuffix, dtoSuffix, csPath);
                    CsGenerator.CreateFORMClasses(databaseName, table, targetNamespace, storedProcedurePrefix, daoSuffix, dtoSuffix, csPath);
                    CsGenerator.DapperClasses(databaseName, table, targetNamespace, storedProcedurePrefix, daoSuffix, dtoSuffix, csPath);
                    CsGenerator.WebApimethods(databaseName, table, targetNamespace, storedProcedurePrefix, daoSuffix, dtoSuffix, csPath);
                    CsGenerator.FrontEndAngular(databaseName, table, targetNamespace, storedProcedurePrefix, daoSuffix, dtoSuffix, csPath);
                    CsGenerator.FrontEndAngularHTML(databaseName, table, targetNamespace, storedProcedurePrefix, daoSuffix, dtoSuffix, csPath);

                    table2 = table;
                    count++;
                    TableCounted(null, new CountEventArgs(count));
                }

                CsGenerator.CreateSharpCore(csPath);
                CsGenerator.CreateAssemblyInfo(csPath, databaseName, databaseName);
                CsGenerator.CreateProjectFile(csPath, projectName, tableList, daoSuffix, dtoSuffix);
                //CsGenerator.CreateFORMClasses(csPath, projectName, tableList, daoSuffix, dtoSuffix);
            }
        }
コード例 #40
0
 private static ISqlFragment WriteInstanceFunctionCall(
     SqlGenerator sqlgen, string functionName, DbFunctionExpression functionExpression, bool isPropertyAccess)
 {
     return WriteInstanceFunctionCall(sqlgen, functionName, functionExpression, isPropertyAccess, null);
 }
コード例 #41
0
 public override ISqlFragment HandleFunction(SqlGenerator sqlGenerator, DbFunctionExpression e)
 {
     AssertArgumentCount(e, 1);
     return(new SqlBuilder("date_trunc('day', ", e.Arguments[0].Accept(sqlGenerator), ")"));
 }
コード例 #42
0
 public void Process(DbMethodCallExpression exp, SqlGenerator generator)
 {
     exp.Object.Accept(generator);
     generator.SqlBuilder.Append(" LIKE '%' || ");
     exp.Arguments.First().Accept(generator);
 }
コード例 #43
0
 /// <summary>
 ///     Constructor
 /// </summary>
 public DapperRepository(SqlProvider sqlProvider)
 {
     SqlGenerator = new SqlGenerator <TEntity>(sqlProvider);
 }
コード例 #44
0
        public override Expression VisitSelect(SelectExpression selectExpression)
        {
            Check.NotNull(selectExpression, nameof(selectExpression));

            IDisposable subQueryIndent = null;

            if (selectExpression.Alias != null)
            {
                _rcbsql.AppendLine("(");

                subQueryIndent = _rcbsql.Indent();
            }

            _rcbsql.Append("SELECT ");

            var projectionAdded = false;

            if (selectExpression.IsProjectStar)
            {
                _rcbsql.Append("*");
                projectionAdded = true;
            }

            if (selectExpression.Projection.Count > 0)
            {
                if (selectExpression.IsProjectStar)
                {
                    _rcbsql.Append(", ");
                }

                for (int i = 0; i < selectExpression.Projection.Count; i++)
                {
                    var col = (ColumnExpression)selectExpression.Projection[i];
                    _rcbsql.Append($"{col.Name} ");
                    if (i < selectExpression.Projection.Count - 1)
                    {
                        _rcbsql.Append(", ");
                    }
                }
                projectionAdded = true;
            }

            if (!projectionAdded)
            {
                _rcbsql.Append("1");
            }

            if (selectExpression.Tables.Count > 0)
            {
                _rcbsql.AppendLine()
                .Append("FROM ");

                GenerateList(selectExpression.Tables, tx =>
                {
                    var te     = ((TableExpression)tx);
                    var schema = string.IsNullOrEmpty(te.Schema) ? __taosConnectionStringBuilder.DataBase : te.Schema;
                    _rcbsql.Append($"{schema}.{te.Table}");
                }, null);
            }
            else
            {
                GeneratePseudoFromClause();
            }

            if (selectExpression.Predicate != null)
            {
                GeneratePredicate(selectExpression.Predicate);
            }

            if (selectExpression.GroupBy.Count > 0)
            {
                _rcbsql.AppendLine();

                _rcbsql.Append("GROUP BY ");
                GenerateList(selectExpression.GroupBy);
            }

            if (selectExpression.Having != null)
            {
                GenerateHaving(selectExpression.Having);
            }

            if (selectExpression.OrderBy.Count > 0)
            {
                var orderByList = new List <Ordering>(selectExpression.OrderBy);

                // Filter out constant and parameter expressions (SELECT 1) if there is no skip or take #10410
                if (selectExpression.Limit == null && selectExpression.Offset == null)
                {
                    //   orderByList.RemoveAll(o => IsOrderByExpressionConstant(ApplyOptimizations(o.Expression, searchCondition: false)));
                }

                if (orderByList.Count > 0)
                {
                    _rcbsql.AppendLine();

                    GenerateOrderBy(orderByList);
                }
            }

            GenerateLimitOffset(selectExpression);

            if (subQueryIndent != null)
            {
                subQueryIndent.Dispose();

                _rcbsql.AppendLine()
                .Append(")");

                if (selectExpression.Alias.Length > 0)
                {
                    _rcbsql
                    .Append(AliasSeparator)
                    .Append(SqlGenerator.DelimitIdentifier(selectExpression.Alias));
                }
            }

            return(selectExpression);
        }
コード例 #45
0
 public DapperRepository(IDbConnection connection, ESqlConnector sqlConnector)
 {
     Connection   = connection;
     SqlGenerator = new SqlGenerator <TEntity>(sqlConnector);
 }
コード例 #46
0
 protected override void AppendIdentityWhereCondition(StringBuilder commandStringBuilder, ColumnModification columnModification)
 => Check.NotNull(commandStringBuilder, nameof(commandStringBuilder))
 .Append(SqlGenerator.DelimitIdentifier(Check.NotNull(columnModification, nameof(columnModification)).ColumnName))
 .Append(" = ")
 .Append("scope_identity()");
コード例 #47
0
        public override void CreateField(ITable table, IField field)
        {
            var sql = SqlGenerator.GenerateCreateFieldStatement(_generator, table, field);

            ExecuteNonQuery(sql);
        }
コード例 #48
0
ファイル: SymbolPair.cs プロジェクト: govorovvs/NETProvider
 public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)
 {
     // Symbol pair should never be part of a SqlBuilder.
     Debug.Assert(false);
 }
コード例 #49
0
    /// <summary>
    /// Adds form field info to the form to the specified position.
    /// </summary>
    /// <param name="ffi">Form field info which will be added</param>
    /// <param name="category">Category name</param>
    /// <param name="position">Field position in the category</param>
    private string AddField(FormFieldInfo ffi, string category, int position)
    {
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm"))
        {
            RedirectToAccessDenied("cms.form", "EditForm");
        }

        var dci = DataClassInfoProvider.GetDataClassInfo(ClassName);

        if (dci != null)
        {
            RaiseBeforeDefinitionUpdate();

            // Ensure the transaction
            using (var tr = new CMSLateBoundTransaction())
            {
                string columnType = DataTypeManager.GetSqlType(ffi.DataType, ffi.Size, ffi.Precision);

                TableManager tm = new TableManager(dci.ClassConnectionString);
                tr.BeginTransaction();

                // Add new column
                tm.AddTableColumn(dci.ClassTableName, ffi.Name, columnType, true, null);

                // Add field to form
                FormInfo.AddFormItem(ffi);
                if (!String.IsNullOrEmpty(category) || position >= 0)
                {
                    FormInfo.MoveFormFieldToPositionInCategory(ffi.Name, category, position);
                }

                // Update form definition
                dci.ClassFormDefinition = FormInfo.GetXmlDefinition();

                // Update class schema
                dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);

                try
                {
                    // Save the class data
                    DataClassInfoProvider.SetDataClassInfo(dci);
                }
                catch (Exception)
                {
                    return(GetString("FormBuilder.ErrorSavingForm"));
                }

                // Generate default view
                SqlGenerator.GenerateDefaultView(dci, SiteContext.CurrentSiteName);
                QueryInfoProvider.ClearDefaultQueries(dci, true, true);

                // Hide field for alternative forms that require it
                HideFieldInAlternativeForms(ffi, dci);

                // Commit the transaction
                tr.Commit();
            }

            ClearHashtables();

            RaiseAfterDefinitionUpdate();

            // Update inherited classes with new fields
            FormHelper.UpdateInheritedClasses(dci);
        }
        else
        {
            return(GetString("FormBuilder.ErrorSavingForm"));
        }

        return(string.Empty);
    }
コード例 #50
0
 public void Process(DbMethodCallExpression exp, SqlGenerator generator)
 {
     generator.SqlBuilder.Append("UPPER(");
     exp.Object.Accept(generator);
     generator.SqlBuilder.Append(")");
 }
コード例 #51
0
 protected internal static string Quote(string name)
 {
     return(SqlGenerator.QuoteIdentifier(name));
 }
コード例 #52
0
 public void Process(DbMethodCallExpression exp, SqlGenerator generator)
 {
     SqlGenerator.DbFunction_DATEADD(generator, "days", exp);
 }
コード例 #53
0
        public void Process(DbMethodCallExpression exp, SqlGenerator generator)
        {
            MethodInfo method = exp.Method;

            if (exp.Method == UtilConstants.MethodInfo_String_Contains)
            {
                Method_String_Contains(exp, generator);
                return;
            }

            List <DbExpression> exps    = new List <DbExpression>();
            IEnumerable         values  = null;
            DbExpression        operand = null;

            Type declaringType = method.DeclaringType;

            if (typeof(IList).IsAssignableFrom(declaringType) || (declaringType.IsGenericType && typeof(ICollection <>).MakeGenericType(declaringType.GetGenericArguments()).IsAssignableFrom(declaringType)))
            {
                if (exp.Object.NodeType == DbExpressionType.SqlQuery)
                {
                    /* where Id in(select id from T) */

                    operand = exp.Arguments[0];
                    In(generator, (DbSqlQueryExpression)exp.Object, operand);
                    return;
                }

                if (!exp.Object.IsEvaluable())
                {
                    throw new NotSupportedException(exp.ToString());
                }

                values  = DbExpressionExtension.Evaluate(exp.Object) as IEnumerable; //Enumerable
                operand = exp.Arguments[0];
                goto constructInState;
            }
            if (method.IsStatic && declaringType == typeof(Enumerable) && exp.Arguments.Count == 2)
            {
                DbExpression arg0 = exp.Arguments[0];
                if (arg0.NodeType == DbExpressionType.SqlQuery)
                {
                    /* where Id in(select id from T) */

                    operand = exp.Arguments[1];
                    In(generator, (DbSqlQueryExpression)arg0, operand);
                    return;
                }

                if (!arg0.IsEvaluable())
                {
                    throw UtilExceptions.NotSupportedMethod(exp.Method);
                }

                values  = DbExpressionExtension.Evaluate(arg0) as IEnumerable;
                operand = exp.Arguments[1];
                goto constructInState;
            }

            throw UtilExceptions.NotSupportedMethod(exp.Method);

constructInState:
            foreach (object value in values)
            {
                if (value == null)
                {
                    exps.Add(DbExpression.Constant(null, operand.Type));
                }
                else
                {
                    Type valueType = value.GetType();
                    if (valueType.IsEnum)
                    {
                        valueType = Enum.GetUnderlyingType(valueType);
                    }

                    if (Utils.IsToStringableNumericType(valueType))
                    {
                        exps.Add(DbExpression.Constant(value));
                    }
                    else
                    {
                        exps.Add(DbExpression.Parameter(value));
                    }
                }
            }

            In(generator, exps, operand);
        }
コード例 #54
0
 public void Process(DbMethodCallExpression exp, SqlGeneratorBase generator)
 {
     SqlGenerator.Aggregate_Min(generator, exp.Arguments.First(), exp.Method.ReturnType);
 }
コード例 #55
0
        /// <inheritdoc />
        public virtual Task <TEntity> FindAsync(Expression <Func <TEntity, bool> > predicate, IDbTransaction transaction)
        {
            var queryResult = SqlGenerator.GetSelectFirst(predicate);

            return(Connection.QueryFirstOrDefaultAsync <TEntity>(queryResult.GetSql(), queryResult.Param, transaction));
        }
コード例 #56
0
        public override void AlterField(ITable table, IField field)
        {
            var sql = SqlGenerator.GenerateAlterTableAndFieldStatement(_generator, table, field, "MODIFY COLUMN");

            ExecuteNonQuery(sql);
        }
コード例 #57
0
        private static ISqlFragment HandleSpatialCanonicalFunction(
            SqlGenerator sqlgen,
            DbFunctionExpression functionExpression,
            Dictionary<string, FunctionHandler> staticMethodsMap,
            Dictionary<string, string> instancePropertiesMap,
            Dictionary<string, string> renamedInstanceMethodsMap)
        {
            FunctionHandler staticFunctionHandler;
            string instancePropertyName;
            if (staticMethodsMap.TryGetValue(functionExpression.Function.Name, out staticFunctionHandler))
            {
                return staticFunctionHandler(sqlgen, functionExpression);
            }
            else if (instancePropertiesMap.TryGetValue(functionExpression.Function.Name, out instancePropertyName))
            {
                Debug.Assert(
                    functionExpression.Function.Parameters.Count > 0
                    && functionExpression.Function.Parameters[0].TypeUsage.IsSpatialType(),
                    "Instance property function does not have instance parameter?");
                return WriteInstanceFunctionCall(
                    sqlgen, instancePropertyName, functionExpression, isPropertyAccess: true, castReturnTypeTo: null);
            }
            else
            {
                // Default translation pattern is instance method; the instance method name may differ from that of the spatial canonical function
                Debug.Assert(
                    functionExpression.Function.Parameters.Count > 0
                    && functionExpression.Function.Parameters[0].TypeUsage.IsSpatialType(),
                    "Instance method function does not have instance parameter?");
                string effectiveFunctionName;
                if (!renamedInstanceMethodsMap.TryGetValue(functionExpression.Function.Name, out effectiveFunctionName))
                {
                    effectiveFunctionName = functionExpression.Function.Name;
                }

                // For AsGml() calls, the XML result must be cast to string to match the declared function result type.
                string castResultType = null;
                if (effectiveFunctionName == "AsGml")
                {
                    castResultType = "nvarchar(max)";
                }
                return WriteInstanceFunctionCall(
                    sqlgen, effectiveFunctionName, functionExpression, isPropertyAccess: false, castReturnTypeTo: castResultType);
            }
        }
コード例 #58
0
 static IEnumerable <string> Tables(StoreItemCollection storeItems)
 {
     foreach (var entitySet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <EntitySet>())
     {
         var result = new StringBuilder();
         var additionalColumnComments = new Dictionary <string, string>();
         result.AppendFormat("RECREATE TABLE {0} (", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)));
         result.AppendLine();
         foreach (var property in MetadataHelpers.GetProperties(entitySet.ElementType))
         {
             var column = GenerateColumn(property);
             result.Append("\t");
             result.Append(column.ColumnName);
             result.Append(",");
             result.AppendLine();
             foreach (var item in column.ColumnComments)
             {
                 additionalColumnComments.Add(item.Key, item.Value);
             }
         }
         result.AppendFormat("CONSTRAINT {0} PRIMARY KEY ({1})",
                             SqlGenerator.QuoteIdentifier(string.Format("PK_{0}", MetadataHelpers.GetTableName(entitySet))),
                             string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         result.Append(");");
         result.AppendLine();
         foreach (var identity in entitySet.ElementType.KeyMembers.Where(pk => MetadataHelpers.IsStoreGeneratedIdentity(pk)).Select(i => i.Name))
         {
             additionalColumnComments.Add(identity, "#PK_GEN#");
         }
         foreach (var comment in additionalColumnComments)
         {
             result.AppendFormat("COMMENT ON COLUMN {0}.{1} IS '{2}';",
                                 SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)),
                                 SqlGenerator.QuoteIdentifier(comment.Key),
                                 comment.Value);
             result.AppendLine();
         }
         yield return(result.ToString());
     }
 }
コード例 #59
0
        private static ISqlFragment WriteInstanceFunctionCall(
            SqlGenerator sqlgen, string functionName, DbFunctionExpression functionExpression, bool isPropertyAccess,
            string castReturnTypeTo)
        {
            Debug.Assert(
                !isPropertyAccess || functionExpression.Arguments.Count == 1,
                "Property accessor instance functions should have only the single instance argument");

            return WrapWithCast(
                castReturnTypeTo, result =>
                                      {
                                          var instanceExpression = functionExpression.Arguments[0];

                                          // Write the instance - if this is another function call, it need not be enclosed in parentheses.
                                          if (instanceExpression.ExpressionKind
                                              != DbExpressionKind.Function)
                                          {
                                              sqlgen.ParenthesizeExpressionIfNeeded(instanceExpression, result);
                                          }
                                          else
                                          {
                                              result.Append(instanceExpression.Accept(sqlgen));
                                          }
                                          result.Append(".");
                                          result.Append(functionName);

                                          if (!isPropertyAccess)
                                          {
                                              WriteFunctionArguments(sqlgen, functionExpression.Arguments.Skip(1), result);
                                          }
                                      });
        }
コード例 #60
0
 static IEnumerable <string> ForeignKeyConstraints(StoreItemCollection storeItems)
 {
     foreach (var associationSet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <AssociationSet>())
     {
         var result = new StringBuilder();
         ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single <ReferentialConstraint>();
         AssociationSetEnd     end        = associationSet.AssociationSetEnds[constraint.FromRole.Name];
         AssociationSetEnd     end2       = associationSet.AssociationSetEnds[constraint.ToRole.Name];
         result.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2})",
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)),
                             SqlGenerator.QuoteIdentifier(string.Format("FK_{0}", associationSet.Name)),
                             string.Join(", ", constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name))));
         result.AppendLine();
         result.AppendFormat("REFERENCES {0}({1})",
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)),
                             string.Join(", ", constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         result.AppendFormat("ON DELETE {0}",
                             end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? "CASCADE" : "NO ACTION");
         result.Append(";");
         yield return(result.ToString());
     }
 }