Esempio n. 1
0
        protected override async Task HandleMessage(PgTransaction transaction, MessageBuilder messageBuilder, PipeWriter writer, CancellationToken token)
        {
            if (!string.IsNullOrEmpty(StatementName))
            {
                throw new PgErrorException(PgErrorCodes.FeatureNotSupported, "Named statements are not supported.");
            }

            // Extract optional parameter types (e.g. $1::int4)
            var foundParamTypes = new List <string>();
            var cleanQueryText  = ParamRegex.Replace(Query, new MatchEvaluator((Match match) =>
            {
                foundParamTypes.Add(match.Groups["type"].Value);
                return("");
            }));

            if (ParametersDataTypes.Length < foundParamTypes.Count)
            {
                var arr = ParametersDataTypes;
                ParametersDataTypes = new int[foundParamTypes.Count];
                arr.CopyTo(ParametersDataTypes.AsSpan());
            }

            for (int i = 0; i < foundParamTypes.Count; i++)
            {
                if (ParametersDataTypes[i] == 0)
                {
                    ParametersDataTypes[i] = PgType.Parse(foundParamTypes[i]).Oid;
                }
            }

            transaction.Init(cleanQueryText, ParametersDataTypes);
            await writer.WriteAsync(messageBuilder.ParseComplete(), token);
        }
Esempio n. 2
0
        private static Collection <PgType> GetTypes(DataTable table)
        {
            Collection <PgType> types = new Collection <PgType>();

            if (table.Rows.Count.Equals(0))
            {
                return(types);
            }

            foreach (DataRow row in table.Rows)
            {
                PgType type = new PgType
                {
                    RowNumber   = Conversion.TryCastLong(row["row_number"]),
                    SchemaName  = Conversion.TryCastString(row["schema_name"]),
                    Name        = Conversion.TryCastString(row["type_name"]),
                    BaseType    = Conversion.TryCastString(row["base_type"]),
                    Owner       = Conversion.TryCastString(row["owner"]),
                    Collation   = Conversion.TryCastString(row["collation"]),
                    Default     = Conversion.TryCastString(row["default"]),
                    Type        = Conversion.TryCastString(row["type"]),
                    StoreType   = Conversion.TryCastString(row["store_type"]),
                    NotNull     = Conversion.TryCastBoolean(row["not_null"]),
                    Definition  = Conversion.TryCastString(row["definition"]),
                    Description = Conversion.TryCastString(row["description"])
                };

                types.Add(type);
            }

            return(types);
        }
Esempio n. 3
0
 public PgColumn(string name, short columnIndex, PgType pgType, PgFormat formatCode, int tableOid = 0)
 {
     Name          = name;
     TableObjectId = tableOid;
     ColumnIndex   = columnIndex;
     PgType        = pgType;
     FormatCode    = formatCode;
 }
Esempio n. 4
0
 private static void AddDefinition(StreamWriter writer, PgType type, List <string> newValues, SearchPathHelper searchPathHelper)
 {
     foreach (var newValue in newValues)
     {
         searchPathHelper.OutputSearchPath(writer);
         writer.WriteLine();
         writer.WriteLine(type.AlterSQL(newValue));
     }
 }
Esempio n. 5
0
        private static void BuildDocumentation(string content, PgType type)
        {
            content = content.Replace("[DBName]", Program.Database.ToUpperInvariant());

            content = Parsers.TypeParser.Parse(content, type);

            string targetPath = System.IO.Path.Combine(OutputPath, type.SchemaName, type.Name + ".html");

            FileHelper.WriteFile(content, targetPath);
        }
Esempio n. 6
0
        internal static void CallPgDiffTypesAddDefinition(StreamWriter writer, PgType type, List <string> newValues, SearchPathHelper searchPathHelper)
        {
            var pt = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(PgDiffTypes));

            try
            {
                pt.InvokeStatic("AddDefinition", new object[] { writer, type, newValues, searchPathHelper });
            }
            catch (System.MissingMethodException missingMethodException)
            {
                throw new System.NotSupportedException("AddDefinition with requested parameters is not found. Rerun code generation.", missingMethodException);
            }
        }
Esempio n. 7
0
        internal static string Parse(string content, PgType type)
        {
            StringBuilder items = new StringBuilder();

            items.Append(content.Replace("[Name]", type.Name)
                         .Replace("[RowNumber]", type.RowNumber.ToString())
                         .Replace("[TypeSchema]", type.SchemaName)
                         .Replace("[BaseType]", type.BaseType)
                         .Replace("[Owner]", type.Owner)
                         .Replace("[Collation]", type.Collation)
                         .Replace("[Default]", type.Default)
                         .Replace("[Type]", type.Type)
                         .Replace("[StoreType]", type.StoreType)
                         .Replace("[Definition]", type.Definition)
                         .Replace("[NotNull]", type.NotNull.ToString())
                         .Replace("[Description]", type.Description));

            content = content.Replace(content, items.ToString());
            return(content);
        }
