<commit_before>﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Efrpg.Filtering;
using Efrpg.Readers;

namespace Efrpg
{
    public class StoredProcedure : EntityName
    {
        public Schema Schema;
        public List<StoredProcedureParameter> Parameters;
        public List<List<DataColumn>> ReturnModels; // A list of return models, containing a list of return columns
        public bool IsTableValuedFunction;
        public bool IsScalarValuedFunction;
        public bool IsStoredProcedure;
        public bool HasSpatialParameter;
        public bool HasSpatialReturnModel;

        public StoredProcedure()
        {
            Parameters = new List<StoredProcedureParameter>();
            ReturnModels = new List<List<DataColumn>>();
        }

        public static bool IsNullable(DataColumn col)
        {
            return col.DataType.Namespace != null &&
                   col.AllowDBNull &&
                   !(
                       Column.NotNullable.Contains(col.DataType.Name.ToLower()) ||
                       Column.NotNullable.Contains(col.DataType.Namespace.ToLower() + "." + col.DataType.Name.ToLower())
                     );
        }

        public static string WrapTypeIfNullable(string propertyType, DataColumn col)
        {
            return !IsNullable(col) ? propertyType : string.Format(Settings.NullableShortHand ? "{0}?" : "Nullable<{0}>", propertyType);
        }

        public string WriteStoredProcFunctionName(IDbContextFilter filter)
        {
            var name = filter.StoredProcedureRename(this);
            return !string.IsNullOrEmpty(name) ? name : NameHumanCase;
        }

        public bool StoredProcHasOutParams()
        {
            return Parameters.Any(x => x.Mode != StoredProcedureParameterMode.In);
        }

        public string WriteStoredProcFunctionParams(bool includeProcResult)
        {
            var sb = new StringBuilder(255);
            var n = 1;
            var data = Parameters.Where(x => x.Mode != StoredProcedureParameterMode.Out).OrderBy(x => x.Ordinal).ToList();
            var count = data.Count;
            foreach (var p in data)
            {
                sb.AppendFormat("{0}{1}{2} {3}{4}",
                    p.Mode == StoredProcedureParameterMode.In ? string.Empty : "out ",
                    p.PropertyType,
                    Column.NotNullable.Contains(p.PropertyType.ToLower()) ? string.Empty : "?",
                    p.NameHumanCase,
                    n++ < count ? ", " : string.Empty);
            }

            if (includeProcResult && ReturnModels.Count > 0 && ReturnModels.First().Count > 0)
                sb.AppendFormat((data.Count > 0 ? ", " : string.Empty) + "out int procResult");

            return sb.ToString();
        }

        public string WriteStoredProcFunctionOverloadCall()
        {
            var sb = new StringBuilder(255);
            foreach (var p in Parameters.OrderBy(x => x.Ordinal))
            {
                sb.AppendFormat("{0}{1}, ",
                    p.Mode == StoredProcedureParameterMode.In ? string.Empty : "out ",
                    p.NameHumanCase);
            }

            sb.Append("out procResult");
            return sb.ToString();
        }

        public string WriteStoredProcFunctionSqlAtParams()
        {
            var sb = new StringBuilder(255);
            var n = 1;
            var count = Parameters.Count;
            foreach (var p in Parameters.OrderBy(x => x.Ordinal))
            {
                sb.AppendFormat("{0}{1}{2}",
                    p.Name,
                    p.Mode == StoredProcedureParameterMode.In ? string.Empty : " OUTPUT",
                    n++ < count ? ", " : string.Empty);
            }

            return sb.ToString();
        }

        public string WriteNetCoreTableValuedFunctionsSqlAtParams()
        {
            var sb = new StringBuilder(255);
            var count = Parameters.Count;
            for(var n = 0; n < count; n++)
            {
                sb.AppendFormat("{{{0}}}{1}",
                    n,
                    (n + 1) < count ? ", " : string.Empty);
            }

            return sb.ToString();
        }

        public string WriteStoredProcSqlParameterName(StoredProcedureParameter p)
        {
            return p.NameHumanCase + "Param";
        }

