How do I insert Postgres "infinity" into a Timestamp field with JOOQ? - postgresql

I have a column defined like this:
expiry timestamp(0) without time zone not null
With Postgres, I can issue SQL like:
insert into my_table(expiry) values ('infinity')
I've been digging through the JOOQ doco, but couldn't find any example of dealing with this.
Can I do that with JOOQ - and what would it look like?
Additionally, is it possible using an UpdatableRecord? Is there some kind of infinity "flag" instance of Timestamp I can use?

Ok, found a way to do it directly.
MyRecord r = db.insertInto(
MY_RECORD,
MY_RECORD.ID,
MY_RECORD.CREATED,
MY_RECORD.EXPIRY
).values(
val(id),
currentTimestamp(),
val("infinity").cast(Timestamp.class)
).returning().fetchOne();
But that feels more like a workaround than the right way to do it. Casting a string to a timestamp seems a little bit round-about to me, so I wrote a CustomField to make using it and querying easier:
public class TimestampLiteral extends CustomField<Timestamp> {
public static final TimestampLiteral INFINITY =
new TimestampLiteral("'infinity'");
public static final TimestampLiteral NEGATIVE_INFINITY =
new TimestampLiteral("'-infinity'");
public static final TimestampLiteral TODAY =
new TimestampLiteral("'today'");
private String literalValue;
public TimestampLiteral(String literalValue){
super("timestamp_literal", SQLDataType.TIMESTAMP);
this.literalValue = literalValue;
}
#Override
public void accept(Context<?> context){
context.visit(delegate(context.configuration()));
}
private QueryPart delegate(Configuration configuration){
switch( configuration.dialect().family() ){
case POSTGRES:
return DSL.field(literalValue);
default:
throw new UnsupportedOperationException(
"Dialect not supported because I don't know how/if this works in other databases.");
}
}
}
Then the query is:
MyRecord r = db.insertInto(
MY_RECORD,
MY_RECORD.ID,
MY_RECORD.CREATED,
MY_RECORD.EXPIRY
).values(
val(id),
TimestampLiteral.TODAY,
TimestampLiteral.INFINITY
).returning().fetchOne();
Don't know if this is necessarily the "right" way to do this, but it seems to work for the moment.
Still interested to hear if there's a way to do this with an UpdatableRecord.

I create a java.sql.Timestamp passing org.postgresql.PGStatement.DATE_POSITIVE_INFINITY to its constructor.
create.insertInto(
MY_RECORD,
MY_RECORD.ID,
MY_RECORD.CREATED,
MY_RECORD.EXPIRY
).values(
1,
new Timestamp(System.currentTimeMillis()),
new Timestamp(PGStatement.DATE_POSITIVE_INFINITY)
).execute();

Related

java.time.LocalDate not supported in native queries by latest Spring Data/Hibernate?

