/// <summary>
 /// Set data. Override to to handle multipple resultsets. Takes only first result as Default
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="result"></param>
 /// <returns></returns>
 protected virtual T SetData(SqlMapper.GridReader result)
 {
     return(result.Read <T>().FirstOrDefault());
 }
Esempio n. 2
0
        protected virtual async Task <List <T> > PageListItemsAsync(SqlMapper.GridReader gridReader)
        {
            var result = await gridReader.ReadAsync <T>();

            return(result.ToList());
        }
        public static async Task <IReadOnlyCollection <Apprenticeship> > MapApprenticeships(SqlMapper.GridReader reader)
        {
            var apprenticeships = reader.Read <ApprenticeshipHeaderResult, Standard, ApprenticeshipHeaderResult>(
                (header, standard) =>
            {
                header.Standard = standard;
                return(header);
            },
                splitOn: "StandardCode");

            var locations = (reader.Read <ApprenticeshipLocationResult, Venue, ApprenticeshipLocationResult>(
                                 (location, venue) =>
            {
                location.Venue = venue;
                return(location);
            },
                                 splitOn: "VenueId"))
                            .GroupBy(al => al.ApprenticeshipId)
                            .ToDictionary(g => g.Key, g => g.AsEnumerable());

            var apprenticeshipLocationSubRegions = (await reader.ReadAsync <ApprenticeshipLocationSubRegionResult>())
                                                   .GroupBy(r => r.ApprenticeshipLocationId)
                                                   .ToDictionary(g => g.Key, g => g.Select(r => r.RegionId).AsEnumerable());

            return(apprenticeships
                   .Select(a => new Apprenticeship()
            {
                ApprenticeshipId = a.ApprenticeshipId,
                CreatedOn = a.CreatedOn,
                UpdatedOn = a.UpdatedOn,
                ProviderId = a.ProviderId,
                ProviderUkprn = a.ProviderUkprn,
                Standard = a.Standard,
                MarketingInformation = a.MarketingInformation,
                ApprenticeshipWebsite = a.ApprenticeshipWebsite,
                ContactEmail = a.ContactEmail,
                ContactTelephone = a.ContactTelephone,
                ContactWebsite = a.ContactWebsite,
                ApprenticeshipLocations = locations.GetValueOrDefault(a.ApprenticeshipId, Enumerable.Empty <ApprenticeshipLocationResult>())
                                          .Select(al =>
                {
                    // Some bad Classroom-based data has a non-null National value; fix that up here
                    if (al.ApprenticeshipLocationType == ApprenticeshipLocationType.ClassroomBased)
                    {
                        al.National = null;
                    }

                    // If National is true then remove explicit Radius
                    if (al.National == true)
                    {
                        al.Radius = null;
                    }

                    return new ApprenticeshipLocation()
                    {
                        ApprenticeshipLocationId = al.ApprenticeshipLocationId,
                        ApprenticeshipLocationType = al.ApprenticeshipLocationType,
                        DeliveryModes = MapDeliveryModesFromSqlValue(al.DeliveryModes).ToArray(),
                        National = al.National,
                        Radius = al.Radius,
                        SubRegionIds = apprenticeshipLocationSubRegions.GetValueOrDefault(al.ApprenticeshipLocationId, Enumerable.Empty <string>()).ToArray(),
                        Telephone = al.Telephone,
                        Venue = al.Venue
                    };
                })
                                          .ToArray()
            })
                   .ToArray());
        }
 /// <summary>
 /// Set data for List result.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="result"></param>
 /// <returns></returns>
 protected virtual IEnumerable <T> SetListData(SqlMapper.GridReader result)
 {
     return(result.Read <T>());
 }
