Exemple #1
0
        public override string ToCreateTableStatement(Type tableType)
        {
            var sbColumns     = StringBuilderCache.Allocate();
            var sbConstraints = StringBuilderCache.Allocate();

            var modelDef = GetModel(tableType);

            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
                if (fieldDef.CustomSelect != null)
                {
                    continue;
                }

                if (sbColumns.Length != 0)
                {
                    sbColumns.Append(", \n  ");
                }

                sbColumns.Append(GetColumnDefinition(fieldDef));

                if (fieldDef.ForeignKey == null)
                {
                    continue;
                }

                var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);
                sbConstraints.AppendFormat(
                    ", \n\n  CONSTRAINT {0} FOREIGN KEY ({1}) REFERENCES {2} ({3})",
                    GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef)),
                    GetQuotedColumnName(fieldDef.FieldName),
                    GetQuotedTableName(refModelDef),
                    GetQuotedColumnName(refModelDef.PrimaryKey.FieldName));

                if (!string.IsNullOrEmpty(fieldDef.ForeignKey.OnDelete))
                {
                    sbConstraints.AppendFormat(" ON DELETE {0}", fieldDef.ForeignKey.OnDelete);
                }

                if (!string.IsNullOrEmpty(fieldDef.ForeignKey.OnUpdate))
                {
                    sbConstraints.AppendFormat(" ON UPDATE {0}", fieldDef.ForeignKey.OnUpdate);
                }
            }
            var sql = string.Format(
                "CREATE TABLE {0} \n(\n  {1}{2} \n); \n", GetQuotedTableName(modelDef),
                StringBuilderCache.ReturnAndFree(sbColumns),
                StringBuilderCacheAlt.ReturnAndFree(sbConstraints));

            return(sql);
        }
Exemple #2
0
        public string Type(string type, string[] genericArgs)
        {
            var useType = TypeFilter?.Invoke(type, genericArgs);

            if (useType != null)
            {
                return(useType);
            }

            if (!genericArgs.IsEmpty())
            {
                if (type == "Nullable`1")
                {
                    return("{0}?".Fmt(TypeAlias(GenericArg(genericArgs[0]))));
                }
                if (ArrayTypes.Contains(type))
                {
                    return("[{0}]".Fmt(TypeAlias(GenericArg(genericArgs[0]))).StripNullable());
                }
                if (DictionaryTypes.Contains(type))
                {
                    return("[{0}:{1}]".Fmt(
                               TypeAlias(GenericArg(genericArgs[0])),
                               TypeAlias(GenericArg(genericArgs[1]))));
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return("{0}<{1}>".Fmt(typeName, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }
            else
            {
                type = type.StripNullable();
            }

            return(TypeAlias(type));
        }
Exemple #3
0
        public override string ToString()
        {
            var sb = StringBuilderCacheAlt.Allocate();

            foreach (var arg in Args)
            {
                if (sb.Length > 0)
                {
                    sb.Append(',');
                }
                sb.Append(JsonValue(arg));
            }
            return($"{Name}({StringBuilderCacheAlt.ReturnAndFree(sb)})");
        }
Exemple #4
0
        //Output different format for debugging to verify command was parsed correctly
        public virtual string ToDebugString()
        {
            var sb = StringBuilderCacheAlt.Allocate();

            foreach (var arg in Args)
            {
                if (sb.Length > 0)
                {
                    sb.Append('|');
                }
                sb.Append(arg);
            }
            return($"[{Name}:{StringBuilderCacheAlt.ReturnAndFree(sb)}]");
        }
Exemple #5
0
        public string Type(string type, string[] genericArgs)
        {
            var useType = TypeFilter?.Invoke(type, genericArgs);

            if (useType != null)
            {
                return(useType);
            }

            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return /*@Nullable*/ (GenericArg(genericArgs[0]));
                }
                if (ArrayTypes.Contains(type))
                {
                    return($"ArrayList<{GenericArg(genericArgs[0])}>".StripNullable());
                }
                if (DictionaryTypes.Contains(type))
                {
                    return($"HashMap<{GenericArg(genericArgs[0])},{GenericArg(genericArgs[1])}>");
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return($"{typeName}<{StringBuilderCacheAlt.ReturnAndFree(args)}>");
                }
            }
            else
            {
                type = type.StripNullable();
            }

            return(TypeAlias(type));
        }
        public override string ToCreateTableStatement(Type tableType)
        {
            var modelDefinition = OrmLiteUtils.GetModelDefinition(tableType);
            var quotedTableName = this.GetQuotedTableName(modelDefinition);

            var columns     = StringBuilderCache.Allocate();
            var constraints = StringBuilderCacheAlt.Allocate();

            foreach (var fieldDef in modelDefinition.FieldDefinitions)
            {
                if (columns.Length != 0)
                {
                    columns.Append(", \n  ");
                }

                var columnDefinition = this.GetColumnDefinition(fieldDef.Clone(f => f.IsPrimaryKey = false));
                columns.Append(columnDefinition);

                if (fieldDef.IsPrimaryKey)
                {
                    constraints.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY ({2});\n",
                                             quotedTableName,
                                             this.GetQuotedName("PK_" + modelDefinition.ModelName),
                                             this.GetQuotedColumnName(fieldDef.FieldName));
                }

                if (fieldDef.ForeignKey == null || OrmLiteConfig.SkipForeignKeys)
                {
                    continue;
                }

                var foreignModelDefinition = OrmLiteUtils.GetModelDefinition(fieldDef.ForeignKey.ReferenceType);
                constraints.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4}){5}{6};\n",
                                         quotedTableName,
                                         this.GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDefinition, foreignModelDefinition, this.NamingStrategy, fieldDef)),
                                         this.GetQuotedColumnName(fieldDef.FieldName),
                                         this.GetQuotedTableName(foreignModelDefinition),
                                         this.GetQuotedColumnName(foreignModelDefinition.PrimaryKey.FieldName),
                                         this.GetForeignKeyOnDeleteClause(fieldDef.ForeignKey),
                                         this.GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
            }

            return(string.Format("CREATE TABLE {0} \n(\n  {1} \n); \n {2}\n",
                                 quotedTableName,
                                 StringBuilderCache.ReturnAndFree(columns),
                                 StringBuilderCacheAlt.ReturnAndFree(constraints)));
        }
