Handling undefined variables in Fabrik Joomla - joomla

I have a database join field with a WHERE condition in Fabrik (Joomla). The field gets its content from tableA. The WHERE condition needs one variable from the URL {queryParam}.
This is the WHERE condition:
WHERE EXISTS (SELECT 1 FROM tableB WHERE {thistable}.id = tableB.selected AND tableB.parent_id = {queryParam})
The issue with this is, that queryParam of course is not always defined which then breaks the whole application since the SQL query is invalid.
I'm not very familiar with Fabrik and Joomla. What would a good practice be to handle this issue? I know, that without queryParam the SQL query will always return nothing. Is there a way to check if queryParam is set and If it's not to prevent the SQL query from running?
Or can I set a default for queryParam (e.g 0, which also will always lead to no results)
I've already looked through the Fabrik wiki, forum and Joomla posts but couldn't find any useful information.
Environment: Joomla 3.9.4, Fabrik 3.x

Related

JPA add a condition to every single query automatically

Before anything, i must say this first: This table design is not my decision. We protest but to no avail, so please don't tell me, don't create a table like that.
We have a database with each table have a flag. This flag used to indicate which environment this row belong to, production or test data.
For server side, we have one variable which currently stored in ThreadLocal to indicate which environment this request belong to, same value as the flag in database.
Our requirement is that if my request belong to test environment then we must select only record belong to this environment. We would need to add a condition to every query we made to database, something like:
SELECT t FROM TABLE t WHERE t.flag = :environment
But we have to update every single query, update every object to set this flag before insert/update into database. This will require a lot of effort as our system already built long ago, not on progress. Also this will bring a lots of risk if someone forgot to add this to any new query.
So is there anyway to insert a condition to check this flag value for every query without have to manually edit the query string? Like an interceptor or something to put this condition in?
Which JPA provider?
With Hibernate, you could try using a #Filter.
Multitenancy could be another option, but probably an overkill in your scenario.
Finally, since you flagged the question with Oracle, perhaps the easiest approach would be to provide dedicated schemas (per environment) with views for every single table in your db, filtered by the flag column. Not sure if you're allowed to do that, though.
With some of the above, you would need a global entity listener to populate the flag field of your entities before they are persisted.

Using two different slugs on a route

I'm upgrading an old procedural site to laravel 5.2, and I'm struggling with the old routes I made.
On this website, the routes were made like this : {user_slug}/{content_slug}.html. For the moment, I use cviebrock/eloquent-sluggable to generate the slugs, but I'm open to another one if this one cannot meet my needs.
I have two questions :
Can I make the content-slug unique, but per user ?
How can I write the route and the controller in order to match the correct user slug ad the correct content slug ?
I have not done this myself but I believe there would be a way in the validation rules to do this. Here is an untested rough draft to check content_slug in the posts table but only check uniqueness where the user_id field equals a variable:
'content_slug' => "unique:posts,content_slug,NULL,id,user_id,$user->id"
Depending on who you ask, they may advise you (either instead of or as well as doing the above) to set up a key in the database based on the user_id and content_slug fields. This way the database returns an error if an insert is attempted as well as gives a performance boost when running a query off that index. Queries off of an index can literally give an exponential performance increase.

mutual exclusion in joomla

I created an extension for joomla using:
$id=$database->insertid();
I just covered that if two users are logged on to the site will fit together perform two records in the database and then this statement will return in both cases the same value.
in php you can solve this problem with the transactions.
In joomla how do I solve this problem?
If you have a table you are working with that extends JTable then make sure that you included the check out functionality that is optionally a part of that. THis must means adding a couple of fields like what is in the content table. This will prevent two people from editing the same row at the same time which creates a race condition in which one of the other will lose their data.
Please note that both php and joomla functions to return the last insert id rely on the mysql implementation, and mysql returns the last id inserted on the currently open connection so concurrency is not an issue
#iacoposk8 Your are right it might possible that in very rear case. Such time try to add current logged in user id in your sql query or any where so that it doesn't make any confict. I hope you get it what i want to say. Thanks

Using Oracle's GUID()-generated ID's in Grails/Hibernate