Problem: Native queries with Spring Data returning dates return java.sql.Date not java.time.LocalDate, despite the setup.
Context: A new project with Spring Boot 2.0.0.M5 (the latest), Hibernate 5.2.11, Hibernate-Java8 5.2.12 (which gives support for JSR310 classes as long as it's on the classpath).
Anonymized example below (the app is not really about birthdays):
public interface BirthdayRepository<T, ID extends Serializable> extends Repository<T, ID> {
#Query(value = "select day from birthdays", nativeQuery = true)
Iterable<java.sql.Date> getBirthdays(); //the return type should ideally be java.time.LocalDate
}
In the database (SQL Server), the day field is DATE and values are like 2017-10-24.
The problem is that at runtime, the Spring Data repository (whose implementation I cannot control, or is there a way?) returns java.sql.Date not java.time.LocalDate (Clarification: the return type appears to be decided by Spring Data and remains java.sql.Date even if I change the return type to be java.time.LocalDate, which is how I started to).
Isn't there a way to get LocalDate directly? I can convert it later, but (1) that's inefficient and (2) the repository methods have to return the old date/time classes, which is something I'd like to avoid. I read the Spring Data documentation, but there's nothing about this.
EDIT: for anyone having the same question, below is the solution, the converter suggested by Jens.
public class LocalDateTypeConverter {
#Converter(autoApply = true)
public static class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
#Nullable
#Override
public Date convertToDatabaseColumn(LocalDate date) {
return date == null ? null : new Date(LocalDateToDateConverter.INSTANCE.convert(date).getTime());
}
#Nullable
#Override
public LocalDate convertToEntityAttribute(Date date) {
return date == null ? null : DateToLocalDateConverter.INSTANCE.convert(date);
}
}
It looks like you found a gap in the converters. Spring Data converts out of the box between java.util.Date and java.time.LocalDate but not between java.time.LocalDate and java.sql.Date and other date and time-related types in the java.sql package.
You can create your own converter to do that. You can use Jsr310JpaConverters as a template.
Also, you might want to create a feature request and if you build a converter for your use, you might even submit a pull request.
I know this is an older question, but my solution to this problem does not require a custom converter.
public interface BirthdayRepository<T, ID extends Serializable> extends Repository<T, ID> {
#Query(value = "select cast(day as date) from birthdays", nativeQuery = true)
Iterable<java.time.LocalDate> getBirthdays();
}
The CAST tells JPQL to use available java date\time types rather than java.sql.Date

How to implement a #FieldBridge to an #EmbeddedId field

When there is an #EmbeddedId field, a custom Field Bridge should be implemented.
There is a Feature opened about it https://hibernate.atlassian.net/browse/HSEARCH-1879. But it isn't ready yet.
In this case, the interface correct to implement is TwoWayFieldBridge?
Below is my implementation for a composite ID with 5 fields.
public class ChavePrimariaAcompanhamentoBridge implements TwoWayFieldBridge {
#Override
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
AcompanhamentoPK chavePrimaria = (AcompanhamentoPK) value;
Integer ano = chavePrimaria.getAno();
Integer mes = chavePrimaria.getMes();
Long codigoCredenciada = chavePrimaria.getCredenciada().getCodigo();
Long codigoPosto = chavePrimaria.getPostoAtendimento().getCodigo();
Integer numeroSequencial = chavePrimaria.getNumeroSequencial();
luceneOptions.addNumericFieldToDocument("mes", mes, document);
luceneOptions.addNumericFieldToDocument("ano", ano, document);
luceneOptions.addNumericFieldToDocument("credenciada.codigo", codigoCredenciada, document);
luceneOptions.addNumericFieldToDocument("postoAtendimento.codigo", codigoPosto, document);
luceneOptions.addNumericFieldToDocument("numeroSequencial", numeroSequencial, document);
}
#Override
public Object get(String name, Document document) {
AcompanhamentoPK chavePrimaria = new AcompanhamentoPK();
chavePrimaria.setMes(Integer.valueOf(document.get("mes")));
chavePrimaria.setAno(Integer.valueOf(document.get("ano")));
chavePrimaria.setCredenciada(new Credenciada(Long.valueOf(document.get("credenciada.codigo"))));
chavePrimaria.setPostoAtendimento(new CadastroPostoAtendimento(Long.valueOf(document.get("postoAtendimento.codigo"))));
chavePrimaria.setNumeroSequencial(Integer.valueOf(document.get("numeroSequencial")));
return chavePrimaria;
}
#Override
public String objectToString(Object value) {
AcompanhamentoPK chavePrimaria = (AcompanhamentoPK) value;
return chavePrimaria.toString();
}
}
1 - Is there another best way to make it?
2 - Is there any error(about concepts) in this implementation?
3 - What is the objectToString method used for? It is important?
I am making this question because I haven't found any documentation about it, so I am not sure.
EDIT: In Hibernate Search 6+, in order to map an #EmbeddedId, you should use a custom IdentifierBridge: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#mapper-orm-bridge-identifierbridge
Original answer for Hibernate Search 5:
In this case, the interface correct to implement is TwoWayFieldBridge?
Yes: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#_two_way_bridge
1 - Is there another best way to make it?
Not that I know of.
2 - Is there any error(about concepts) in this implementation?
Yes.
You shouldn't use Integer.valueOf here. Just call Field.numericValue() on the result of document.get, and cast the result to Integer.
You should also store the unique string representation of the ID in the set() method:
luceneOptions.addFieldToDocument( name, objectToString( id ), document );
3 - What is the objectToString method used for?
Hibernate Search will use the result of this method mostly to build queries, for example when it must retrieve documents that should be deleted, or when you query the ID field explicitly.
It is important?
Nothing will work unless you implement it properly, i.e. unless you make sure that:
it returns two different values for two different composite IDs
it always returns the same value for a given composite ID