Exemple #7
0
        public bool AppendAttributes(StringBuilderWrapper sb, List <MetadataAttribute> attributes)
        {
            if (attributes == null || attributes.Count == 0)
            {
                return(false);
            }

            foreach (var attr in attributes)
            {
                var attrName = EscapeKeyword(attr.Name);

                if ((attr.Args == null || attr.Args.Count == 0) &&
                    (attr.ConstructorArgs == null || attr.ConstructorArgs.Count == 0))
                {
                    sb.AppendLine("<{0}>".Fmt(attrName));
                }
                else
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    if (attr.ConstructorArgs != null)
                    {
                        foreach (var ctorArg in attr.ConstructorArgs)
                        {
                            if (args.Length > 0)
                            {
                                args.Append(", ");
                            }
                            args.Append("{0}".Fmt(TypeValue(ctorArg.Type, ctorArg.Value)));
                        }
                    }
                    else if (attr.Args != null)
                    {
                        foreach (var attrArg in attr.Args)
                        {
                            if (args.Length > 0)
                            {
                                args.Append(", ");
                            }
                            args.Append("{0}:={1}".Fmt(attrArg.Name, TypeValue(attrArg.Type, attrArg.Value)));
                        }
                    }
                    sb.AppendLine("<{0}({1})>".Fmt(attrName, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }

            return(true);
        }
Exemple #8
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand dbCommand, ICollection <string> insertFields = null)
        {
            var sbColumnNames  = StringBuilderCache.Allocate();
            var sbColumnValues = StringBuilderCacheAlt.Allocate();
            var modelDef       = GetModel(typeof(T));

            dbCommand.Parameters.Clear();
            dbCommand.CommandTimeout = OrmLiteConfig.CommandTimeout;

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (fieldDef.IsComputed || fieldDef.IsRowVersion)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
                    sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));

                    AddParameter(dbCommand, fieldDef);
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in CreateParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            dbCommand.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2})",
                                                  GetQuotedTableName(modelDef),
                                                  StringBuilderCache.ReturnAndFree(sbColumnNames),
                                                  StringBuilderCacheAlt.ReturnAndFree(sbColumnValues));
        }
        public bool AppendAttributes(StringBuilderWrapper sb, List <MetadataAttribute> attributes)
        {
            if (attributes == null || attributes.Count == 0)
            {
                return(false);
            }

            foreach (var attr in attributes)
            {
                if ((attr.Args == null || attr.Args.Count == 0) &&
                    (attr.ConstructorArgs == null || attr.ConstructorArgs.Count == 0))
                {
                    sb.AppendLine($"[{attr.Name}]");
                }
                else
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    if (attr.ConstructorArgs != null)
                    {
                        foreach (var ctorArg in attr.ConstructorArgs)
                        {
                            if (args.Length > 0)
                            {
                                args.Append(", ");
                            }
                            args.Append($"{TypeValue(ctorArg.Type, ctorArg.Value)}");
                        }
                    }
                    else if (attr.Args != null)
                    {
                        foreach (var attrArg in attr.Args)
                        {
                            if (args.Length > 0)
                            {
                                args.Append(", ");
                            }
                            args.Append($"{attrArg.Name}={TypeValue(attrArg.Type, attrArg.Value)}");
                        }
                    }
                    sb.AppendLine($"[{attr.Name}({StringBuilderCacheAlt.ReturnAndFree(args)})]");
                }
            }

            return(true);
        }
Exemple #10
0
        public string GetTypeName(Type type)
        {
            try
            {
                //Inner classes?
                var typeName = type == null
                               //|| type.FullName == null
                                        ? null
                                        : StringBuilderCacheAlt.Allocate()
                               .Append(type.FullName.Replace('+', '.').LeftPart('`'));

                if (typeName == null)
                {
                    return(null);
                }

                if (type.HasGenericType()
                    //TODO: support GenericTypeDefinition properly
                    && !type.IsGenericTypeDefinition
                    )
                {
                    var genericArgs = type.GetGenericArguments();

                    typeName.Append("<");
                    var i = 0;
                    foreach (var genericArg in genericArgs)
                    {
                        if (i++ > 0)
                        {
                            typeName.Append(", ");
                        }
                        typeName.Append(GetTypeName(genericArg));
                    }
                    typeName.Append(">");
                }

                return(StringBuilderCacheAlt.ReturnAndFree(typeName));
            }
            catch (Exception)
            {
                //Console.WriteLine(ex);
                throw;
            }
        }
        public string Type(string type, string[] genericArgs)
        {
            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return("{0}?".Fmt(GenericArg(genericArgs[0])));
                }
                if (ArrayTypes.Contains(type))
                {
                    return("{0}[]".Fmt(GenericArg(genericArgs[0])).StripNullable());
                }
                if (DictionaryTypes.Contains(type))
                {
                    return("{{ [index:{0}]: {1}; }}".Fmt(
                               GenericArg(genericArgs[0]),
                               GenericArg(genericArgs[1])));
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return("{0}<{1}>".Fmt(typeName, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }
            else
            {
                type = type.StripNullable();
            }

            return(TypeAlias(type));
        }
Exemple #12
0
        public string Type(string type, string[] genericArgs)
        {
            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return /*@Nullable*/ ("{0}".Fmt(GenericArg(genericArgs[0])));
                }
                if (ArrayTypes.Contains(type))
                {
                    return("ArrayList<{0}>".Fmt(GenericArg(genericArgs[0])));
                }
                if (DictionaryTypes.Contains(type))
                {
                    return("HashMap<{0},{1}>".Fmt(
                               GenericArg(genericArgs[0]),
                               GenericArg(genericArgs[1])));
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return("{0}<{1}>".Fmt(typeName, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }

            return(TypeAlias(type));
        }
Exemple #13
0
        // Join previously split sections back into one document
        public static string JoinSections(List <string> sections)
        {
            var sb = StringBuilderCacheAlt.Allocate();

            for (int i = 0; i < sections.Count; i++)
            {
                if (i > 0)
                {
                    // For subsequent sections, need to make sure we
                    // have a line break after the previous section.
                    string strPrev = sections[sections.Count - 1];
                    if (strPrev.Length > 0 && !strPrev.EndsWith("\n") && !strPrev.EndsWith("\r"))
                    {
                        sb.Append("\n");
                    }
                }

                sb.Append(sections[i]);
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
        public string Type(string type, string[] genericArgs, bool includeNested = false)
        {
            var useType = TypeFilter?.Invoke(type, genericArgs);

            if (useType != null)
            {
                return(useType);
            }

            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return($"{TypeAlias(genericArgs[0], includeNested: includeNested)}?");
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(TypeAlias(arg.SanitizeType(), includeNested: includeNested));
                    }

                    var typeName = NameOnly(type, includeNested: includeNested).SanitizeType();
                    return($"{typeName}<{StringBuilderCacheAlt.ReturnAndFree(args)}>");
                }
            }

            return(TypeAlias(type, includeNested: includeNested));
        }
        public override string GetColumnDefinition(FieldDefinition fieldDef)
        {
            var fieldDefinition = ResolveFragment(fieldDef.CustomFieldDefinition)
                                  ?? GetColumnTypeDefinition(fieldDef.ColumnType, fieldDef.FieldLength, fieldDef.Scale);

            var sql = StringBuilderCache.Allocate();

            sql.AppendFormat("{0} {1}", GetQuotedColumnName(fieldDef.FieldName), fieldDefinition);

            var defaultValue = GetDefaultValue(fieldDef);

            if (fieldDef.IsRowVersion)
            {
                sql.AppendFormat(DefaultValueFormat, 1L);
            }
            else if (!string.IsNullOrEmpty(defaultValue))
            {
                sql.AppendFormat(DefaultValueFormat, defaultValue);
            }

            if (fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))
            {
                sql.Append(AutoIncrementDefinition);
            }
            else
            // Identity columns must accept null to generate a new value.
            if (!fieldDef.IsNullable)
            {
                sql.Append(" NOT NULL");
            }
            if (fieldDef.IsUniqueConstraint)
            {
                sql.Append(" UNIQUE");
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sql));
        }
