Cyclic Dependency in Formik Yup Schema - formik

I have 5 fields field1...field5 in my formik form.I am using Yup for schema validation. Only one of field1, field2,field3 are mandatory at a given time. Field4 and Field5 have independent validations which do not have any dependency of other fields whatsoever. I have figured a way of writing
schema = Yup.object().shape({
field1: Yup.string().when(['field2', 'field3'], {
is: (field2, field3) => !field2 && !field3,
then: Yup.string().required()
}),
field2: Yup.string().when(['field1', 'field3'], {
is: (field1, field3) => !field1 && !field3,
then: Yup.string().required()
}),
field3: Yup.string().when(['field1', 'field2'], {
is: (field1, field2) => !field1 && !field2,
then: Yup.string().required()
}),
field4: Yup.string().max(30, "Maximum 30 characters are allowed").required("This is a mandatory field"),
field5: Yup.string().max(30, "Maximum 30 characters are allowed").required("This is a mandatory field")
}
,[['field1', 'field2'], ['field1', 'field3'], ['field2','field3']]
)
Please observe field4 and field5 are not mentioned in the second last line since they are not dependent on other fields. I mentioned field1,field2,field3 on the second last line since without it, the schema throws a cyclic dependency issue.
My Question is: Is the placement of field4 and field5 correct in the below schema.

Related

computed selected field not present in response

I have this model in gorm with 2 fields which I do not want inside the table as they are computed from the sql query:
type User struct {
ID uint `json:"id" gorm:"primarykey,autoIncrement"`
MutedUsers []*User `json:"-" gorm:"many2many:user_muted_users;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
BlockedUsers []*User `json:"-" gorm:"many2many:user_blocked_users;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
...
IsMuted bool `json:"is_muted" gorm:"-"`
IsBlocked bool `json:"is_blocked" gorm:"-"`
}
Query which computes above fields:
var users []models.User
userMutedQ := database.Instance.
Table("user_muted_users").
Select("1").
Where("user_id = ? and muted_user_id = u.id", 1)
userBlockedQ := database.Instance.
Table("user_blocked_users").
Select("1").
Where("user_id = ? and blocked_user_id = u.id", 1)
database.Instance.
Table("users u").
Select("u.*, "+
"(case when exists(?) then 'true' else 'false' end) as is_muted, "+
"(case when exists(?) then 'true' else 'false' end) as is_blocked, ",
userMutedQ, userBlockedQ,
).
Where("u.id = 1").
Scan(&users)
The sql from the console, when run against the database will produce columns with the right value for is_muted is_blocked (some true some false).
The users list however, have all values for is_muted is_blocked to false. Maybe gorm is ignoring them due to the - flag definition. If I don't use - then gorm will create is_muted is_blocked columns inside my database which are totally redundant since the value is always computed.
What is the right way here?
According to docs (Declaring Models/Field-Level Permission) and new feature (Add field tag to ignore migration and PR), you can use migration directive for - tag to ignore field creation during migration and use -> to readonly field permission:
IsBlocked bool `gorm:"->;-:migration"`

How to properly escape parameters for JSONB deep query in node-postgres

When bypassing an ORM and doing direct queries to node-postgres, there are a nice pile of weird edge issues to keep in mind. For example, you have probably already encountered the fact that camelCaseColumns have to be in double-quotes, and also parameterized type casting…
client.query(`SELECT id, "authorFirstName", "authorLastName" FROM books WHERE isbn = $1::int`, [1444723448]`)
client.query(`SELECT id FROM books WHERE "authorLastName" = $1::string`, ['King']`)
JSON and JSONB types add another aspect of weirdness. The important thing to keep in mind is, "$1" is not merely a variable placeholder; it is an indicator of a discrete unit of information.
Given a table where characters is a column of type JSONB, this will not work…
client.query(
`SELECT id FROM books WHERE characters #> ([ {'name': $1::string} ])`,
['Roland Deschain']
)
This fails because the unit of information is the JSON object, not a string you're inserting into a blob of text.
This is a little more clear when one looks at a simpler SELECT and an UPDATE…
const userData = await client.query(
`SELECT characters FROM books WHERE id = $1::uuid`,
[ some_book_id ]
)
const newCharacters = JSON.stringify([
...userData[0].characters,
{ name: 'Jake' },
{ name: 'Eddie' },
{ name: 'Odetta' }
])
await this.databaseService.executeQuery(
`UPDATE books SET characters = $1::jsonb WHERE id = $2::uuid`,
[ newCharacters, some_book_id ]
)
The deep search query should be formed thusly:
const searchBundle = JSON.stringify([
{'name': 'Roland Deschain'}
])
client.query(
`SELECT id FROM books WHERE characters #> ($1::jsonb)`,
[searchBundle]
)

