コード例 #1
0
        public virtual string MakeExecuteScalarWithConn(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            // ExecuteScalar() with connection
            code.AppendLine("public virtual " + ctx.ExecuteScalarReturnType + " ExecuteScalar(" + ctx.MethodSignature + "IDbConnection conn, IDbTransaction tx = null){");
            code.AppendLine("IDbCommand cmd = conn.CreateCommand();");
            code.AppendLine("if(tx != null)");
            code.AppendLine("cmd.Transaction = tx;");
            code.AppendLine("cmd.CommandText = getCommandText();");
            foreach (var qp in ctx.Query.QueryParams)
            {
                code.AppendLine("AddAParameter(cmd, \"" + qp.DbType + "\", \"" + qp.DbName + "\", " + qp.CSName + ", " + qp.Length + ", " + qp.Scale + ", " + qp.Precision + ");");
            }
            code.AppendLine("var result = cmd.ExecuteScalar();");
            // only convert dbnull if nullable

            code.AppendLine("if( result == null || result == DBNull.Value)");
            code.AppendLine("return null;");
            code.AppendLine("else");
            code.AppendLine("return (" + ctx.ExecuteScalarReturnType + ")result;");
            code.AppendLine("}");
            // close ExecuteScalar()
            return(code.ToString());
        }
コード例 #2
0
        public void InjectPOCOFactory(ICodeGenerationContext ctx, ProjectItem partialClass)
        {
            bool rememberToClose = false;

            if (!partialClass.IsOpen)
            {
                partialClass.Open();
                rememberToClose = true;
            }
            var    textDoc   = ((TextDocument)partialClass.Document.Object());
            var    ep        = textDoc.CreateEditPoint();
            string textOfDoc = ep.GetText(textDoc.EndPoint);

            if (textOfDoc.IndexOf("Results CreatePoco(") == -1)
            {
                StringBuilder bldr = new StringBuilder();
                bldr.AppendLine("// POCO factory, called for each line of results. For polymorphic POCOs, put your instantiation logic here.");
                bldr.AppendLine("// Tag the results class as abstract above, add some virtual methods, create some subclasses, then instantiate them here based on data in the row.");
                bldr.AppendLine("public partial class " + ctx.BaseName + "\n{");
                bldr.AppendLine(ctx.BaseName + "Results CreatePoco(System.Data.IDataRecord record)\n{");
                bldr.AppendLine("return new " + ctx.BaseName + "Results();\n}\n}");

                int    insertHere  = textOfDoc.LastIndexOf('}');
                string newContents = textOfDoc.Substring(0, insertHere) + bldr.ToString() + textOfDoc.Substring(insertHere, textOfDoc.Length - insertHere);
                ep.ReplaceText(textDoc.EndPoint, newContents, 0);
                ep.SmartFormat(textDoc.EndPoint);
                partialClass.Save();
            }
            if (rememberToClose)
            {
                partialClass.Document.Close();
            }
        }
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var genericArgs = string.Join(", ", GenericTypeArguments ?? new string[0]);

            genericArgs = string.IsNullOrEmpty(genericArgs) ? string.Empty : $"<{genericArgs}>";
            return($"type {Name}{genericArgs} = {Definition!.GenerateCode(context)};");
        }