Exemple #16
0
        // Remove the markdown escapes from a string
        public static string UnescapeString(string str, bool ExtraMode)
        {
            if (str == null || str.IndexOf('\\') == -1)
            {
                return(str);
            }

            var sb = StringBuilderCacheAlt.Allocate();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '\\' && i + 1 < str.Length && IsEscapableChar(str[i + 1], ExtraMode))
                {
                    sb.Append(str[i + 1]);
                    i++;
                }
                else
                {
                    sb.Append(str[i]);
                }
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
Exemple #17
0
        public override string ToInsertRowStatement(IDbCommand cmd, object objWithProperties, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();

            var tableType = objWithProperties.GetType();
            var modelDef  = GetModel(tableType);

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (fieldDef.ReturnOnInsert || (fieldDef.IsPrimaryKey && fieldDef.AutoIncrement && HasInsertReturnValues(modelDef)))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append(GetQuotedColumnName(fieldDef.FieldName));
                }

                if (fieldDef.IsComputed)
                {
                    continue;
                }

                if ((fieldDef.AutoIncrement || !string.IsNullOrEmpty(fieldDef.Sequence) ||
                     fieldDef.Name == OrmLiteConfig.IdField) &&
                    cmd != null)
                {
                    EnsureAutoIncrementSequence(modelDef, fieldDef);

                    var result = GetNextValue(cmd, fieldDef.Sequence, fieldDef.GetValue(objWithProperties));

                    var fieldValue = this.ConvertNumber(fieldDef.FieldType, result);
                    fieldDef.SetValueFn(objWithProperties, fieldValue);
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
                    sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));

                    var p = AddParameter(cmd, fieldDef);
                    p.Value = GetFieldValue(fieldDef, fieldDef.GetValue(objWithProperties)) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in ToInsertRowStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);
            var sql          = string.Format("INSERT INTO {0} ({1}) VALUES ({2}) {3};",
                                             GetQuotedTableName(modelDef),
                                             StringBuilderCache.ReturnAndFree(sbColumnNames),
                                             StringBuilderCacheAlt.ReturnAndFree(sbColumnValues),
                                             strReturning.Length > 0 ? "RETURNING " + strReturning : "");

            return(sql);
        }
Exemple #18
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null,
                                                                     Func <FieldDefinition, bool> shouldInclude        = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if ((ShouldSkipInsert(fieldDef) && !fieldDef.AutoId) &&
                    shouldInclude?.Invoke(fieldDef) != true)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (SupportsSequences(fieldDef))
                    {
                        sbColumnValues.Append("NEXT VALUE FOR " + Sequence(NamingStrategy.GetSchemaName(modelDef), fieldDef.Sequence));
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName), fieldDef.CustomInsert));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            foreach (var fieldDef in modelDef.AutoIdFields) // need to include any AutoId fields that weren't included
            {
                if (fieldDefs.Contains(fieldDef))
                {
                    continue;
                }

                if (sbReturningColumns.Length > 0)
                {
                    sbReturningColumns.Append(",");
                }
                sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning    = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            cmd.CommandText = sbColumnNames.Length > 0
                ? $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) {strReturning}" +
                              $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})"
                : $"INSERT INTO {GetQuotedTableName(modelDef)}{strReturning} DEFAULT VALUES";
        }