CASE WHEN conditional in HiveQL

I'm having trouble bringing a case then into HiveQL.
I have a column with data:
if column is NULL = FALSE
if the column is PEOPLE = TRUE. It returns all results as TRUE.
What's wrong with my role?
SELECT
id,
datetime,
CASE
WHEN tb_people !="" THEN 'TRUE'
ELSE 'FALSE'
END
FROM <BD>.<TABLE>
!="" is only checking for blank strings. "" and NULL are two different things. As such, what you're looking for is:
SELECT
id,
datetime,
CASE
WHEN tb_people IS NOT NULL THEN 'TRUE'
ELSE 'FALSE'
END
FROM <BD>.<TABLE>
I'd also recommend using the boolean true and false rather than string literals. This would let you replace your entire case statement with ifnotnull(tb_people) https://hive.apache.org/javadocs/r3.0.0/api/org/apache/hadoop/hive/ql/exec/vector/expressions/IsNotNull.html.

Setting Linq2Db to read and update with CHAR type and NOT NULL constraint in Oracle

Reading value of fixed CHAR string from table, using Linq2db Oracle provider:
CREATE TABLE mytable
(pk NUMBER(15,0) NOT NULL,
fixed_data CHAR(20) DEFAULT ' ' NOT NULL)
Although in database, length of FIXED_DATA filed is 20,
SELECT LENGTH(fixed_data) FROM mytable WHERE pk = 1
-- result is 20
When same field is read using Linq2Db, value gets truncated to empty string:
var row = (from row in database.mytable where row.pk == 1 select row).ToList()[0];
Console.WriteLine(row.fixed_data.Length);
// result is zero
This causes problem when record is updated using Linq2Db, Oracle converts empty string to NULL, and UPDATE fails:
database.Update(row);
// Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01407: cannot update ("MYSCHEMA"."MYTABLE"."FIXED_DATA") to NULL
Is there any setting in Linq2Db for read->update cycle to work with CHAR type and NOT NULL constraint?
Found a solution, thanks to source code openly available. By default, Linq2Db calls expression IDataReader.GetString(int).TrimEnd(' ') on every CHAR and NCHAR column. However this can be easily customized, by implementing custom provider, which overrides field value retrieval expression, with one that does not trim:
class MyOracleProvider : OracleDataProvider
{
public MyOracleProvider(string name)
: base(name)
{
// original is SetCharField("Char", (r,i) => r.GetString(i).TrimEnd(' '));
SetCharField("Char", (r, i) => r.GetString(i));
// original is SetCharField("NChar", (r,i) => r.GetString(i).TrimEnd(' '));
SetCharField("NChar", (r, i) => r.GetString(i));
}
}

RethinkDB filter array, return only matched values

I have a table like this
{
dummy: [
"new val",
"new val 2",
"new val 3",
"other",
]
}
want to get only matched values to "new", I am using query like this:
r.db('db').table('table')('dummy').filter(function (val) {
return val.match("^new")
})
but its giving error
e: Expected type STRING but found ARRAY in
what is wrong with query, if I remove .match("^new"), it returns all values
Thanks
The reason of why you're getting Expected type STRING but found ARRAY in is that the value of the dummy field is an array itself, and you cannot apply match to arrays.
Despite the filter you tried may look confusing, you have to rethink your query a bit: just remap the array to a new ^new-keyed array, and then just filter its values out in an inner expression.
For example:
r.db('db')
.table('table')
.getField('dummy')
.map((array) => array.filter((element) => element.match("^new")))
Output:
[
"new val" ,
"new val 2" ,
"new val 3"
]

Resources