Esempio n. 5
0
 public GridReaderResultReader(SqlMapper.GridReader reader)
 {
     _reader = reader;
 }
        private static async Task <Table> GetTableSchemaAsync(this SqlConnection connection,
                                                              SqlTransaction transaction, TableSchemaKey key, CancellationToken cancellationToken)
        {
            // Validate parameters.
            Debug.Assert(connection != null);

            // The sql.
            const string sql = @"
select 
    s.name as schema_name, t.name as table_name, t.create_date, t.modify_date 
from 
    sys.tables as t 
        inner join sys.schemas as s on 
            s.schema_id = t.schema_id 
where 
    t.object_id = object_id(@table);
select
	c.column_id,
	c.name,
	c.is_identity,
	c.is_nullable,
	c.is_computed
from 
	sys.columns as c
where 
	c.object_id = object_id(@table);
select
	i.index_id,
	i.name,
	i.is_primary_key,
	ic.column_id,
	ic.key_ordinal,
	ic.is_descending_key,
	ic.is_included_column
from 
	sys.indexes as i
		inner join sys.index_columns as ic on
			ic.object_id = i.object_id and
			ic.index_id = i.index_id
where 
	i.object_id = object_id(@table);
";

            // Query multiple.
            using (SqlMapper.GridReader gridReader = await connection.QueryMultipleAsync(sql,
                                                                                         new { table = key.Table }, transaction: transaction, commandType: CommandType.Text).ConfigureAwait(false))
            {
                // Get the items.
                TableRecord tableRecord = (await gridReader.ReadAsync <TableRecord>().ConfigureAwait(false)).
                                          Single();

                // Set the column records.
                IReadOnlyCollection <ColumnRecord> columnRecords = (await gridReader.ReadAsync <ColumnRecord>().
                                                                    ConfigureAwait(false)).ToReadOnlyCollection();

                // Set the index records.
                IReadOnlyCollection <IndexRecord> indexRecords = (await gridReader.ReadAsync <IndexRecord>().
                                                                  ConfigureAwait(false)).ToReadOnlyCollection();

                // Start creating everything, the columns first.
                IReadOnlyDictionary <int, Column> columns = columnRecords.
                                                            Select(c => new Column(c.column_id, c.name, c.is_identity, c.is_nullable, c.is_computed)).
                                                            ToReadOnlyDictionary(c => c.Id);

                // Get the indexes and index columns.
                IReadOnlyCollection <Index> indexes = indexRecords.
                                                      // Group the indexes first.
                                                      GroupBy(i => new { i.index_id, i.name, i.is_primary_key }).

                                                      // Select the index for each group.
                                                      Select(g => new Index(g.Key.index_id, g.Key.name, g.Key.is_primary_key,
                                                                            // Get the individual columns.
                                                                            g.Select(c => new IndexColumn(columns[c.column_id], c.key_ordinal, c.is_descending_key,
                                                                                                          c.is_included_column)))).
                                                      // Materialize.
                                                      ToReadOnlyCollection();

                // Assemble the table and return.
                return(new Table(tableRecord.schema_name, tableRecord.table_name, tableRecord.create_date,
                                 tableRecord.modify_date, columns.Values.OrderBy(c => c.Id), indexes));
            }
        }
        private bool ParseResult(IBookingData request, SqlMapper.GridReader reader)
        {
            if ((request == null) || (reader == null))
            {
                return(false);
            }
            if (request.Value == null)
            {
                return(false);
            }
            try
            {
                request.OfficeDto = SelectionHelpers.WrappedSelectedDto <OFICINAS, OfficeDtos>(request.Value.OFICINA_RES1, _mapper, reader);

                request.ReservationOfficeDeparture = SelectionHelpers.WrappedSelectedDto <OFICINAS, OfficeDtos>(request.Value.OFISALIDA_RES1, _mapper, reader);

                request.ReservationOfficeArrival = SelectionHelpers.WrappedSelectedDto <OFICINAS, OfficeDtos>(request.Value.OFIRETORNO_RES1, _mapper, reader);

                request.BookingBudget = SelectionHelpers.WrappedSelectedDto <BudgetSummaryDto, BudgetSummaryDto>(request.Value.PRESUPUESTO_RES1, _mapper, reader);

                request.FareDto = SelectionHelpers.WrappedSelectedDto <NTARI, FareDto>(request.Value.TARIFA_RES1, _mapper, reader);

                request.VehicleGroupDto = SelectionHelpers.WrappedSelectedDto <GRUPOS, VehicleGroupDto>(request.Value.GRUPO_RES1, _mapper, reader);

                request.BrokerDto = SelectionHelpers.WrappedSelectedDto <CommissionAgentSummaryDto, CommissionAgentSummaryDto>(request.Value.COMISIO_RES2, _mapper, reader);

                request.VehicleDto = SelectionHelpers.WrappedSelectedDto <VehicleSummaryDto, VehicleSummaryDto>(request.Value.VCACT_RES1, _mapper, reader);

                request.Clients = SelectionHelpers.WrappedSelectedDto <ClientSummaryExtended, ClientSummaryExtended>(request.Value.CLIENTE_RES1, _mapper, reader);

                request.DriverDto2 = SelectionHelpers.WrappedSelectedDto <ClientSummaryExtended, ClientSummaryExtended>(request.Value.CONDUCTOR_RES1, _mapper, reader);

                request.DriverDto3 = SelectionHelpers.WrappedSelectedDto <ClientSummaryExtended, ClientSummaryExtended>(request.Value.OTROCOND_RES2, _mapper, reader);

                request.DriverDto4 = SelectionHelpers.WrappedSelectedDto <ClientSummaryExtended, ClientSummaryExtended>(request.Value.OTRO2COND_RES2, _mapper, reader);

                request.DriverDto5 = SelectionHelpers.WrappedSelectedDto <ClientSummaryExtended, ClientSummaryExtended>(request.Value.OTRO3COND_RES2, _mapper, reader);
                // request.DriverDto6 = SelectionHelpers.WrappedSelectedDto<ClientSummaryExtended, ClientSummaryExtended>(request.Value., _mapper, reader);


                request.CityDto3 = SelectionHelpers.WrappedSelectedDto <POBLACIONES, CityDto>(request.Value.POCOND_RES2, _mapper, reader);

                request.DriverCountryList = SelectionHelpers.WrappedSelectedDto <Country, CountryDto>(request.Value.PAISNIFCOND_RES2, _mapper, reader);

                request.CountryDto3 = SelectionHelpers.WrappedSelectedDto <Country, CountryDto>(request.Value.PAISCOND_RES2, _mapper, reader);

                request.ProvinceDto3 = SelectionHelpers.WrappedSelectedDto <PROVINCIA, ProvinciaDto>(request.Value.PROVCOND_RES2, _mapper, reader);

                request.OriginDto = SelectionHelpers.WrappedSelectedDto <ORIGEN, OrigenDto>(request.Value.ORIGEN_RES2, _mapper, reader);

                request.BookingMediaDto = SelectionHelpers.WrappedSelectedDto <MEDIO_RES, BookingMediaDto>(request.Value.MEDIO_RES1, _mapper, reader);

                request.BookingTypeDto = SelectionHelpers.WrappedSelectedDto <TIPOS_RESERVAS, BookingTypeDto>(request.Value.TIPORES_res1, _mapper, reader);

                request.AgencyEmployeeDto = SelectionHelpers.WrappedSelectedDto <EAGE, AgencyEmployeeDto>(request.Value.EMPLEAGE_RES2, _mapper, reader);

                request.ContactsDto1 = SelectionHelpers.WrappedSelectedDto <CliContactos, ContactsDto>(request.Value.CONTACTO_RES2, _mapper, reader);

                request.PaymentFormDto = SelectionHelpers.WrappedSelectedDto <FORMAS, PaymentFormDto>(request.Value.FCOBRO_RES1, _mapper, reader);

                request.PrintingTypeDto = SelectionHelpers.WrappedSelectedDto <CONTRATIPIMPR, PrintingTypeDto>(request.Value.CONTRATIPIMPR_RES, _mapper, reader);

                request.VehicleActivitiesDto = SelectionHelpers.WrappedSelectedDto <ACTIVEHI, VehicleActivitiesDto>(request.Value.ACTIVEHI_RES1, _mapper, reader);



#pragma warning disable CS0168 // Variable is declared but never used
            }
            catch (System.Exception ex)
#pragma warning restore CS0168 // Variable is declared but never used
            {
                throw new DataAccessLayerException("Parsing multiple query result error", ex);
            }
            return(true);
        }
 void mapper(SqlMapper.GridReader gridReader)
 {
     results   = gridReader.Read <T>();
     totalRows = gridReader.Read <int>().First();
 }