Exemple #19
0
        public override string ToInsertRowStatement(IDbCommand cmd, object objWithProperties, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var tableType          = objWithProperties.GetType();
            var modelDef           = GetModel(tableType);

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef) && !fieldDef.AutoId)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
                    sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));

                    var p = AddParameter(cmd, fieldDef);
                    p.Value = GetFieldValue(fieldDef, fieldDef.GetValue(objWithProperties)) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in ToInsertRowStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            foreach (var fieldDef in modelDef.AutoIdFields) // need to include any AutoId fields that weren't included
            {
                if (fieldDefs.Contains(fieldDef))
                {
                    continue;
                }

                if (sbReturningColumns.Length > 0)
                {
                    sbReturningColumns.Append(",");
                }
                sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            var sql = sbColumnNames.Length > 0
                ? $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
                      strReturning +
                      $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})"
                : $"INSERT INTO {GetQuotedTableName(modelDef)} {strReturning} DEFAULT VALUES";

            return(sql);
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                var enumType = Type(type.Name, type.GenericArgs);
                RegisterType(type, enumType);

                var isIntEnum = type.IsEnumInt.GetValueOrDefault() || type.EnumNames.IsEmpty();
                if (!isIntEnum)
                {
                    sb.AppendLine($"enum {enumType}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    foreach (var name in type.EnumNames.Safe())
                    {
                        sb.AppendLine($"{name},");
                    }
                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
                else
                {
                    sb.AppendLine($"class {enumType}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    if (type.EnumNames != null)
                    {
                        for (var i = 0; i < type.EnumNames.Count; i++)
                        {
                            var name  = type.EnumNames[i];
                            var value = type.EnumValues?[i];

                            sb.AppendLine($"static const {enumType} {name} = const {enumType}._({value});");
                        }
                    }


                    sb.AppendLine();
                    sb.AppendLine("final int _value;");
                    sb.AppendLine($"const {enumType}._(this._value);");
                    sb.AppendLine($"int get value => _value;");

                    var enumNames = (type.EnumNames ?? TypeConstants.EmptyStringList).Join(",");
                    sb.AppendLine($"static List<{enumType}> get values => const [{enumNames}];");

                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InDeclarationType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                var implStr    = options.ImplementsFn?.Invoke();
                if (!string.IsNullOrEmpty(implStr))
                {
                    interfaces.Add(implStr);

                    if (implStr.StartsWith("IReturn<"))
                    {
                        var types      = implStr.RightPart('<');
                        var returnType = types.Substring(0, types.Length - 1);

                        if (returnType == "any")
                        {
                            returnType = "dynamic";
                        }

                        // This is to avoid invalid syntax such as "return new string()"
                        responseTypeExpression = defaultValues.TryGetValue(returnType, out var newReturnInstance)
                            ? $"createResponse() {{ return {newReturnInstance}; }}"
                            : $"createResponse() {{ return new {returnType}(); }}";
                    }
                    else if (implStr == "IReturnVoid")
                    {
                        responseTypeExpression = "createResponse() {}";
                    }
                }

                type.Implements.Each(x => interfaces.Add(Type(x)));

                var isClass         = type.IsInterface != true;
                var isAbstractClass = type.IsInterface == true || type.IsAbstract == true;
                var baseClass       = extends.Count > 0 ? extends[0] : null;
                var hasDtoBaseClass = baseClass != null;
                var hasListBase     = baseClass != null && baseClass.StartsWith("List<");
                if (hasListBase)
                {
                    baseClass       = "ListBase" + baseClass.Substring(4);
                    hasDtoBaseClass = false;
                }
                if (!isAbstractClass)
                {
                    interfaces.Add("IConvertible");
                }
                var extend = baseClass != null
                    ? " extends " + baseClass
                    : "";

                if (interfaces.Count > 0)
                {
                    if (isClass)
                    {
                        extend += " implements " + string.Join(", ", interfaces.ToArray());
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(extend))
                        {
                            extend = " extends ";
                        }
                        else
                        {
                            extend += ", ";
                        }

                        extend += string.Join(", ", interfaces.ToArray());
                    }
                }

                var typeDeclaration = !isAbstractClass ? "class" : "abstract class";

                var typeName = Type(type.Name, type.GenericArgs);

                RegisterType(type, typeName);

                sb.AppendLine($"{typeDeclaration} {typeName}{extend}");
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest && !isAbstractClass;
                if (addVersionInfo)
                {
                    sb.AppendLine($"int {"Version".PropertyStyle()};");
                }

                if (type.Name == "IReturn`1")
                {
                    sb.AppendLine("T createResponse();");
                    sb.AppendLine("String getTypeName();");
                }
                else if (type.Name == "IReturnVoid")
                {
                    sb.AppendLine("void createResponse();");
                    sb.AppendLine("String getTypeName();");
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (isClass)
                {
                    var typeNameWithoutGenericArgs = typeName.LeftPart('<');
                    var props = (type.Properties ?? TypeConstants <MetadataPropertyType> .EmptyList).ToList();

                    if (addVersionInfo)
                    {
                        props.Insert(0, new MetadataPropertyType {
                            Name          = "Version".PropertyStyle(),
                            Type          = "Int32",
                            TypeNamespace = "System",
                            IsValueType   = true,
                            Value         = Config.AddImplicitVersion.ToString()
                        });
                    }

                    if (props.Count > 0)
                    {
                        sb.AppendLine();
                    }

                    if (hasListBase)
                    {
                        var genericArg = baseClass.Substring(9, baseClass.Length - 10);
                        sb.AppendLine($"final List<{genericArg}> l = [];");
                        sb.AppendLine("void set length(int newLength) { l.length = newLength; }");
                        sb.AppendLine("int get length => l.length;");
                        sb.AppendLine($"{genericArg} operator [](int index) => l[index];");
                        sb.AppendLine($"void operator []=(int index, {genericArg} value) {{ l[index] = value; }}");
                    }

                    var sbBody = StringBuilderCacheAlt.Allocate();
                    if (props.Count > 0)
                    {
                        foreach (var prop in props)
                        {
                            if (sbBody.Length == 0)
                            {
                                sbBody.Append(typeNameWithoutGenericArgs + "({");
                            }
                            else
                            {
                                sbBody.Append(",");
                            }
                            sbBody.Append($"this.{prop.Name.PropertyStyle().PropertyName()}");
                            if (!string.IsNullOrEmpty(prop.Value))
                            {
                                sbBody.Append("=" + prop.Value);
                            }
                        }
                        if (sbBody.Length > 0)
                        {
                            sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody) + "});");
                        }
                    }
                    else
                    {
                        sb.AppendLine(typeNameWithoutGenericArgs + "();");
                    }

                    if (props.Count > 0)
                    {
                        sbBody = StringBuilderCacheAlt.Allocate();
                        sbBody.Append(typeNameWithoutGenericArgs + ".fromJson(Map<String, dynamic> json)");
                        sbBody.Append(" { fromMap(json); }");
                        sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));
                        sb.AppendLine();
                    }
                    else
                    {
                        sb.AppendLine(typeNameWithoutGenericArgs + ".fromJson(Map<String, dynamic> json) : " +
                                      (hasDtoBaseClass ? "super.fromJson(json);" : "super();"));
                    }

                    sbBody = StringBuilderCacheAlt.Allocate();
                    sbBody.AppendLine("fromMap(Map<String, dynamic> json) {");
                    if (hasDtoBaseClass)
                    {
                        sbBody.AppendLine("        super.fromMap(json);");
                    }
                    foreach (var prop in props)
                    {
                        var propType = DartPropertyType(prop);
                        var jsonName = prop.Name.PropertyStyle();
                        var propName = jsonName.PropertyName();
                        if (UseTypeConversion(prop))
                        {
                            bool registerType = true;
                            if (type.GenericArgs?.Length > 0 && prop.GenericArgs?.Length > 0)
                            {
                                var argIndexes = new List <int>();
                                foreach (var arg in prop.GenericArgs)
                                {
                                    var argIndex = Array.IndexOf(type.GenericArgs, arg);
                                    argIndexes.Add(argIndex);
                                }
                                if (argIndexes.All(x => x != -1))
                                {
                                    propType     = prop.Type.LeftPart('`') + "<${runtimeGenericTypeDefs(this,[" + argIndexes.Join(",") + "]).join(\",\")}>";
                                    registerType = false;
                                }
                            }

                            if (registerType)
                            {
                                RegisterPropertyType(prop, propType);
                            }

                            sbBody.AppendLine($"        {propName} = JsonConverters.fromJson(json['{jsonName}'],'{propType}',context);");
                        }
                        else
                        {
                            if (DartToJsonConverters.TryGetValue(propType, out var conversionFn))
                            {
                                sbBody.AppendLine($"        {propName} = JsonConverters.{conversionFn}(json['{jsonName}']);");
                            }
                            else
                            {
                                sbBody.AppendLine($"        {propName} = json['{jsonName}'];");
                            }
                        }
                    }
                    sbBody.AppendLine("        return this;");
                    sbBody.AppendLine("    }");
                    sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));

                    sbBody = StringBuilderCacheAlt.Allocate();
                    if (props.Count > 0)
                    {
                        foreach (var prop in props)
                        {
                            if (sbBody.Length == 0)
                            {
                                sbBody.Append("Map<String, dynamic> toJson() => ");
                                if (hasDtoBaseClass)
                                {
                                    sbBody.Append("super.toJson()..addAll(");
                                }

                                sbBody.AppendLine("{");
                            }
                            else
                            {
                                sbBody.AppendLine(",");
                            }

                            var propType = DartPropertyType(prop);
                            var jsonName = prop.Name.PropertyStyle();
                            var propName = jsonName.PropertyName();
                            if (UseTypeConversion(prop))
                            {
                                sbBody.Append($"        '{jsonName}': JsonConverters.toJson({propName},'{propType}',context)");
                            }
                            else
                            {
                                sbBody.Append($"        '{jsonName}': {propName}");
                            }
                        }
                        if (sbBody.Length > 0)
                        {
                            sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));
                            sb.AppendLine(hasDtoBaseClass ? "});" : "};");
                            sb.AppendLine();
                        }
                    }
                    else
                    {
                        sb.AppendLine("Map<String, dynamic> toJson() => " +
                                      (hasDtoBaseClass ? "super.toJson();" : "{};"));
                    }

                    if (responseTypeExpression != null)
                    {
                        sb.AppendLine(responseTypeExpression);
                        sb.AppendLine($"String getTypeName() {{ return \"{type.Name}\"; }}");
                    }

                    if (isClass)
                    {
                        sb.AppendLine("TypeContext context = _ctx;");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            PostTypeFilter?.Invoke(sb, type);

            return(lastNS);
        }
Exemple #21
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type,
                                  bool includeResponseStatus,
                                  bool addPropertyAccessors,
                                  string settersReturnType)
        {
            var wasAdded = false;

            var sbInner     = StringBuilderCacheAlt.Allocate();
            var sbAccessors = new StringBuilderWrapper(sbInner);

            if (addPropertyAccessors)
            {
                sbAccessors.AppendLine();
                sbAccessors = sbAccessors.Indent().Indent();
            }

            var dataMemberIndex = 1;

            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded)
                    {
                        sb.AppendLine();
                    }

                    var propType = Type(prop.GetTypeName(Config, allTypes), prop.GenericArgs);

                    var fieldName    = prop.Name.SafeToken().PropertyStyle();
                    var accessorName = fieldName.ToPascalCase();

                    wasAdded = AppendComments(sb, prop.Description);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                    if (!fieldName.IsKeyWord())
                    {
                        sb.AppendLine("public {0} {1} = null;".Fmt(propType, fieldName));
                    }
                    else
                    {
                        var originalName = fieldName;
                        fieldName = Char.ToUpper(fieldName[0]) + fieldName.SafeSubstring(1);
                        sb.AppendLine("@SerializedName(\"{0}\") public {1} {2} = null;".Fmt(originalName, propType, fieldName));
                    }

                    if (addPropertyAccessors)
                    {
                        sbAccessors.AppendPropertyAccessor(propType, fieldName, accessorName, settersReturnType);
                    }
                }
            }

            if (includeResponseStatus)
            {
                if (wasAdded)
                {
                    sb.AppendLine();
                }

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public ResponseStatus {0} = null;".Fmt(typeof(ResponseStatus).Name.PropertyStyle()));

                if (addPropertyAccessors)
                {
                    sbAccessors.AppendPropertyAccessor("ResponseStatus", "ResponseStatus", settersReturnType);
                }
            }

            if (sbAccessors.Length > 0)
            {
                sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbInner).TrimEnd()); //remove last \n
            }
        }