コード例 #4
0
        public string MakeSelfTestMethod(ICodeGenerationContext ctx)
        {
            char[]        spaceComma = new char[] { ',', ' ' };
            StringBuilder code       = new StringBuilder();

            code.AppendLine("[Fact]");
            code.AppendLine("public void " + ctx.BaseName + "SelfTest()");
            code.AppendLine("{");
            code.AppendLine("var queryText = getCommandText();");
            code.AppendLine("// we'll be getting a runtime version with the comments section closed. To run without parameters, open it.");
            code.AppendLine("queryText = queryText.Replace(\"/*designTime\", \"-- designTime\");");
            code.AppendLine("queryText = queryText.Replace(\"endDesignTime*/\", \"-- endDesignTime\");");
            // QfruntimeConnection will be used, but we still need to reference a provider, for the prepare parameters method.
            code.AppendLine($"var schema = new AdoSchemaFetcher().GetFields(QfRuntimeConnection.GetConnection(), \"{ctx.Config.Provider}\", queryText);");
            code.Append("Assert.True(" + ctx.ResultFields.Count + " <=  schema.Count,");
            code.AppendLine("\"Query only returns \" + schema.Count.ToString() + \" columns. Expected at least " + ctx.ResultFields.Count + ". \");");
            for (int i = 0; i < ctx.ResultFields.Count; i++)
            {
                var col = ctx.ResultFields[i];
                code.Append("Assert.True(schema[" + i.ToString() + "].TypeDb == \"" + col.TypeDb + "\",");
                code.AppendLine("\"Result Column " + i.ToString() + " Type wrong. Expected " + col.TypeDb + ". Found \" + schema[" + i.ToString() + "].TypeDb + \".\");");
                code.Append("Assert.True(schema[" + i.ToString() + "].ColumnName == \"" + col.ColumnName + "\",");
                code.AppendLine("\"Result Column " + i.ToString() + " Name wrong. Expected " + col.ColumnName + ". Found \" + schema[" + i.ToString() + "].ColumnName + \".\");");
            }
            code.AppendLine("}");
            return(code.ToString());
        }
        public string GenerateBody(string name, ICodeGenerationContext context)
        {
            var result = new StringBuilder();

            result.Append("class ");
            if (name != null)
            {
                result.Append(name).Append(" ");
            }
            if (BaseClass != null)
            {
                result.Append("extends ").Append(BaseClass.GenerateCode(context)).Append(" ");
            }
            if (ImplementedInterfaces?.Any() == true)
            {
                result.Append("implements ").Append(string.Join(", ", ImplementedInterfaces.Select(x => x.GenerateCode(context)))).Append(" ");
            }
            result.Append("{").Append(context.NewLine);
            foreach (var member in Members)
            {
                result.AppendWithTab(context.Tab, member.GenerateCode(context), context.NewLine)
                .Append(context.NewLine)
                .Append(context.NewLine);
            }
            result.Append("}");
            return(result.ToString());
        }
コード例 #6
0
        public string SelfTestUsings(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            code.AppendLine("using QueryFirst;");
            code.AppendLine("using Xunit;");
            return(code.ToString());
        }
コード例 #7
0
 public string GenerateCode(ICodeGenerationContext context)
 {
     if (ValueLiteral == null)
     {
         return(Name);
     }
     return($"{Name} = {ValueLiteral.GenerateCode(context)}");
 }
コード例 #8
0
 public override string GenerateCode(ICodeGenerationContext context)
 {
     if (context.TypeChecker == JavaScriptTypeChecker.TypeScript)
     {
         return($"Nullable<{InnerType.GenerateCode(context)}>");
     }
     return("?" + InnerType.GenerateCode(context));
 }
コード例 #9
0
 public override string GenerateCode(ICodeGenerationContext context)
 {
     if (context.TypeChecker == JavaScriptTypeChecker.TypeScript)
     {
         return($"({Expression.GenerateCode(context)}) as {TargetType.GenerateCode(context)}");
     }
     return($"(({Expression.GenerateCode(context)}): {TargetType.GenerateCode(context)})");
 }
 public override string GenerateCode(ICodeGenerationContext context)
 {
     if (context.TypeChecker == JavaScriptTypeChecker.TypeScript)
     {
         return($"import {{ {TypeName} }} from '{context.GetReferenceFromUnitToAnother(CurrentUnit.Path, TargetUnit.Path)}';");
     }
     return($"import type {{ {TypeName} }} from '{context.GetReferenceFromUnitToAnother(CurrentUnit.Path, TargetUnit.Path)}';");
 }
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var result = new StringBuilder();

            result.AppendFormat("interface {0} ", Name);
            result.Append(Definition !.GenerateCode(context));
            return(result.ToString());
        }
コード例 #12
0
 internal TypeScriptGenerator(TypeScriptCodeGenerationContext tsCtx, ICodeGenerationContext codeCtx)
 {
     Context         = tsCtx;
     CodeContext     = codeCtx;
     _typeMappings   = new Dictionary <Type, TSTypeFile>();
     _attributeCache = codeCtx.CurrentRun.EngineMap.AllTypesAttributesCache;
     _typeFiles      = new List <TSTypeFile>();
     _success        = true;
 }
コード例 #13
0
ファイル: Query.cs プロジェクト: squidesk/query-first
        public Query(ICodeGenerationContext _ctx)
        {
            ctx = _ctx;
            var textDoc = ((TextDocument)ctx.QueryDoc.Object());
            var start   = textDoc.StartPoint;

            text     = start.CreateEditPoint().GetText(textDoc.EndPoint);
            provider = ctx.Provider;
        }
コード例 #14
0
ファイル: MySqlClient.cs プロジェクト: cool-lei/query-first
        public override string MakeAddAParameter(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            code.AppendLine("private void AddAParameter(IDbCommand Cmd, string DbType, string DbName, object Value, int Length, int Scale, int Precision)\n{");
            code.AppendLine("((MySql.Data.MySqlClient.MySqlCommand)Cmd).Parameters.AddWithValue(DbName, Value);");
            code.AppendLine("}");
            return(code.ToString());
        }