Esempio n. 9
0
        public async Task <IEnumerable <FarmerBuyingCalendarViewModel> > Gets(string condition = "")
        {
            List <FarmerBuyingCalendarViewModel> result = new List <FarmerBuyingCalendarViewModel>();
            string cmd = $@"SELECT * FROM `farmer_buying_calendar` o
                            LEFT JOIN `farmer` f ON o.farmer_id = f.id AND f.is_used = 1 AND f.is_deleted = 0
                            LEFT JOIN `farmer_buying_calendar_item` i ON i.farmer_buying_calendar_id = o.id
                            LEFT JOIN `product` p ON p.id = i.product_id AND p.is_used = 1 AND p.is_deleted = 0
                            LEFT JOIN `uom` u ON u.id = i.uom_id AND u.is_used = 1 AND u.is_deleted = 0
                            WHERE o.is_deleted = 0";

            if (!string.IsNullOrEmpty(condition))
            {
                cmd += " AND " + condition;
            }
            if (DbConnection != null)
            {
                SqlMapper.GridReader rd = await DbConnection.QueryMultipleAsync(cmd, transaction : DbTransaction);

                rd.Read <FarmerBuyingCalendar, Farmer, FarmerBuyingCalendarItem, Product, UoM, FarmerBuyingCalendarViewModel>(
                    (orderRs, fRs, itemRs, pRs, uRs) =>
                {
                    var order = result.FirstOrDefault(o => o.Id == orderRs.Id);

                    if (order == null)
                    {
                        order = CommonHelper.Mapper <FarmerBuyingCalendar, FarmerBuyingCalendarViewModel>(orderRs);
                        result.Add(order);
                    }

                    if (order.Farmer == null)
                    {
                        order.Farmer = fRs;
                    }

                    var item = order.Items.FirstOrDefault(i => i.Id == itemRs.Id);
                    if (item == null)
                    {
                        item = CommonHelper.Mapper <FarmerBuyingCalendarItem, FarmerBuyingCalendarItemViewModel>(itemRs);
                        order.Items.Add(item);
                    }

                    item.Product = pRs;
                    item.UoM     = uRs;

                    return(order);
                }
                    );

                return(result);
            }
            else
            {
                using (var conn = DALHelper.GetConnection())
                {
                    SqlMapper.GridReader rd = await conn.QueryMultipleAsync(cmd, transaction : DbTransaction);

                    rd.Read <FarmerBuyingCalendar, Farmer, FarmerBuyingCalendarItem, Product, UoM, FarmerBuyingCalendarViewModel>(
                        (orderRs, fRs, itemRs, pRs, uRs) =>
                    {
                        var order = result.FirstOrDefault(o => o.Id == orderRs.Id);

                        if (order == null)
                        {
                            order = CommonHelper.Mapper <FarmerBuyingCalendar, FarmerBuyingCalendarViewModel>(orderRs);
                            result.Add(order);
                        }

                        if (order.Farmer == null)
                        {
                            order.Farmer = fRs;
                        }

                        var item = order.Items.FirstOrDefault(i => i.Id == itemRs.Id);
                        if (item == null)
                        {
                            item = CommonHelper.Mapper <FarmerBuyingCalendarItem, FarmerBuyingCalendarItemViewModel>(itemRs);
                            order.Items.Add(item);
                        }

                        item.Product = pRs;
                        item.UoM     = uRs;

                        return(order);
                    }
                        );

                    return(result);
                }
            }
        }
 public QueryReader(SqlMapper.GridReader reader, DbConnection connection)
 {
     _reader     = reader;
     _connection = connection;
 }