Exemple #22
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();
            cmd.CommandTimeout = OrmLiteConfig.CommandTimeout;

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (fieldDef.ReturnOnInsert || (fieldDef.IsPrimaryKey && fieldDef.AutoIncrement && HasInsertReturnValues(modelDef)))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append(GetQuotedColumnName(fieldDef.FieldName));
                }

                if (fieldDef.ShouldSkipInsert() && !fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (fieldDef.AutoIncrement || !string.IsNullOrEmpty(fieldDef.Sequence))
                    {
                        EnsureAutoIncrementSequence(modelDef, fieldDef);
                        sbColumnValues.Append("NEXT VALUE FOR " + fieldDef.Sequence);
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            cmd.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2}) {3}",
                                            GetQuotedTableName(modelDef),
                                            StringBuilderCache.ReturnAndFree(sbColumnNames),
                                            StringBuilderCacheAlt.ReturnAndFree(sbColumnValues),
                                            strReturning.Length > 0 ? "RETURNING " + strReturning : "");
        }
        public IRawString htmlList(TemplateScopeContext scope, object target, object scopeOptions)
        {
            if (target is IDictionary <string, object> single)
            {
                target = new[] { single }
            }
            ;

            var items        = target.AssertEnumerable(nameof(htmlList));
            var scopedParams = scope.AssertOptions(nameof(htmlList), scopeOptions);
            var depth        = scopedParams.TryGetValue("depth", out object oDepth) ? (int)oDepth : 0;
            var childDepth   = scopedParams.TryGetValue("childDepth", out object oChildDepth) ? oChildDepth.ConvertTo <int>() : 1;

            scopedParams["depth"] = depth + 1;

            try
            {
                scopedParams.TryGetValue("className", out object parentClass);
                scopedParams.TryGetValue("childClass", out object childClass);
                var className = ((depth < childDepth ? parentClass : childClass ?? parentClass)
                                 ?? Context.Args[TemplateConstants.DefaultTableClassName]).ToString();

                scopedParams.TryGetValue("headerStyle", out object oHeaderStyle);
                scopedParams.TryGetValue("headerTag", out object oHeaderTag);
                scopedParams.TryGetValue("captionIfEmpty", out object captionIfEmpty);
                var headerTag   = oHeaderTag as string ?? "th";
                var headerStyle = oHeaderStyle as string ?? "splitCase";

                var           sbHeader = StringBuilderCache.Allocate();
                var           sbRows   = StringBuilderCacheAlt.Allocate();
                List <string> keys     = null;

                foreach (var item in items)
                {
                    if (item is IDictionary <string, object> d)
                    {
                        if (keys == null)
                        {
                            keys = d.Keys.ToList();
                            sbHeader.Append("<tr>");
                            foreach (var key in keys)
                            {
                                sbHeader.Append('<').Append(headerTag).Append('>');
                                sbHeader.Append(Context.DefaultFilters?.textStyle(key, headerStyle)?.HtmlEncode());
                                sbHeader.Append("</").Append(headerTag).Append('>');
                            }
                            sbHeader.Append("</tr>");
                        }

                        sbRows.Append("<tr>");
                        foreach (var key in keys)
                        {
                            var value = d[key];
                            if (value == target)
                            {
                                break;                  // Prevent cyclical deps like 'it' binding
                            }
                            sbRows.Append("<td>");

                            if (!isComplexType(value))
                            {
                                sbRows.Append(GetScalarHtml(value));
                            }
                            else
                            {
                                var htmlValue = htmlDump(scope, value, scopeOptions);
                                sbRows.Append(htmlValue.ToRawString());
                            }

                            sbRows.Append("</td>");
                        }
                        sbRows.Append("</tr>");
                    }
                }

                var isEmpty = sbRows.Length == 0;
                if (isEmpty && captionIfEmpty == null)
                {
                    return(RawString.Empty);
                }

                var htmlHeaders = StringBuilderCache.ReturnAndFree(sbHeader);
                var htmlRows    = StringBuilderCacheAlt.ReturnAndFree(sbRows);

                var sb = StringBuilderCache.Allocate();
                sb.Append("<table");

                if (scopedParams.TryGetValue("id", out object id))
                {
                    sb.Append(" id=\"").Append(id).Append("\"");
                }
                if (!string.IsNullOrEmpty(className))
                {
                    sb.Append(" class=\"").Append(className).Append("\"");
                }

                sb.Append(">");

                scopedParams.TryGetValue("caption", out object caption);
                if (isEmpty)
                {
                    caption = captionIfEmpty;
                }

                if (caption != null && !scopedParams.TryGetValue("hasCaption", out _))
                {
                    sb.Append("<caption>").Append(caption.ToString().HtmlEncode()).Append("</caption>");
                    scopedParams["hasCaption"] = true;
                }

                if (htmlHeaders.Length > 0)
                {
                    sb.Append("<thead>").Append(htmlHeaders).Append("</thead>");
                }
                if (htmlRows.Length > 0)
                {
                    sb.Append("<tbody>").Append(htmlRows).Append("</tbody>");
                }

                sb.Append("</table>");

                var html = StringBuilderCache.ReturnAndFree(sb);
                return(html.ToRawString());
            }
            finally
            {
                scopedParams["depth"] = depth;
            }
        }
        public IRawString htmlDump(TemplateScopeContext scope, object target, object scopeOptions)
        {
            var scopedParams = scope.AssertOptions(nameof(htmlDump), scopeOptions);
            var depth        = scopedParams.TryGetValue("depth", out object oDepth) ? (int)oDepth : 0;
            var childDepth   = scopedParams.TryGetValue("childDepth", out object oChildDepth) ? oChildDepth.ConvertTo <int>() : 1;

            scopedParams["depth"] = depth + 1;

            try
            {
                if (!isComplexType(target))
                {
                    return(GetScalarHtml(target).ToRawString());
                }

                scopedParams.TryGetValue("captionIfEmpty", out object captionIfEmpty);
                scopedParams.TryGetValue("headerStyle", out object oHeaderStyle);
                scopedParams.TryGetValue("className", out object parentClass);
                scopedParams.TryGetValue("childClass", out object childClass);
                var headerStyle = oHeaderStyle as string ?? "splitCase";
                var className   = ((depth < childDepth ? parentClass : childClass ?? parentClass)
                                   ?? Context.Args[TemplateConstants.DefaultTableClassName]).ToString();

                if (target is IEnumerable e)
                {
                    var objs = e.Map(x => x);

                    var isEmpty = objs.Count == 0;
                    if (isEmpty && captionIfEmpty == null)
                    {
                        return(RawString.Empty);
                    }

                    var first = !isEmpty ? objs[0] : null;
                    if (first is IDictionary)
                    {
                        return(htmlList(scope, target, scopeOptions));
                    }

                    var sb = StringBuilderCacheAlt.Allocate();

                    sb.Append("<table");

                    if (scopedParams.TryGetValue("id", out object id))
                    {
                        sb.Append(" id=\"").Append(id).Append("\"");
                    }

                    sb.Append(" class=\"").Append(className).Append("\"");

                    sb.Append(">");

                    scopedParams.TryGetValue("caption", out object caption);
                    if (isEmpty)
                    {
                        caption = captionIfEmpty;
                    }

                    if (caption != null && !scopedParams.TryGetValue("hasCaption", out _))
                    {
                        sb.Append("<caption>").Append(caption.ToString().HtmlEncode()).Append("</caption>");
                        scopedParams["hasCaption"] = true;
                    }

                    if (!isEmpty)
                    {
                        sb.Append("<tbody>");

                        if (first is KeyValuePair <string, object> )
                        {
                            foreach (var o in objs)
                            {
                                if (o is KeyValuePair <string, object> kvp)
                                {
                                    if (kvp.Value == target)
                                    {
                                        break;                      // Prevent cyclical deps like 'it' binding
                                    }
                                    sb.Append("<tr>");
                                    sb.Append("<th>");
                                    sb.Append(Context.DefaultFilters?.textStyle(kvp.Key, headerStyle)?.HtmlEncode());
                                    sb.Append("</th>");
                                    sb.Append("<td>");
                                    if (!isComplexType(kvp.Value))
                                    {
                                        sb.Append(GetScalarHtml(kvp.Value));
                                    }
                                    else
                                    {
                                        var body = htmlDump(scope, kvp.Value, scopeOptions);
                                        sb.Append(body.ToRawString());
                                    }
                                    sb.Append("</td>");
                                    sb.Append("</tr>");
                                }
                            }
                        }
                        else if (!isComplexType(first))
                        {
                            foreach (var o in objs)
                            {
                                sb.Append("<tr>");
                                sb.Append("<td>");
                                sb.Append(GetScalarHtml(o));
                                sb.Append("</td>");
                                sb.Append("</tr>");
                            }
                        }
                        else
                        {
                            if (objs.Count > 1)
                            {
                                var rows = objs.Map(x => x.ToObjectDictionary());
                                sb.Append("<tr>");
                                sb.Append("<td>");
                                var list = htmlList(scope, rows, scopeOptions);
                                sb.Append(list.ToRawString());
                                sb.Append("</td>");
                                sb.Append("</tr>");
                            }
                            else
                            {
                                foreach (var o in objs)
                                {
                                    sb.Append("<tr>");

                                    if (!isComplexType(o))
                                    {
                                        sb.Append("<td>");
                                        sb.Append(GetScalarHtml(o));
                                        sb.Append("</td>");
                                    }
                                    else
                                    {
                                        sb.Append("<td>");
                                        var body = htmlDump(scope, o, scopeOptions);
                                        sb.Append(body.ToRawString());
                                        sb.Append("</td>");
                                    }

                                    sb.Append("</tr>");
                                }
                            }
                        }

                        sb.Append("</tbody>");
                    }

                    sb.Append("</table>");

                    var html = StringBuilderCacheAlt.ReturnAndFree(sb);
                    return(html.ToRawString());
                }

                return(htmlDump(scope, target.ToObjectDictionary(), scopeOptions));
            }
            finally
            {
                scopedParams["depth"] = depth;
            }
        }