コード例 #15
0
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var resultWithNewLines = string.Join(" |" + context.NewLine, types.Select(x => x.GenerateCode(context)));

            if (resultWithNewLines.Length < 90)
            {
                return(string.Join(" | ", types.Select(x => x.GenerateCode(context))));
            }
            return(resultWithNewLines);
        }
コード例 #16
0
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var argument = Argument.Type.GenerateCode(context);

            if (argument != "string" && argument != "number")
            {
                return($"[key in {Argument.Type.GenerateCode(context)}]{(Optional ? "?" : "")}: {ResultType.GenerateCode(context)};");
            }
            return($"[{Argument.GenerateCode(context)}]: {ResultType.GenerateCode(context)};");
        }
コード例 #17
0
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var innerTypeCode = ItemType.GenerateCode(context);

            if (!(ItemType is TypeScriptUnionType))
            {
                return(innerTypeCode + "[]");
            }

            return($"Array<{innerTypeCode}>");
        }
コード例 #18
0
 public virtual string CloseNamespace(ICodeGenerationContext ctx)
 {
     if (!string.IsNullOrEmpty(ctx.Namespace))
     {
         return("}" + Environment.NewLine);
     }
     else
     {
         return("");
     }
 }
コード例 #19
0
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var result = new StringBuilder();

            result.AppendFormat("{{").Append(context.NewLine);
            foreach (var member in Members)
            {
                result.AppendWithTab(context.Tab, member.GenerateCode(context), context.NewLine).Append(context.NewLine);
            }
            result.Append("}");
            return(result.ToString());
        }
コード例 #20
0
        public virtual string MakeGetCommandTextMethod(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            // public load command text
            code.AppendLine("public string getCommandText(){");
            code.AppendLine("return @\"");
            code.Append(ctx.Query.FinalTextForCode);
            code.AppendLine("\";");
            code.AppendLine("}"); // close method;
            return(code.ToString());
        }