Esempio n. 11
0
 public GridReaderWrapper(SqlMapper.GridReader gridReader)
 {
     _gridReader = gridReader;
 }
Esempio n. 12
0
        static IEnumerable <TMain> MapKeys <TMain, TFirstChild, TSecondChild, TThirdChild, TFourthChild, TFifthChild, TSixthChild, TSeventhChild, TEighthChild, TKey>
        (
            SqlMapper.GridReader reader,
            Func <TMain, TKey> mainKey,
            Func <TFirstChild, TKey> firstChild,
            Func <TSecondChild, TKey> secondChild,
            Func <TThirdChild, TKey> thirdChild,
            Func <TFourthChild, TKey> fourthChild,
            Func <TFifthChild, TKey> fifthChild,
            Func <TSixthChild, TKey> sixthChild,
            Func <TSeventhChild, TKey> seventhChild,
            Func <TEighthChild, TKey> eighthChild,
            Action <TMain, IEnumerable <TFirstChild> > addFirstChild,
            Action <TMain, IEnumerable <TSecondChild> > addSecondChild,
            Action <TMain, IEnumerable <TThirdChild> > addThirdChild,
            Action <TMain, IEnumerable <TFourthChild> > addFourthChild,
            Action <TMain, IEnumerable <TFifthChild> > addFifthChild,
            Action <TMain, IEnumerable <TSixthChild> > addSixthChild,
            Action <TMain, IEnumerable <TSeventhChild> > addSeventhChild,
            Action <TMain, IEnumerable <TEighthChild> > addEighthChild
        )
        {
            var first         = reader.Read <TMain>().ToList();
            var childFirstMap = reader
                                .Read <TFirstChild>()
                                .GroupBy(s => firstChild(s))
                                .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childSecondMap = reader
                                 .Read <TSecondChild>()
                                 .GroupBy(s => secondChild(s))
                                 .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childThirdMap = reader
                                .Read <TThirdChild>()
                                .GroupBy(s => thirdChild(s))
                                .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childFourthMap = reader
                                 .Read <TFourthChild>()
                                 .GroupBy(s => fourthChild(s))
                                 .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childFifthMap = reader
                                .Read <TFifthChild>()
                                .GroupBy(s => fifthChild(s))
                                .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childSixthMap = reader
                                .Read <TSixthChild>()
                                .GroupBy(s => sixthChild(s))
                                .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childSeventhMap = reader
                                  .Read <TSeventhChild>()
                                  .GroupBy(s => seventhChild(s))
                                  .ToDictionary(g => g.Key, g => g.AsEnumerable());
            var childEighthMap = reader
                                 .Read <TEighthChild>()
                                 .GroupBy(s => eighthChild(s))
                                 .ToDictionary(g => g.Key, g => g.AsEnumerable());

            foreach (var item in first)
            {
                IEnumerable <TFirstChild> childrenOfFirst;
                if (childFirstMap.TryGetValue(mainKey(item), out childrenOfFirst))
                {
                    addFirstChild(item, childrenOfFirst);
                }

                IEnumerable <TSecondChild> childrenOfSecond;
                if (childSecondMap.TryGetValue(mainKey(item), out childrenOfSecond))
                {
                    addSecondChild(item, childrenOfSecond);
                }

                IEnumerable <TThirdChild> childrenOfThird;
                if (childThirdMap.TryGetValue(mainKey(item), out childrenOfThird))
                {
                    addThirdChild(item, childrenOfThird);
                }

                IEnumerable <TFourthChild> childrenOfFourth;
                if (childFourthMap.TryGetValue(mainKey(item), out childrenOfFourth))
                {
                    addFourthChild(item, childrenOfFourth);
                }

                IEnumerable <TFifthChild> childrenOfFifth;
                if (childFifthMap.TryGetValue(mainKey(item), out childrenOfFifth))
                {
                    addFifthChild(item, childrenOfFifth);
                }

                IEnumerable <TSixthChild> childrenOfSixth;
                if (childSixthMap.TryGetValue(mainKey(item), out childrenOfSixth))
                {
                    addSixthChild(item, childrenOfSixth);
                }

                IEnumerable <TSeventhChild> childrenOfSeventh;
                if (childSeventhMap.TryGetValue(mainKey(item), out childrenOfSeventh))
                {
                    addSeventhChild(item, childrenOfSeventh);
                }

                IEnumerable <TEighthChild> childrenOfEighth;
                if (childEighthMap.TryGetValue(mainKey(item), out childrenOfEighth))
                {
                    addEighthChild(item, childrenOfEighth);
                }
            }

            return(first);
        }