Exemple #25
0
        public override string ToExistStatement(Type fromTableType,
                                                object objWithProperties,
                                                string sqlFilter,
                                                params object[] filterParams)
        {
            var fromModelDef = GetModel(fromTableType);
            var sql          = StringBuilderCache.Allocate();

            sql.AppendFormat("SELECT 1 \nFROM {0}", GetQuotedTableName(fromModelDef));

            var filter    = StringBuilderCacheAlt.Allocate();
            var hasFilter = false;

            if (objWithProperties != null)
            {
                var tableType = objWithProperties.GetType();

                if (fromTableType != tableType)
                {
                    int i        = 0;
                    var fpk      = new List <FieldDefinition>();
                    var modelDef = GetModel(tableType);

                    foreach (var def in modelDef.FieldDefinitions)
                    {
                        if (def.IsPrimaryKey)
                        {
                            fpk.Add(def);
                        }
                    }

                    foreach (var fieldDef in fromModelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed)
                        {
                            continue;
                        }

                        if (fieldDef.ForeignKey != null &&
                            GetModel(fieldDef.ForeignKey.ReferenceType).ModelName == modelDef.ModelName)
                        {
                            if (filter.Length > 0)
                            {
                                filter.Append(" AND ");
                            }

                            filter.AppendFormat("{0} = {1}", GetQuotedColumnName(fieldDef.FieldName),
                                                fpk[i].GetQuotedValue(objWithProperties));
                            i++;
                        }
                    }
                }
                else
                {
                    var modelDef = GetModel(tableType);
                    foreach (var fieldDef in modelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed)
                        {
                            continue;
                        }

                        if (fieldDef.IsPrimaryKey)
                        {
                            if (filter.Length > 0)
                            {
                                filter.Append(" AND ");
                            }
                            filter.AppendFormat("{0} = {1}",
                                                GetQuotedColumnName(fieldDef.FieldName),
                                                fieldDef.GetQuotedValue(objWithProperties));
                        }
                    }
                }

                hasFilter = filter.Length > 0;
                if (hasFilter)
                {
                    sql.AppendFormat("\nWHERE {0} ", StringBuilderCacheAlt.ReturnAndFree(filter));
                }
            }

            if (!string.IsNullOrEmpty(sqlFilter))
            {
                sqlFilter = sqlFilter.SqlFmt(filterParams);
                if (!sqlFilter.StartsWith("\nORDER ", StringComparison.OrdinalIgnoreCase) &&
                    !sqlFilter.StartsWith("\nROWS ", StringComparison.OrdinalIgnoreCase))    // ROWS <m> [TO <n>])
                {
                    sql.Append(hasFilter ? " AND  " : "\nWHERE ");
                }
                sql.Append(sqlFilter);
            }

            var sb = StringBuilderCacheAlt.Allocate()
                     .Append("select 1 from RDB$DATABASE where")
                     .AppendFormat(" exists ({0})", StringBuilderCache.ReturnAndFree(sql));

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
Exemple #26
0
        public static string TextDump(object target, TextDumpOptions options)
        {
            if (options == null)
            {
                options = new TextDumpOptions();
            }

            var depth = options.Depth;

            options.Depth += 1;

            try
            {
                if (!isComplexType(target))
                {
                    return(GetScalarText(target, options.Defaults));
                }

                var headerStyle = options.HeaderStyle;

                if (target is IEnumerable e)
                {
                    var objs = e.Map(x => x);

                    var isEmpty = objs.Count == 0;
                    if (isEmpty)
                    {
                        return(options.CaptionIfEmpty ?? string.Empty);
                    }

                    var first = objs[0];
                    if (first is IDictionary && objs.Count > 1)
                    {
                        return(TextList(objs, options));
                    }

                    var sb = StringBuilderCacheAlt.Allocate();

                    string writeCaption = null;
                    var    caption      = options.Caption;
                    if (caption != null && !options.HasCaption)
                    {
                        writeCaption       = caption;
                        options.HasCaption = true;
                    }

                    if (!isEmpty)
                    {
                        var keys   = new List <string>();
                        var values = new List <string>();

                        string TextKvps(StringBuilder s, IEnumerable <KeyValuePair <string, object> > kvps)
                        {
                            foreach (var kvp in kvps)
                            {
                                if (kvp.Value == target)
                                {
                                    break; // Prevent cyclical deps like 'it' binding
                                }
                                keys.Add(ViewUtils.StyleText(kvp.Key, headerStyle) ?? "");

                                var field = !isComplexType(kvp.Value)
                                    ? GetScalarText(kvp.Value, options.Defaults)
                                    : TextDump(kvp.Value, options);

                                values.Add(field);
                            }

                            var keySize    = keys.Max(x => x.Length);
                            var valuesSize = values.Max(x => x.Length);

                            s.AppendLine(writeCaption != null
                                ? $"| {writeCaption.PadRight(keySize + valuesSize + 2, ' ')} ||"
                                : $"|||");
                            s.AppendLine(writeCaption != null
                                ? $"|-{"".PadRight(keySize, '-')}-|-{"".PadRight(valuesSize, '-')}-|"
                                : "|-|-|");

                            for (var i = 0; i < keys.Count; i++)
                            {
                                s.Append("| ")
                                .Append(keys[i].PadRight(keySize, ' '))
                                .Append(" | ")
                                .Append(values[i].PadRight(valuesSize, ' '))
                                .Append(" |")
                                .AppendLine();
                            }

                            return(StringBuilderCache.ReturnAndFree(s));
                        }

                        if (first is KeyValuePair <string, object> )
                        {
                            return(TextKvps(sb, objs.Cast <KeyValuePair <string, object> >()));
                        }
                        else
                        {
                            if (!isComplexType(first))
                            {
                                foreach (var o in objs)
                                {
                                    values.Add(GetScalarText(o, options.Defaults));
                                }

                                var valuesSize = values.Max(MaxLineLength);
                                if (writeCaption?.Length > valuesSize)
                                {
                                    valuesSize = writeCaption.Length;
                                }

                                sb.AppendLine(writeCaption != null
                                    ? $"| {writeCaption.PadRight(valuesSize)} |"
                                    : $"||");
                                sb.AppendLine(writeCaption != null
                                    ? $"|-{"".PadRight(valuesSize,'-')}-|"
                                    : "|-|");

                                foreach (var value in values)
                                {
                                    sb.Append("| ")
                                    .Append(value.PadRight(valuesSize, ' '))
                                    .Append(" |")
                                    .AppendLine();
                                }
                            }
                            else
                            {
                                if (objs.Count > 1)
                                {
                                    if (writeCaption != null)
                                    {
                                        sb.AppendLine(writeCaption)
                                        .AppendLine();
                                    }

                                    var rows = objs.Map(x => x.ToObjectDictionary());
                                    var list = TextList(rows, options);
                                    sb.AppendLine(list);
                                    return(StringBuilderCache.ReturnAndFree(sb));
                                }
                                else
                                {
                                    foreach (var o in objs)
                                    {
                                        if (!isComplexType(o))
                                        {
                                            values.Add(GetScalarText(o, options.Defaults));
                                        }
                                        else
                                        {
                                            var body = TextDump(o, options);
                                            values.Add(body);
                                        }
                                    }

                                    var valuesSize = values.Max(MaxLineLength);
                                    if (writeCaption?.Length > valuesSize)
                                    {
                                        valuesSize = writeCaption.Length;
                                    }

                                    sb.AppendLine(writeCaption != null
                                        ? $"| {writeCaption.PadRight(valuesSize, ' ')} |"
                                        : $"||");
                                    sb.AppendLine(writeCaption != null ? $"|-{"".PadRight(valuesSize,'-')}-|" : "|-|");

                                    foreach (var value in values)
                                    {
                                        sb.Append("| ")
                                        .Append(value.PadRight(valuesSize, ' '))
                                        .Append(" |")
                                        .AppendLine();
                                    }
                                }
                            }
                        }
                    }

                    return(StringBuilderCache.ReturnAndFree(sb));
                }

                return(TextDump(target.ToObjectDictionary(), options));
            }
            finally
            {
                options.Depth = depth;
            }
        }