コード例 #21
0
        public virtual string Usings(ICodeGenerationContext ctx)
        {
            return(@"using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

");
        }
 public override string GenerateCode(ICodeGenerationContext context)
 {
     if (context.TypeChecker == JavaScriptTypeChecker.TypeScript)
     {
         var argument = Argument.Type.GenerateCode(context);
         if (argument != "stirng" || argument != "number")
         {
             return($"[key in {Argument.Type.GenerateCode(context)}]{(Optional ? "?" : "")}: {ResultType.GenerateCode(context)};");
         }
     }
     return($"[{Argument.GenerateCode(context)}]: {ResultType.GenerateCode(context)};");
 }
コード例 #23
0
ファイル: Npgsql.cs プロジェクト: squidesk/query-first
        public virtual string MakeAddAParameter(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            code.AppendLine("private void AddAParameter(IDbCommand Cmd, string DbType, string DbName, object Value, int Length, int Scale, int Precision)\n{");
            code.AppendLine("var myParam = new Npgsql.NpgsqlParameter();");
            code.AppendLine("myParam.ParameterName = DbName;");
            code.AppendLine("if(DbType != \"\")");
            code.AppendLine("myParam.DbType = (DbType)System.Enum.Parse(typeof(DbType), DbType);");
            code.AppendLine("myParam.Value = Value != null ? Value : DBNull.Value; ");
            code.AppendLine("Cmd.Parameters.Add(myParam);");
            code.AppendLine("}");
            return(code.ToString());
        }
コード例 #24
0
        public virtual string MakeExecuteNonQueryWithoutConn(ICodeGenerationContext ctx)
        {
            char[]        spaceComma = new char[] { ',', ' ' };
            StringBuilder code       = new StringBuilder();

            //ExecuteScalar without connection
            code.AppendLine("public virtual int ExecuteNonQuery(" + ctx.MethodSignature.Trim(spaceComma) + "){");
            code.AppendLine("using (IDbConnection conn = QfRuntimeConnection.GetConnection())");
            code.AppendLine("{");
            code.AppendLine("conn.Open();");
            code.AppendLine("return ExecuteNonQuery(" + ctx.CallingArgs + " conn);");
            code.AppendLine("}");
            code.AppendLine("}");
            return(code.ToString());
        }
コード例 #25
0
        public override string GenerateCode(ICodeGenerationContext context)
        {
            var result = new StringBuilder();

            result.Append("{").Append(context.NewLine);
            var propertiesString = string.Join("," + context.NewLine, Properties.Select(x => x.GenerateCode(context)));

            if (propertiesString.Length > 0)
            {
                propertiesString += ",";
            }
            result.AppendWithTab(context.Tab, propertiesString, context.NewLine).Append(context.NewLine);
            result.Append("}");
            return(result.ToString());
        }
コード例 #26
0
        public virtual string MakeGetOneWithoutConn(ICodeGenerationContext ctx)
        {
            char[]        spaceComma = new char[] { ',', ' ' };
            StringBuilder code       = new StringBuilder();

            // GetOne without connection
            code.AppendLine("public virtual " + ctx.ResultClassName + " GetOne(" + ctx.MethodSignature.Trim(spaceComma) + "){");
            code.AppendLine("using (IDbConnection conn = QfRuntimeConnection.GetConnection())");
            code.AppendLine("{");
            code.AppendLine("conn.Open();");
            code.AppendLine("return GetOne(" + ctx.CallingArgs + " conn);");
            code.AppendLine("}");
            code.AppendLine("}");
            return(code.ToString());
        }
コード例 #27
0
        public virtual string MakeGetOneWithConn(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            // GetOne() with connection
            code.AppendLine("public virtual " + ctx.ResultClassName + " GetOne(" + ctx.MethodSignature + "IDbConnection conn, IDbTransaction tx = null)");
            code.AppendLine("{");
            code.AppendLine("var all = Execute(" + ctx.CallingArgs + " conn,tx);");
            code.AppendLine("using (IEnumerator<" + ctx.ResultClassName + "> iter = all.GetEnumerator())");
            code.AppendLine("{");
            code.AppendLine("iter.MoveNext();");
            code.AppendLine("return iter.Current;");
            code.AppendLine("}");
            code.AppendLine("}"); // close GetOne() method
            return(code.ToString());
        }
コード例 #28
0
        public virtual string MakeExecuteNonQueryWithConn(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            // ExecuteScalar() with connection
            code.AppendLine("public virtual int ExecuteNonQuery(" + ctx.MethodSignature + "IDbConnection conn, IDbTransaction tx = null){");
            code.AppendLine("IDbCommand cmd = conn.CreateCommand();");
            code.AppendLine("if(tx != null)");
            code.AppendLine("cmd.Transaction = tx;");
            code.AppendLine("cmd.CommandText = getCommandText();");
            foreach (var qp in ctx.Query.QueryParams)
            {
                code.AppendLine("AddAParameter(cmd, \"" + qp.DbType + "\", \"" + qp.DbName + "\", " + qp.CSName + ", " + qp.Length + ", " + qp.Scale + ", " + qp.Precision + ");");
            }
            code.AppendLine("return cmd.ExecuteNonQuery();");
            code.AppendLine("}");
            // close ExecuteScalar()
            return(code.ToString());
        }
コード例 #29
0
        public virtual string MakeAddAParameter(ICodeGenerationContext ctx)
        {
            StringBuilder code = new StringBuilder();

            code.AppendLine("private void AddAParameter(IDbCommand Cmd, string DbType, string DbName, object Value, int Length, byte Scale, byte Precision)\n{");
            code.AppendLine("var dbType = (SqlDbType)System.Enum.Parse(typeof(SqlDbType), DbType);");
            code.AppendLine("SqlParameter myParam;");
            code.AppendLine("if(Length != 0){");
            code.AppendLine("myParam = new SqlParameter(DbName, dbType, Length);");
            code.AppendLine("}else{");
            code.AppendLine("myParam = new SqlParameter(DbName, dbType);");
            code.AppendLine("}");
            code.AppendLine("myParam.Value = Value != null ? Value : DBNull.Value;");
            code.AppendLine("myParam.Scale = Scale;");
            code.AppendLine("myParam.Precision = Precision;");
            code.AppendLine("Cmd.Parameters.Add( myParam);");
            code.AppendLine("}");

            return(code.ToString());
        }
        public override string GenerateCode(string name, ICodeGenerationContext context)
        {
            var result = new StringBuilder();

            if (IsStatic)
            {
                result.Append("static ");
            }
            if (IsAsync)
            {
                result.Append("async ");
            }
            result.AppendFormat("{0}({1}): {2} {{", name, Arguments.GenerateCodeCommaSeparated(context), Result.GenerateCode(context)).Append(context.NewLine);
            foreach (var statement in Body)
            {
                result.AppendWithTab(context.Tab, statement.GenerateCode(context), context.NewLine).Append(context.NewLine);
            }
            result.Append("}");
            return(result.ToString());
        }