I trying to use Grails Scaffolding to throw a quick CRUD application together around some legacy database tables. It is an Oracle database, and the primary key value is intended to be populated by Oracle's GUID() function.
Based on this earlier StackOverflow question, I tried specifying "guid" as the Hibernate generator for this column in my Grails domain class:
...
static mapping = {
table name: "OWNER"
version false
columns {
id column: "OWNER_OID", generator: "guid"
name column: "NAME"
...
}
}
...
When I run my Grails app, viewing and even editing records works just fine. However, when I try to create a new record, things blow up with the Oracle error message "ORA-02289: sequence does not exist".
I enabled SQL logging for my datasource, and see Grails/Hibernate trying to execute the following during a save operation:
select hibernate_sequence.nextval from dual
This doesn't look right at all, and doesn't match the generated SQL from that earlier StackOverflow question linked above. Does anyone see something I am missing here, or otherwise know how to make Grails/Hibernate populate a primary key column with Oracle GUID values?
Whew... after another day of wrestling with this, I think I have my arms around the thing. This answer covers a bit more ground than the original question description, but that's because I found yet more problems after getting past the Hibernate generator issue.
Issue #1: Getting an Oracle GUID() value
As covered by Adam Hawkes' answer, the "guid" Hibernate generator is unmaintained and only works for older versions of the Oracle dialect.
However, if you use the Hibernate generator "assigned" (meaning that you want to set primary keys manually rather than have Hibernate auto-generate them), then you can insert values pulled from an Oracle SYS_GUID() call.
Even though Hibernate's newer Oracle dialects don't support "guid" seamlessly, they still understand the SQL necessary to generate these values. If you are inside of a Controller, you can fetch that SQL query with the following:
String guidSQL = grailsApplication.getMainContext().sessionFactory.getDialect().getSelectGUIDString()
If you are inside of a domain class instead, you can still do this... but you will need to first inject a reference to grailsApplication. You probably want to do this in a Controller, though... more on this below.
If you're curious, the actual String returned here (for Oracle) is:
select rawtohex(sys_guid()) from dual
You can execute this SQL and fetch the generated ID value like this:
String guid = grailsApplication.getMainContext().sessionFactory.currentSession.createSQLQuery(guidSQL).list().get(0)
Issue #2: Actually using this value in a Grails domain object
To actually use this GUID value in your Grails domain class, you need to use the Hibernate generator "assigned". As mentioned earlier, this declares that you want to set your own ID's manually, rather than letting Grails/GORM/Hibernate generate them automatically. Compare this modified code snippet to the one in my original question above:
...
static mapping = {
table name: "OWNER"
version false
id column: "OWNER_OID", generator: "assigned"
name column: "NAME"
...
}
...
In my domain class, I changed "guid" to "assigned". I also found that I needed to eliminate the "columns {}" grouping block, and move all my column information up a level (weird).
Now, in whichever Controller is creating these domain objects... generate a GUID as described above, and plug it into the object's "id" field. In a Controller generated automatically by Grails Scaffolding, the function will be "save()":
def save() {
def ownerInstance = new Owner(params)
String guidSQL = grailsApplication.getMainContext().sessionFactory.getDialect().getSelectGUIDString()
ownerInstance.id = grailsApplication.getMainContext().sessionFactory.currentSession.createSQLQuery(guidSQL).list().get(0)
if (!ownerInstance.save(flush: true, insert: true)) {
render(view: "create", model: [ownerInstance: ownerInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'owner.label', default: 'Owner'), ownerInstance.id])
redirect(action: "show", id: ownerInstance.id)
}
You might think to try putting this logic directly inside the domain object, in a "beforeInsert()" function. That would definitely be cleaner and more elegant, but there are some known bugs with Grails that prevent ID's from being set in "beforeInsert()" properly. Sadly, you'll have to keep this logic at the Controller level.
Issue #3: Make Grails/GORM/Hibernate store this properly
The plain truth is that Grails is primarily intended for virgin-new applications, and its support for legacy databases is pretty spotty (in fairness, though, it's a bit less spotty than other "dynamic" frameworks I've tried). Even if you use the "assigned" generator, Grails sometimes gets confused when it goes to persist the domain object.
One such problem is that a ".save()" call sometimes tries to do an UPDATE when it should be doing an INSERT. Notice that in the Controller snippet above, I have added "insert: true" as a parameter to the ".save()" call. This tells Grails/GORM/Hibernate explicitly to attempt an INSERT operation rather than an UPDATE one.
All of the stars and planets must be in alignment for this to work right. If your domain class "static mapping {}" block does not set the Hibernate generator to "assigned", and also set "version false", then Grails/GORM/Hibernate will still get confused and try to issue an UPDATE rather than an INSERT.
If you are using auto-generated Grails Scaffolding controllers, then it is safe to use "insert: true" in the Controller's "save()" function, because that function in only called when saving a new object for the first time. When a user edits an existing object, the Controller's "update()" function is used instead. However, if you are doing your own thing in your own custom code somewhere... it will be important to check on whether a domain object is already in the the database before you make a ".save()" call, and only pass the "insert: true" parameter if it really is a first-time insert.
Issue #4: Using natural keys with Grails/GORM/Hibernate
One final note, not having to do with Oracle GUID values, but related to these Grails issues in general. Let's say that in a legacy database (such as the one I've been dealing with), some of your tables use a natural key as their primary key. Say you have an OWNER_TYPE table, containing all the possible "types" of OWNER, and the NAME column is both the human-readable identifier as well as the primary key.
You'll have to do a couple of other things to make this work with Grails Scaffolding. For one thing, the auto-generated Views do not show the ID field on the screen when users are creating new objects. You will have to insert some HTML to the relevant View to add a field for the ID. If you give the field a name of "id", then the auto-generated Controller's "save()" function will receive this value as "params.id".
Secondly, you have to make sure that the auto-generated Controller's "save()" function properly inserts the ID value. When first generated, a "save()" starts off by instantiating a domain object from the CGI parameters passed by the View:
def ownerTypeInstance = new OwnerType.get( params )
However, this does not handle the ID field you added to your View. You will still need to set that manually. If on the View you gave the HTML field a name of "id", then it will be available in "save()" as "params.id":
...
ownerTypeInstance = new OwnerType()
ownerTypeInstance.id = params.id
// Proceed to the ".save()" step, making sure to pass "insert: true"
...
Piece of cake, huh? Perhaps "Issue #5" is figuring out why you put yourself through all this pain, rather than just writing your CRUD interface by hand with Spring Web MVC (or even vanilla JSP's) in the first place! :)
Support for using SYS_GUID() is dependent upon the Oracle dialect that you are using. Looking at the hibernate source on GitHub it appears that the dialect was only setup to use the Oracle-generated guid in Oracle9Dialect.java and Oracle8iDialect.java. Therefore, it won't work with the 9i or 10g dialects.
You should submit a patch to hibernate which will add the required function(s) to enable the same functionality as the other dialects.

Codeigniter and nested tab markup

I need some guidance. Forgive me for a lengthy post but I need to explain myself. In my world, there is no one who understands what I am talking about so I have to go online for assistance.
I am an architect doing my own website because work has dried up and I plan to use an improved website for a marketing campaign.
I have done what I'd call a "lash-up" of this site which functions OK. But it's nowhere near ready to publish. I am trying to get it reorganised to do this and am moving the whole thing over to Codeigniter. My puzzle relates to views in Codeigniter.
One of the main pages for potential clients is the projects page showing work done. It uses nested tabbing. As I have said, I've made it work OK in ordinary procedural PHP.
Note that the projects are organised by category i.e housing, commercial etc In each category there are projects.
Actually the tabs are dynamically produced with some assistance from jQuery. I mean by this that my homespun php creates markup based on what's returned from the database.
The tab markup is the usual one of an unordered list whose li elements contain anchors whose hrefs reference divs arranged below. To achieve nesting, these divs then contain another ul with a further set of divs related to it.
The top tabs correspond to a category e.g housing, commercial. The lower tabs correspond to projects within a category.
I've made this work with four queries before. I think at least one may be redundant but I said it was a "lash-up".
Query 1: "select distinct pcat, pcatid from pcategory inner join projects on pcatid = projcat order by pcat desc"
From this query I get hold of the id used in the href.
Query 2 : same as above but this time the id is used for div id.
The next query is the source of my puzzlement because I don't see how to replicate it with CI.
Query3 :
$jobcat=$row2['pcatid'];
$queryall3 = "select projid, projtit, projcost, projdate from projects where projcat= '$jobcat'";
This query uses the category id - $jobcat - returned by each iteration of the while clause used to expand the results from query 2. In other words, it runs inside the query 2 while loop so it can get the category id and then get all the projects related to it.
The results of query 3 are used to form the lower tabs, and their href value is the id of the project.
Query4: same as query 3 and used to populate the lower divs with data from the database relating to a specific project.
So, finally my question: it seems to me that query 3 is difficult to manage using the Codeigniter set up. I can imagine an array of results looped over in a view. What I can't conceive is how to make a model call within that loop.
Apologies for a long-winded question and any maladroit coding assumptions exhibited. Assistance would be a blessing.
Tom
I don't really see what you're asking, but it seems that you want to know how to perform queries in CI?
In which case I suggest you take a good read of the docs
$this->db->select('pcat, pcatid');
$this->db->distinct();
$this->db->from('pcategory');
$this->db->join('projects', 'pcategory.pcatid = projects.pid', 'inner');
$this->db->order_by('pcat', 'DESC');
$result = $this->db->get();
I very much doubt this will work as I do not know your table structure but may give you an idea of how to use the active record class in CI.
You can of course just use the query method:
$results = $this->db->query('YOUR QUERY HERE');
the active record class can do a lot of the work for you, however.
As for about being difficult to do in CI, this is simply untrue - you just need a clearer picture and understanding of what you want to achieve.
Edit
$jobcat=$row2['pcatid'];
$queryall3 = "select projid, projtit, projcost, projdate from projects where projcat= '$jobcat'";
$results=$this->db->query($queryall3);
$data = $results->result_array(); // get the results of the 3rd query as an array
// new query
$this->db->select('query_4_select'); // select whatever you need
$this->db->from('whatever_table');
// this probably isn't the most efficient way, but for examples sake:
foreach($data as $row) // using the result_array from above
{
$this->db->or_where('query_4_id', $row['id']); // the magic !!
}
$new_results = $this->db->get();
So essentially, you get the ID's from query 3, run it through a foreach and build a where x=x or x=y or x=b type query, which will then (hopefully) return the desired results.
This is one way, you will need to tweak it.
But it sounds like you can just use a join? Perhaps if you could post your entire tables structure.

Resources