Esempio n. 8
0
        public ArrayField(string dataLocator, string pgType, ISerializer serializer, MemberInfo[] members) : base(dataLocator, pgType, serializer.Casing, members)
        {
            var rawLocator = RawLocator;

            RawLocator = $"CAST({rawLocator} as jsonb)";

            var collectionType = members.Last().GetMemberType();

            ElementType = collectionType.DetermineElementType();
            var innerPgType = PostgresqlProvider.Instance.GetDatabaseType(ElementType, EnumStorage.AsInteger);


            if (PostgresqlProvider.Instance.HasTypeMapping(ElementType))
            {
                PgType = innerPgType + "[]";
            }

            if (PgType == "jsonb[]")
            {
                PgType = "jsonb";
            }



            TypedLocator = $"CAST({rawLocator} as {PgType})";



            LocatorForIncludedDocumentId =
                $"CAST(ARRAY(SELECT jsonb_array_elements_text(CAST({rawLocator} as jsonb))) as {innerPgType}[])";

            if (PgType.EqualsIgnoreCase("JSONB"))
            {
                LocatorForFlattenedElements = $"unnest(CAST(ARRAY(SELECT jsonb_array_elements(CAST({rawLocator} as jsonb))) as jsonb[]))";
            }
            else
            {
                LocatorForFlattenedElements = $"unnest({LocatorForIncludedDocumentId})";;
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Creates the types.
        /// </summary>
        internal static void Create(StreamWriter writer, [NullGuard.AllowNull] PgSchema oldSchema, PgSchema newSchema, SearchPathHelper searchPathHelper)
        {
            foreach (PgType newType in newSchema.Types)
            {
                if (oldSchema == null || !oldSchema.ContainsType(newType.Signature))
                {
                    PgType oldType = null;
                    if (oldSchema != null)
                    {
                        oldType = oldSchema.GetEnum(newType.Name);
                    }

                    if (oldType != null)
                    {
                        // if definitions of type changed it will be ignored to
                        continue;
                    }

                    searchPathHelper.OutputSearchPath(writer);
                    writer.WriteLine();
                    writer.WriteLine(newType.CreationSQL);
                }
            }
        }
Esempio n. 10
0
        public void WritePatch(DocumentMapping mapping, SchemaPatch patch)
        {
            patch.Updates.Apply(mapping, $"ALTER TABLE {mapping.Table.QualifiedName} ADD COLUMN {ColumnName} {PgType.Trim()};");

            patch.UpWriter.WriteLine($"update {mapping.Table.QualifiedName} set {UpdateSqlFragment()};");
        }
Esempio n. 11
0
        internal static void Run(PgType type)
        {
            string content = FileHelper.ReadResource(TemplatePath);

            BuildDocumentation(content, type);
        }
Esempio n. 12
0
        /// <summary>
        /// Parses the given statement and adds the <see cref="PgType"/> to the <see cref="PgDatabase"/>.
        /// </summary>
        /// <param name="database">The <see cref="PgDatabase"/> to which the <see cref="PgType"/> is added.</param>
        /// <param name="statement">The SQL statement of the <see cref="PgType"/>.</param>
        public static void Parse(PgDatabase database, string statement)
        {
            var parser = new Parser(statement);

            parser.Expect("CREATE");
            parser.Expect("TYPE");

            var typeName = parser.ParseIdentifier();

            parser.Expect("AS");

            // check if type is enum
            if (parser.ExpectOptional("ENUM"))
            {
                var enumEntries = new List <string>();

                var columnsExist = parser.ExpectOptional("(");

                if (columnsExist)
                {
                    while (!parser.ExpectOptional(")"))
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        var entry = parser.ParseStringCompat();
#pragma warning restore CS0618 // Type or member is obsolete
                        enumEntries.Add(ParserUtils.GetObjectName(entry));
                        parser.ExpectOptional(",");
                    }
                }

                var type = new PgType(ParserUtils.GetObjectName(typeName), true)
                {
                    EnumEntries = enumEntries,
                };
                var schemaName = ParserUtils.GetSchemaName(typeName, database);

                if (database.SchemaIsIgnored(schemaName))
                {
                    return;
                }

                PgSchema schema = database.GetSchema(schemaName);
                if (schema == null)
                {
                    throw new Exception(string.Format("Cannot find schema {0}. Statement {1}", schemaName, statement));
                }

                schema.Add(type);
            }
            else
            {
                var type = new PgType(ParserUtils.GetObjectName(typeName), false);

                var arguments = new List <PgArgument>();

                // type is no enum
                parser.Expect("(");

                var attributeType = new StringBuilder();

                while (true)
                {
                    var name     = parser.ParseIdentifier();
                    var datatype = parser.ParseDataType();

                    arguments.Add(new PgArgument(name, datatype));

                    parser.SkipWhitespace();
                    if (parser.ExpectOptional(")"))
                    {
                        break;
                    }
                    else
                    {
                        parser.Expect(",");
                    }
                }

                type.AttributeArguments = arguments;

                parser.Expect(";");

                var      schemaName = ParserUtils.GetSchemaName(typeName, database);
                PgSchema schema     = database.GetSchema(schemaName);
                if (schema == null)
                {
                    throw new Exception(string.Format("Cannot find schema {0}. Statement {1}", schemaName, statement));
                }

                schema.Add(type);
            }
        }