        public string WriteStoredProcFunctionDeclareSqlParameter(bool includeProcResult)
        {
            var sb = new StringBuilder(1024);
            foreach (var p in Parameters.OrderBy(x => x.Ordinal))
            {
                var isNullable = !Column.NotNullable.Contains(p.PropertyType.ToLower());
                var getValueOrDefault = isNullable ? ".GetValueOrDefault()" : string.Empty;
                var isGeography = p.PropertyType == "DbGeography";

                sb.AppendLine(
                    string.Format("        var {0} = new SqlParameter", WriteStoredProcSqlParameterName(p))
                    + string.Format(" {{ ParameterName = \"{0}\", ", p.Name)
                    + (isGeography ? "UdtTypeName = \"geography\"" : string.Format("SqlDbType = SqlDbType.{0}", p.SqlDbType))
                    + ", Direction = ParameterDirection."
                    + (p.Mode == StoredProcedureParameterMode.In ? "Input" : "Output")
                    + (p.Mode == StoredProcedureParameterMode.In
                        ? ", Value = " + (isGeography
                            ? string.Format("SqlGeography.Parse({0}.AsText())", p.NameHumanCase)
                              : p.NameHumanCase + getValueOrDefault)
                        : string.Empty)
                    + (p.MaxLength != 0 ? ", Size = " + p.MaxLength : string.Empty)
                    + ((p.Precision > 0 || p.Scale > 0) ? ", Precision = " + p.Precision + ", Scale = " + p.Scale : string.Empty)
                    + (p.PropertyType.ToLower().Contains("datatable") ? ", TypeName = \"" + p.UserDefinedTypeName + "\"" : string.Empty)
                    + " };");

                if (p.Mode == StoredProcedureParameterMode.In)
                {
                    sb.AppendFormat(
                        isNullable
                            ? "        if (!{0}.HasValue){1}            {0}Param.Value = DBNull.Value;{1}{1}"
                            : "        if ({0}Param.Value == null){1}            {0}Param.Value = DBNull.Value;{1}{1}",
                        p.NameHumanCase, Environment.NewLine);
                }
            }
<commit_msg>Use full namespace for SqlGeography.Parse<commit_after>﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Efrpg.Filtering;
using Efrpg.Readers;

namespace Efrpg
{
    public class StoredProcedure : EntityName
    {
        public Schema Schema;
        public List<StoredProcedureParameter> Parameters;
        public List<List<DataColumn>> ReturnModels; // A list of return models, containing a list of return columns
        public bool IsTableValuedFunction;
        public bool IsScalarValuedFunction;
        public bool IsStoredProcedure;
        public bool HasSpatialParameter;
        public bool HasSpatialReturnModel;

        public StoredProcedure()
        {
            Parameters = new List<StoredProcedureParameter>();
            ReturnModels = new List<List<DataColumn>>();
        }

        public static bool IsNullable(DataColumn col)
        {
            return col.DataType.Namespace != null &&
                   col.AllowDBNull &&
                   !(
                       Column.NotNullable.Contains(col.DataType.Name.ToLower()) ||
                       Column.NotNullable.Contains(col.DataType.Namespace.ToLower() + "." + col.DataType.Name.ToLower())
                     );
        }

        public static string WrapTypeIfNullable(string propertyType, DataColumn col)
        {
            return !IsNullable(col) ? propertyType : string.Format(Settings.NullableShortHand ? "{0}?" : "Nullable<{0}>", propertyType);
        }

        public string WriteStoredProcFunctionName(IDbContextFilter filter)
        {
            var name = filter.StoredProcedureRename(this);
            return !string.IsNullOrEmpty(name) ? name : NameHumanCase;
        }

        public bool StoredProcHasOutParams()
        {
            return Parameters.Any(x => x.Mode != StoredProcedureParameterMode.In);
        }

        public string WriteStoredProcFunctionParams(bool includeProcResult)
        {
            var sb = new StringBuilder(255);
            var n = 1;
            var data = Parameters.Where(x => x.Mode != StoredProcedureParameterMode.Out).OrderBy(x => x.Ordinal).ToList();
            var count = data.Count;
            foreach (var p in data)
            {
                sb.AppendFormat("{0}{1}{2} {3}{4}",
                    p.Mode == StoredProcedureParameterMode.In ? string.Empty : "out ",
                    p.PropertyType,
                    Column.NotNullable.Contains(p.PropertyType.ToLower()) ? string.Empty : "?",
                    p.NameHumanCase,
                    n++ < count ? ", " : string.Empty);
            }

            if (includeProcResult && ReturnModels.Count > 0 && ReturnModels.First().Count > 0)
                sb.AppendFormat((data.Count > 0 ? ", " : string.Empty) + "out int procResult");

            return sb.ToString();
        }

        public string WriteStoredProcFunctionOverloadCall()
        {
            var sb = new StringBuilder(255);
            foreach (var p in Parameters.OrderBy(x => x.Ordinal))
            {
                sb.AppendFormat("{0}{1}, ",
                    p.Mode == StoredProcedureParameterMode.In ? string.Empty : "out ",
                    p.NameHumanCase);
            }

            sb.Append("out procResult");
            return sb.ToString();
        }

        public string WriteStoredProcFunctionSqlAtParams()
        {
            var sb = new StringBuilder(255);
            var n = 1;
            var count = Parameters.Count;
            foreach (var p in Parameters.OrderBy(x => x.Ordinal))
            {
                sb.AppendFormat("{0}{1}{2}",
                    p.Name,
                    p.Mode == StoredProcedureParameterMode.In ? string.Empty : " OUTPUT",
                    n++ < count ? ", " : string.Empty);
            }

            return sb.ToString();
        }

        public string WriteNetCoreTableValuedFunctionsSqlAtParams()
        {
            var sb = new StringBuilder(255);
            var count = Parameters.Count;
            for(var n = 0; n < count; n++)
            {
                sb.AppendFormat("{{{0}}}{1}",
                    n,
                    (n + 1) < count ? ", " : string.Empty);
            }

            return sb.ToString();
        }

        public string WriteStoredProcSqlParameterName(StoredProcedureParameter p)
        {
            return p.NameHumanCase + "Param";
        }

        public string WriteStoredProcFunctionDeclareSqlParameter(bool includeProcResult)
        {
            var sb = new StringBuilder(1024);
            foreach (var p in Parameters.OrderBy(x => x.Ordinal))
            {
                var isNullable = !Column.NotNullable.Contains(p.PropertyType.ToLower());
                var getValueOrDefault = isNullable ? ".GetValueOrDefault()" : string.Empty;
                var isGeography = p.PropertyType == "DbGeography";

                sb.AppendLine(
                    string.Format("        var {0} = new SqlParameter", WriteStoredProcSqlParameterName(p))
                    + string.Format(" {{ ParameterName = \"{0}\", ", p.Name)
                    + (isGeography ? "UdtTypeName = \"geography\"" : string.Format("SqlDbType = SqlDbType.{0}", p.SqlDbType))
                    + ", Direction = ParameterDirection."
                    + (p.Mode == StoredProcedureParameterMode.In ? "Input" : "Output")
                    + (p.Mode == StoredProcedureParameterMode.In
                        ? ", Value = " + (isGeography
                            ? string.Format("Microsoft.SqlServer.Types.SqlGeography.Parse({0}.AsText())", p.NameHumanCase)
                              : p.NameHumanCase + getValueOrDefault)
                        : string.Empty)
                    + (p.MaxLength != 0 ? ", Size = " + p.MaxLength : string.Empty)
                    + ((p.Precision > 0 || p.Scale > 0) ? ", Precision = " + p.Precision + ", Scale = " + p.Scale : string.Empty)
                    + (p.PropertyType.ToLower().Contains("datatable") ? ", TypeName = \"" + p.UserDefinedTypeName + "\"" : string.Empty)
                    + " };");

                if (p.Mode == StoredProcedureParameterMode.In)
                {
                    sb.AppendFormat(
                        isNullable
                            ? "        if (!{0}.HasValue){1}            {0}Param.Value = DBNull.Value;{1}{1}"
                            : "        if ({0}Param.Value == null){1}            {0}Param.Value = DBNull.Value;{1}{1}",
                        p.NameHumanCase, Environment.NewLine);
                }
            }

{'fraction_non_alphanumeric': 0.11418159732766474, 'fraction_numerical': 0.008199210446401458, 'mean_word_length': 1.6214925373134328, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4304412', 'n_tokens_mistral': 3530, 'n_tokens_neox': 3336, 'n_words': 674}