Exemple #27
0
    /// <summary>
    /// Run a Process asynchronously, returning  entire captured process output, whilst streaming stdOut, stdErr callbacks
    /// </summary>
    /// <param name="startInfo">The start information.</param>
    /// <param name="timeoutMs">The timeout ms.</param>
    /// <param name="onOut">The on out.</param>
    /// <param name="onError">The on error.</param>
    /// <returns>A Task&lt;ProcessResult&gt; representing the asynchronous operation.</returns>
    public static async Task <ProcessResult> RunAsync(ProcessStartInfo startInfo, int?timeoutMs = null,
                                                      Action <string> onOut = null, Action <string> onError = null)
    {
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError  = true;

        using var process = new Process
              {
                  StartInfo           = startInfo,
                  EnableRaisingEvents = true,
              };

        // List of tasks to wait for a whole process exit
        var processTasks = new List <Task>();

        // === EXITED Event handling ===
        var processExitEvent = new TaskCompletionSource <object>();

        process.Exited += (sender, args) =>
        {
            processExitEvent.TrySetResult(true);
        };
        processTasks.Add(processExitEvent.Task);

        long callbackTicks = 0;

        // === STDOUT handling ===
        var stdOutBuilder    = StringBuilderCache.Allocate();
        var stdOutCloseEvent = new TaskCompletionSource <bool>();

        process.OutputDataReceived += (s, e) =>
        {
            if (e.Data == null)
            {
                stdOutCloseEvent.TrySetResult(true);
            }
            else
            {
                stdOutBuilder.AppendLine(e.Data);
                if (onOut != null)
                {
                    var swCallback = Stopwatch.StartNew();
                    onOut(e.Data);
                    callbackTicks += swCallback.ElapsedTicks;
                }
            }
        };

        processTasks.Add(stdOutCloseEvent.Task);

        // === STDERR handling ===
        var stdErrBuilder    = StringBuilderCacheAlt.Allocate();
        var stdErrCloseEvent = new TaskCompletionSource <bool>();

        process.ErrorDataReceived += (s, e) =>
        {
            if (e.Data == null)
            {
                stdErrCloseEvent.TrySetResult(true);
            }
            else
            {
                stdErrBuilder.AppendLine(e.Data);
                if (onError != null)
                {
                    var swCallback = Stopwatch.StartNew();
                    onError(e.Data);
                    callbackTicks += swCallback.ElapsedTicks;
                }
            }
        };

        processTasks.Add(stdErrCloseEvent.Task);

        // === START OF PROCESS ===
        var sw     = Stopwatch.StartNew();
        var result = new ProcessResult
        {
            StartAt = DateTime.UtcNow,
        };

        if (!process.Start())
        {
            result.ExitCode = process.ExitCode;
            return(result);
        }

        // Reads the output stream first as needed and then waits because deadlocks are possible
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        // === ASYNC WAIT OF PROCESS ===

        // Process completion = exit AND stdout (if defined) AND stderr (if defined)
        var processCompletionTask = Task.WhenAll(processTasks);

        // Task to wait for exit OR timeout (if defined)
        var awaitingTask = timeoutMs.HasValue
                               ? Task.WhenAny(Task.Delay(timeoutMs.Value), processCompletionTask)
                               : Task.WhenAny(processCompletionTask);

        // Let's now wait for something to end...
        if (await awaitingTask.ConfigureAwait(false) == processCompletionTask)
        {
            // -> Process exited cleanly
            result.ExitCode = process.ExitCode;
        }
        else
        {
            // -> Timeout, let's kill the process
            try
            {
                process.Kill();
            }
            catch
            {
                // ignored
            }
        }

        // Read stdout/stderr
        result.EndAt = DateTime.UtcNow;
        if (callbackTicks > 0)
        {
            var callbackMs = callbackTicks / Stopwatch.Frequency * 1000;
            result.CallbackDurationMs = callbackMs;
            result.DurationMs         = sw.ElapsedMilliseconds - callbackMs;
        }
        else
        {
            result.DurationMs = sw.ElapsedMilliseconds;
        }
        result.StdOut = StringBuilderCache.ReturnAndFree(stdOutBuilder);
        result.StdErr = StringBuilderCacheAlt.ReturnAndFree(stdErrBuilder);

        return(result);
    }