Esempio n. 13
0
        private static async Task <ICollection <TransactionModel> > GetTransactionModelsAsync(SqlMapper.GridReader reader)
        {
            var transactions = (await reader.ReadAsync <Transaction>()).ToList();
            var postings     = await reader.ReadAsync <PostingDto>();

            var postingsLookupByTransactionId = postings
                                                .GroupBy(x => x.TransactionId)
                                                .ToDictionary(x => x.Key, x => x.ToList());

            var transactionModels = new List <TransactionModel>(transactions.Count);

            foreach (var transaction in transactions)
            {
                var transactionModel = new TransactionModel
                {
                    Id          = transaction.Id,
                    Description = transaction.Description,
                    PostedDate  = transaction.PostedDate,
                };

                if (postingsLookupByTransactionId.TryGetValue(transaction.Id, out var transactionPostings))
                {
                    foreach (var posting in transactionPostings)
                    {
                        var postingModel = new TransactionModel.Posting
                        {
                            Account = new TransactionModel.Account {
                                Id = posting.AccountId, Name = posting.AccountName
                            },
                            Amount = posting.Amount,
                        };

                        transactionModel.Postings.Add(postingModel);
                    }
                }

                transactionModels.Add(transactionModel);
            }


            return(transactionModels);
        }
Esempio n. 14
0
        protected virtual List <T> PageListItems(SqlMapper.GridReader gridReader)
        {
            var result = gridReader.Read <T>();

            return(result.ToList());
        }