INET Nordic FIX protocols extending to nanosecond granularity timestamps

All INET Nordic FIX protocols will be enhanced by extending to nanosecond granularity timestamps on 16.oktober 2015 (see notification and section 3.1.1 in the spec).
The timestamps will look like this: 20150924-10:35:20.840117690
quickfix currently rejects messages that contain fields with this new format with the error: Incorrect data format for value
Are there any plans to support this new format? Or maybe some workaround?
You can first try modifying your data dictionary. For example if you are using fix42.xml that comes with QuickFIX, you can change the affected timestamp fields from type='UTCTIMESTAMP' to type='STRING'.
If that isn't enough, you should instead write a patch against QuickFIX in C++, which should be somewhat straightforward once you know where to patch it, which I think is UtcTimeStampConvertor, around here: https://github.com/quickfix/quickfix/blob/master/src/C%2B%2B/FieldConvertors.h#L564
I think you need to add a case 27: above case 21: near the top, because your format has six extra digits. It looks like the rest of the function doesn't care about the total field length.
Of course if you want to actually inspect the sub-millisecond precision part of these timestamps, you'll need to do more.
No plans in QF/n, but only because this is the first I've heard of this.
I'll need to write some tests to see what the repercussions are. It may be that the time/date parser just truncates the extra nano places when it converts the string to a DateTime.
I've opened an issue: https://github.com/connamara/quickfixn/issues/352
This change is as far as I know kind of breaking the fix protocol definition of timestamps but that's another story.
There is a static class in QuickFixn called DateTimeConverter under QuickFix/Fields/Converters.
To get this to work correctly you would need to add format strings in lines in that class.
Add "yyyyMMdd-HH:mm:ss.fffffff" to DATE_TIME_FORMATS and "HH:mm:ss.fffffff" to TIME_ONLY_FORMATS so that it would look like this.
/// <summary>
/// Convert DateTime to/from String
/// </summary>
public static class DateTimeConverter
{
public const string DATE_TIME_FORMAT_WITH_MILLISECONDS = "{0:yyyyMMdd-HH:mm:ss.fff}";
public const string DATE_TIME_FORMAT_WITHOUT_MILLISECONDS = "{0:yyyyMMdd-HH:mm:ss}";
public const string DATE_ONLY_FORMAT = "{0:yyyyMMdd}";
public const string TIME_ONLY_FORMAT_WITH_MILLISECONDS = "{0:HH:mm:ss.fff}";
public const string TIME_ONLY_FORMAT_WITHOUT_MILLISECONDS = "{0:HH:mm:ss}";
public static string[] DATE_TIME_FORMATS = { "yyyyMMdd-HH:mm:ss.fffffff", "yyyyMMdd-HH:mm:ss.fff", "yyyyMMdd-HH:mm:ss" };
public static string[] DATE_ONLY_FORMATS = { "yyyyMMdd" };
public static string[] TIME_ONLY_FORMATS = { "HH:mm:ss.fffffff", "HH:mm:ss.fff", "HH:mm:ss" };
public static DateTimeStyles DATE_TIME_STYLES = DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal;
public static CultureInfo DATE_TIME_CULTURE_INFO = CultureInfo.InvariantCulture;

Reading integers from AppSettings over and over

Some I do quite a lot of is read integers from AppSettings. What's the best way to do this?
Rather than do this every time:
int page_size;
if (int.TryParse( ConfigurationManager.AppSettings["PAGE_SIZE"], out page_size){
}
I'm thinking a method in my Helpers class like this:
int GetSettingInt(string key) {
int i;
return int.TryParse(ConfigurationManager.AppSettings[key], out i) ? i : -1;
}
but this is just to save some keystrokes.
Ideally, I'd love to put them all into some kind of structure that I could use intellisense with so I don't end up with run-time errors, but I don't know how I'd approach this... or if this is even possible.
What's a best practices way of getting and reading integers from the AppSettings section of the Web.Config?
ONE MORE THING...
wouldn't it be a good idea to set this as readonly?
readonly int pageSize = Helpers.GetSettingInt("PAGE_SIZE") doesn't seem to work.
I've found an answer to my problem. It involves extra work at first, but in the end, it will reduce errors.
It is found at Scott Allen's blog OdeToCode and here's my implementation:
Create a static class called Config
public static class Config {
public static int PageSize {
get { return int.Parse(ConfigurationManager.AppSettings["PAGE_SIZE"]); }
}
public static int HighlightedProductId {
get {
return int.Parse(ConfigurationManager.AppSettings["HIGHLIGHT_PID"]);
}
}
}
Advantage of doing this are three-fold:
Intellisense
One breakpoint (DRY)
Since I only am writing the Config String ONCE, I do a regular int.Parse.
If someone changes the AppSetting Key, it will break, but I can handle that, as those values aren't changed and the performance is better than a TryParse and it can be fixed in one location.
The solution is so simple... I don't know why I didn't think of it before. Call the values like so:
Config.PageSize
Config.HighlightedProductId
Yay!
I know that this question was asked many years ago, but maybe this answer could be useful for someone. Currently, if you're already receiving an IConfiguration reference in your class constructor, the best way to do it is using GetValue<int>("appsettings-key-goes-here"):
public class MyClass
{
private readonly IConfiguration _configuration;
public MyClass(IConfiguration configuration)
{
_configuration = configuration;
}
public void MyMethod()
{
int value = _configuration.GetValue<int>("appsettings-key-goes-here");
}
}
Take a look at T4Config. I will generate an interface and concrete implementation of your appsettings and connectionstringsections of you web/app config using Lazyloading of the values in the proper data types. It uses a simple T4 template to auto generate things for you.
To avoid creating a bicycle class you could use the following:
System.Configuration.Abstractions.AppSettings.AppSetting<int>("intKey");
https://github.com/davidwhitney/System.Configuration.Abstractions

NUnit TestCaseSource pass value to factory

I'm using the NUnit 2.5.3 TestCaseSource attribute and creating a factory to generate my tests. Something like this:
[Test, TestCaseSource(typeof(TestCaseFactories), "VariableString")]
public void Does_Pass_Standard_Description_Tests(string text)
{
Item obj = new Item();
obj.Description = text;
}
My source is this:
public static IEnumerable<TestCaseData> VariableString
{
get
{
yield return new TestCaseData(string.Empty).Throws(typeof(PreconditionException))
.SetName("Does_Reject_Empty_Text");
yield return new TestCaseData(null).Throws(typeof(PreconditionException))
.SetName("Does_Reject_Null_Text");
yield return new TestCaseData(" ").Throws(typeof(PreconditionException))
.SetName("Does_Reject_Whitespace_Text");
}
}
What I need to be able to do is to add a maximum length check to the Variable String, but this maximum length is defined in the contracts in the class under test. In our case its a simple public struct:
public struct ItemLengths
{
public const int Description = 255;
}
I can't find any way of passing a value to the test case generator. I've tried static shared values and these are not picked up. I don't want to save stuff to a file, as then I'd need to regenerate this file every time the code changed.
I want to add the following line to my testcase:
yield return new TestCaseData(new string('A', MAX_LENGTH_HERE + 1))
.Throws(typeof(PreconditionException));
Something fairly simple in concept, but something I'm finding impossible to do. Any suggestions?
Change the parameter of your test as class instead of a string. Like so:
public class StringTest {
public string testString;
public int maxLength;
}
Then construct this class to pass as an argument to TestCaseData constructor. That way you can pass the string and any other arguments you like.
Another option is to make the test have 2 arguments of string and int.
Then for the TestCaseData( "mystring", 255). Did you realize they can have multiple arguments?
Wayne
I faced a similar problem like yours and ended up writing a small NUnit addin and a custom attribute that extends the NUnit TestCaseSourceAttribute. In my particular case I wasn't interested in passing parameters to the factory method but you could easily use the same technique to achieve what you want.
It wasn't all that hard and only required me to write something like three small classes. You can read more about my solution at: blackbox testing with nunit using a custom testcasesource.
PS. In order to use this technique you have to use NUnit 2.5 (at least) Good luck.