Exemple #28
0
        internal string MakeID(string str, int start, int len)
        {
            // Parse the string into a list of tokens
            Tokenize(str, start, len);

            var sb = StringBuilderCacheAlt.Allocate();

            foreach (var t in m_Tokens)
            {
                switch (t.type)
                {
                case TokenType.Text:
                    sb.Append(str, t.startOffset, t.length);
                    break;

                case TokenType.link:
                    LinkInfo li = (LinkInfo)t.data;
                    sb.Append(li.link_text);
                    break;
                }

                FreeToken(t);
            }

            // Now clean it using the same rules as pandoc
            base.Reset(sb.ToString());

            // Skip everything up to the first letter
            while (!eof)
            {
                if (Char.IsLetter(current))
                {
                    break;
                }
                SkipForward(1);
            }

            // Process all characters
            sb.Length = 0;
            while (!eof)
            {
                char ch = current;
                if (char.IsLetterOrDigit(ch) || ch == '_' || ch == '-' || ch == '.')
                {
                    sb.Append(Char.ToLower(ch));
                }
                else if (ch == ' ')
                {
                    sb.Append("-");
                }
                else if (IsLineEnd(ch))
                {
                    sb.Append("-");
                    SkipEol();
                    continue;
                }

                SkipForward(1);
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
Exemple #29
0
        public override string ToCreateTableStatement(Type tableType)
        {
            var sbColumns      = StringBuilderCache.Allocate();
            var sbConstraints  = StringBuilderCacheAlt.Allocate();
            var sbTableOptions = StringBuilderCacheAlt.Allocate();

            var fileTableAttrib = tableType.FirstAttribute <SqlServerFileTableAttribute>();

            var modelDef = GetModel(tableType);

            if (fileTableAttrib == null)
            {
                foreach (var fieldDef in modelDef.FieldDefinitions)
                {
                    if (fieldDef.CustomSelect != null)
                    {
                        continue;
                    }

                    var columnDefinition = GetColumnDefinition(fieldDef);

                    if (columnDefinition == null)
                    {
                        continue;
                    }

                    if (sbColumns.Length != 0)
                    {
                        sbColumns.Append(", \n  ");
                    }

                    sbColumns.Append(columnDefinition);

                    if (fieldDef.ForeignKey == null || OrmLiteConfig.SkipForeignKeys)
                    {
                        continue;
                    }

                    var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);
                    sbConstraints.Append(
                        $", \n\n  CONSTRAINT {GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef))} " +
                        $"FOREIGN KEY ({GetQuotedColumnName(fieldDef.FieldName)}) " +
                        $"REFERENCES {GetQuotedTableName(refModelDef)} ({GetQuotedColumnName(refModelDef.PrimaryKey.FieldName)})");

                    sbConstraints.Append(GetForeignKeyOnDeleteClause(fieldDef.ForeignKey));
                    sbConstraints.Append(GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
                }
            }
            else
            {
                if (fileTableAttrib.FileTableDirectory != null || fileTableAttrib.FileTableCollateFileName != null)
                {
                    sbTableOptions.Append(" WITH (");

                    if (fileTableAttrib.FileTableDirectory != null)
                    {
                        sbTableOptions.Append($" FILETABLE_DIRECTORY = N'{fileTableAttrib.FileTableDirectory}'\n");
                    }

                    if (fileTableAttrib.FileTableCollateFileName != null)
                    {
                        if (fileTableAttrib.FileTableDirectory != null)
                        {
                            sbTableOptions.Append(" ,");
                        }

                        sbTableOptions.Append($" FILETABLE_COLLATE_FILENAME = {fileTableAttrib.FileTableCollateFileName ?? "database_default" }\n");
                    }
                    sbTableOptions.Append(")");
                }
            }

            var sql = $"CREATE TABLE {GetQuotedTableName(modelDef)} ";

            sql += (fileTableAttrib != null)
                ? $"\n AS FILETABLE{StringBuilderCache.ReturnAndFree(sbTableOptions)};"
                : $"\n(\n  {StringBuilderCache.ReturnAndFree(sbColumns)}{StringBuilderCacheAlt.ReturnAndFree(sbConstraints)} \n){StringBuilderCache.ReturnAndFree(sbTableOptions)}; \n";

            return(sql);
        }
        public override string ToExistStatement(Type fromTableType, object objWithProperties, string sqlFilter, params object[] filterParams)
        {
            var fromModelDef = GetModel(fromTableType);

            var sql = StringBuilderCache.Allocate();

            sql.AppendFormat("SELECT 1 \nFROM {0}", this.GetQuotedTableName(fromModelDef));

            var filter    = StringBuilderCacheAlt.Allocate();
            var hasFilter = false;

            if (objWithProperties != null)
            {
                var tableType = objWithProperties.GetType();

                if (fromTableType != tableType)
                {
                    int i        = 0;
                    var fpk      = new List <FieldDefinition>();
                    var modelDef = GetModel(tableType);

                    foreach (var def in modelDef.FieldDefinitions)
                    {
                        if (def.IsPrimaryKey)
                        {
                            fpk.Add(def);
                        }
                    }

                    foreach (var fieldDef in fromModelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed || fieldDef.ForeignKey == null)
                        {
                            continue;
                        }

                        var model = GetModel(fieldDef.ForeignKey.ReferenceType);
                        if (model.ModelName != modelDef.ModelName)
                        {
                            continue;
                        }

                        if (filter.Length > 0)
                        {
                            filter.Append(" AND ");
                        }

                        filter.AppendFormat("{0} = {1}", GetQuotedColumnName(fieldDef.FieldName), fpk[i++].GetQuotedValue(objWithProperties));
                    }
                }
                else
                {
                    var modelDef = GetModel(tableType);
                    foreach (var fieldDef in modelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed || !fieldDef.IsPrimaryKey)
                        {
                            continue;
                        }

                        if (filter.Length > 0)
                        {
                            filter.Append(" AND ");
                        }

                        filter.AppendFormat("{0} = {1}",
                                            GetQuotedColumnName(fieldDef.FieldName), fieldDef.GetQuotedValue(objWithProperties));
                    }
                }

                hasFilter = filter.Length > 0;
                if (hasFilter)
                {
                    sql.AppendFormat("\nWHERE {0} ", StringBuilderCacheAlt.ReturnAndFree(filter));
                }
            }

            if (!string.IsNullOrEmpty(sqlFilter))
            {
                sqlFilter = sqlFilter.SqlFmt(filterParams);
                sql.Append(hasFilter ? " AND  " : "\nWHERE ");
                sql.Append(sqlFilter);
            }

            return(string.Format("SELECT EXISTS({0});", StringBuilderCache.ReturnAndFree(sql)));
        }