Esempio n. 15
0
        public static IEnumerable <DtoType> SelectDto <EntityType, DtoType>(IMapper mapper, SqlMapper.GridReader gridReader) where DtoType : class
        {
            var hasValue = gridReader.ReadSingle <int>() > 0;

            if (hasValue)
            {
                var entityCollection = gridReader.Read <EntityType>();
                if (entityCollection != null)
                {
                    if (typeof(EntityType) != typeof(DtoType))
                    {
                        return(mapper.Map <IEnumerable <EntityType>, IEnumerable <DtoType> >(entityCollection));
                    }
                    else
                    {
                        return(entityCollection as IEnumerable <DtoType>);
                    }
                }
            }
            else
            {
                var badValue = gridReader.Read();
            }
            var list = new List <DtoType>();

            return(list);
        }
Esempio n. 16
0
 public IEnumerable <T> Read <T>()
 {
     SqlMapper.GridReader reader = _items.Dequeue();
     return(reader.Read <T>());
 }
Esempio n. 17
0
        public static IEnumerable <DtoType> WrappedSelectedDto <EntityType, DtoType>(object value, IMapper mapper, SqlMapper.GridReader reader) where DtoType : class
        {
            IEnumerable <DtoType> current = new List <DtoType>();

            if ((value == null) || (reader == null))
            {
                return(current);
            }
            // malformed string or empty string shall return null or empty values.
            if (value is string currentString)
            {
                if (string.IsNullOrEmpty(currentString))
                {
                    return(current);
                }
            }
            current = SelectDto <EntityType, DtoType>(mapper, reader);
            return(current);
        }
Esempio n. 18
0
 internal Reader(SqlMapper.GridReader reader) => _reader = reader;
Esempio n. 19
0
        public async Task <MalUserLookupResults> GetAnimeListForUserAsync(string user, CancellationToken cancellationToken)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
            {
                await conn.OpenAsync(cancellationToken);

                // ILIKE does a table scan. :( The ideal way of doing a case-insensitive search would be to use the citext
                // data type, but that's an add-on and not part of a standard Postgres install.
                // This class is only intended to be used for development anyway.

                string sql = @"
SELECT mal_user.mal_name, mal_user.mal_user_id FROM mal_user WHERE mal_name ILIKE :UserName ORDER BY mal_user_id LIMIT 1;

SELECT

mal_anime.mal_anime_id, mal_anime.title, mal_anime.mal_anime_type_id, mal_anime.num_episodes, mal_anime.mal_anime_status_id,
mal_anime.start_year, mal_anime.start_month, mal_anime.start_day, mal_anime.end_year, mal_anime.end_month, mal_anime.end_day,
mal_anime.image_url,

mal_list_entry.rating, mal_list_entry.mal_list_entry_status_id, mal_list_entry.num_episodes_watched,
mal_list_entry.started_watching_year, mal_list_entry.started_watching_month, mal_list_entry.started_watching_day,
mal_list_entry.finished_watching_year, finished_watching_month, finished_watching_day, mal_list_entry.last_mal_update,

mal_list.synonyms, mal_list.tags

FROM
(
SELECT mal_user.mal_user_id AS mal_user_id, mal_anime.mal_anime_id AS mal_anime_id, array_agg(DISTINCT mal_anime_synonym.synonym) AS synonyms, array_agg(DISTINCT mal_list_entry_tag.tag) AS tags

FROM mal_user
JOIN mal_list_entry ON mal_user.mal_user_id = mal_list_entry.mal_user_id
JOIN mal_anime ON mal_list_entry.mal_anime_id = mal_anime.mal_anime_id
LEFT OUTER JOIN mal_anime_synonym ON mal_anime.mal_anime_id = mal_anime_synonym.mal_anime_id
LEFT OUTER JOIN mal_list_entry_tag ON mal_list_entry.mal_anime_id = mal_list_entry_tag.mal_anime_id AND mal_list_entry.mal_user_id = mal_list_entry_tag.mal_user_id

WHERE mal_user.mal_user_id = (SELECT mal_user_id FROM mal_user WHERE mal_name ILIKE :UserName ORDER BY mal_user_id LIMIT 1)
GROUP BY mal_user.mal_user_id, mal_anime.mal_anime_id
) AS mal_list
JOIN mal_user ON mal_list.mal_user_id = mal_user.mal_user_id
JOIN mal_anime ON mal_list.mal_anime_id = mal_anime.mal_anime_id
JOIN mal_list_entry ON mal_list.mal_user_id = mal_list_entry.mal_user_id AND mal_list.mal_anime_id = mal_list_entry.mal_anime_id
";
                int    userId;
                string canonicalUserName        = null;
                List <MyAnimeListEntry> entries = new List <MyAnimeListEntry>();
                using (SqlMapper.GridReader results = await conn.QueryMultipleAsync(new CommandDefinition(sql, new { UserName = user }, cancellationToken: cancellationToken)))
                {
                    User u = (await results.ReadAsync <User>()).FirstOrDefault();
                    if (u == null)
                    {
                        throw new MalUserNotFoundException(string.Format("No MAL list exists for {0}.", user));
                    }
                    userId            = u.mal_user_id;
                    canonicalUserName = u.mal_name;

                    foreach (UserListEntry dbEntry in await results.ReadAsync <UserListEntry>())
                    {
                        MalAnimeInfoFromUserLookup animeInfo = new MalAnimeInfoFromUserLookup(
                            animeId: dbEntry.mal_anime_id,
                            title: dbEntry.title,
                            type: (MalAnimeType)dbEntry.mal_anime_type_id,
                            synonyms: dbEntry.synonyms.Where(syn => syn != null).ToList(),
                            status: (MalSeriesStatus)dbEntry.mal_anime_status_id,
                            numEpisodes: dbEntry.num_episodes,
                            startDate: new UncertainDate(year: dbEntry.start_year, month: dbEntry.start_month, day: dbEntry.start_day),
                            endDate: new UncertainDate(year: dbEntry.end_year, month: dbEntry.end_month, day: dbEntry.end_day),
                            imageUrl: dbEntry.image_url
                            );

                        MyAnimeListEntry entry = new MyAnimeListEntry(
                            score: dbEntry.rating,
                            status: (CompletionStatus)dbEntry.mal_list_entry_status_id,
                            numEpisodesWatched: dbEntry.num_episodes_watched,
                            myStartDate: new UncertainDate(year: dbEntry.started_watching_year, month: dbEntry.started_watching_month, day: dbEntry.started_watching_day),
                            myFinishDate: new UncertainDate(year: dbEntry.finished_watching_year, month: dbEntry.finished_watching_month, day: dbEntry.finished_watching_day),
                            myLastUpdate: dbEntry.last_mal_update,
                            animeInfo: animeInfo,
                            tags: dbEntry.tags.Where(tag => tag != null).ToList()
                            );

                        entries.Add(entry);
                    }

                    return(new MalUserLookupResults(userId: userId, canonicalUserName: canonicalUserName, animeList: entries));
                }
            }
        }
Esempio n. 20
0
 public object QuerySingle(string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null)
 {
     SqlMapper.GridReader reader = _mydb.QueryMultiple(sql, param, transaction, commandTimeout, commandType);
     return(reader.ReadFirst());
 }
        PanelDatasetCompilerContext ReadContextGrid(ConceptDatasetExecutionRequest request, SqlMapper.GridReader gridReader)
        {
            var queryCtx = gridReader.Read <QueryContext>().FirstOrDefault();
            var concept  = HydratedConceptReader.Read(gridReader).FirstOrDefault();
            var pi       = request.PanelItem;
            var panel    = new Panel
            {
                SubPanels = new List <SubPanel>
                {
                    new SubPanel
                    {
                        PanelItems = new List <PanelItem>
                        {
                            pi.PanelItem(concept)
                        }
                    }
                }
            };

            if (request.EarlyBound != null && request.LateBound != null)
            {
                panel.DateFilter = new DateBoundary
                {
                    Start = new DateFilter {
                        Date = (DateTime)request.EarlyBound, DateIncrementType = DateIncrementType.Specific
                    },
                    End = new DateFilter {
                        Date = (DateTime)request.LateBound, DateIncrementType = DateIncrementType.Specific
                    }
                };
            }

            return(new PanelDatasetCompilerContext
            {
                QueryContext = queryCtx,
                Panel = panel
            });
        }