Run a query each time a database connection is opended Zend FM - php

Is it possible to execute a query every time a new connection to the database is open. This query needs to be run immediately after opening a database connection because this query calls a stored procedure that sets up various access control on the tables using the details of the user who requested to run the query. I have tried to call this stored procedure in various places and they are all successful but I would like some feedback.
I have put this query in an abstract mapper class which other mappers extend. Each time a new mapper is instantiated the stored procedure is called.
Another place to put this call to the stored procedure is before calls to other mapper methods. The downside of this is that there will a lot of duplicate code (code that calls the stored procedure).
The final place to put this call is in Bootstrap.php. Each _init method in this file is suppose to run only once each time the application is loaded. I have decided to put this call to the stored procedure in one of the Bootstrap.php for one of our modules. This is so far the best place I can think of because I only have to write the code that calls the stored procedure once and each time the application is accessed the initialize method will run. The downside of this is that I do not know the side affects of putting things in Bootstrap.php.
One of the main downsides of all these places is that the stored procedure gets called many times. For the access control to work, the stored procedure needs to be called only once per database session. This will not cause any issue other than speed due to unnecessary calls.
Are there any better places to put this call to the stored procedure? Does Zend FM have this feature implemented somewhere? Is there anything I need to take into consideration if I put this in the Bootstrap file.
Thanks for reading this and any help provided.
DB2 Version 10.5
Linux Platform
Zend FM Version 2

As an alternative, you can configure this on the database side by setting the database configuration parameter connect_proc to the name of your stored procedure. Note that the procedure will then be called for all connections, remote and local, including those made by the database administrator.
If you need to pass extra information from the client to the connect_proc routine, you could use the client accounting string connection parameter, which you could then read in the procedure using the MON_GET_CONNECTION() function:
SET acct_string = (
SELECT client_acctng FROM TABLE (
MON_GET_CONNECTION(MON_GET_APPLICATION_HANDLE(),-1)
)
)

Related

Passing database object in PHP functions

Not sure if appropriate but here goes.
I have build a small system for online reservations of slots during a day.
Because I use a database and connect to it all the time to run some queries I created a simple class that creates the connection (using PDO) and running queries (preparing them, running them, if an error happens it manages and logs it, etc).
I also use AJAX a lot so basically, when a user wants to register, log in, get the schedule of the day, book a slot, cancel a booking and so one, I use AJAX to load a script that goes through the procedure for each action (I will call this the AJAX script) and in that script I include the relevant script that contains all the functions needed (I will call this the function script). The idea is that the AJAX script just gets the parameters, calls a list of functions which based on the results returns some kind of response. The function script contain all the code, that builds the queries, and gets the database data, makes any checks, creates new objects if needed etc.
The way I was doing it was that in the start of the AJAX script I create my database class instance and then just pass it through to the functions as needed (Mostly because I started with all the code in the AJAX script and then moved to creating the separate function in the second script and just leaving the minimum code needed to guide the action)...
So my question is, is it a good/better practise to remove the database class instance all together from the AJAX script and instead include the database class script in the function script and just instantiate inside each function? I am wondering about the idea of creating connections along with each function and then destroying them (most of the functions are small and usually have one query or two , there are some that have a lot in which i use transactions).
I have read about using a singleton as well but I am not sure how it would work in the web. My understanding is if there 2 users logged in the site and both try to fetch the schedule, then the script is called once for each user, making a diffrent connection - even if the parameters of the connection are the same ( I have a guest_user with select/insert/update privileges in my database). So even if I had a singleton, then I would still have two separate connection in the above scenario right? Hoever the difference is as I have it now I would have two connections, open for 1 sec but with change I ask about I would have 10 for each user let's say (10 functions called) for 100ms each time... Is this good or bad? Can it cause problems (if I extrapolate this to real world, with say 1000 users, usually 20-40 at the same time on the site)...
What about security, can these connections be used to steal the data that are exchanged (okay this is farfetched and not really an issue, the data are relatively harmless, other than phones but...)

What are the benefits of creating Stored Procedures in SQL and MySQL?

I have a theoretical question.
I can't see any difference between declaring a function within a PHP file and creating a stored procedure in a database that does the same thing.
Why would I want to create a stored procedure to, for example, return a list of all the Cities for a specific Country, when I can do that with a PHP function to query the database and it will have the same result?
What are the benefits of using stored procedures in this case? Or which is better? To use functions in PHP or stored procedures within the database? And what are the differences between the two?
Thank you.
Some benefits include:
Maintainability: you can change the logic in the procedure without needing to edit app1, app2 and app3 calls.
Security/Access Control: it's easier to worry about who can call a predefined procedure than it is to control who can access which tables or which table rows.
Performance: if your app is not situated on the same server as your DB, and what you're doing involves multiple queries, using a procedure reduces the network overhead by involving a single call to the database, rather than as many calls as there are queries.
Performance (2): a procedure's query plan is typically cached, allowing you to reuse it again and again without needing to re-prepare it.
(In the case of your particular example, the benefits are admittedly nil.)
Short answer would be if you want code to be portable, don't use stored procedures because if you will want at some point change database for example from MySQL to PostgreSQL you will have to update/port all stored procedures you have written.
On the other hand, sometimes you can achieve better performance results using stored procedures because all that code will run by database engine. You also can make situation worse if stored procedures will be used improperly.
I dont think that selecting country is very expensive operation. So I guess you don't have to use stored procedures for this case.
As most of the guys already explained it, but still i would try to reiterate in my own way
Stored Procedures :
Logic resides in the database.
Lets say some query which we need to execute, then we can do that either by :
Sending the query to DataBase server from client, where it will be parsed, compiled and then executed.
The other way is stationing the query at DataBase server and create an aliasing for the query, which client will use to send the request to database server and when recieved at server it will be executed.
So we have :
Client ----------------------------------------------------------> Server
Conventional :
Query created #Client ---------- then propagate to Server ----------Query : Reached server : Parse, Compiled , execute.
Stored Procedures :
Alias is Created, used by Client----------------then propogate to Server-------- Alias reached at Server : Parse,Compiled, Cached (for the first Time)
Next time same alias comes up, execute the query executable directly.
Advantages :
Reduce Network Traffic : If client is sending a big query, and may be using the same query very frequently then every bit of the query is send to the network and hence which may increase the network traffic and unnecessary increase the network usage.
Faster Query Execution : Since stored procedures are Parsed, Compiled at once, and the executable is cached in the Database. Therefore if same query is
repeated multiple times then Database directly executes the executable and hence Time is saved in Parse,Compile etc. This is good if query is used frequently.
If query is not used frequently, then it might not be good, because storing cached executable takes space, why to put Load on Database unnecessarily.
Modular : If multiple applications wants to use the same query, then with traditional way you are duplicating code unnecessarily at applications, the best
way is to put the code close to Database, this way duplication can be alleviated easily.
Security: Stored procedures are also developed, keeping in mind about Authorization(means who is privileged to run the query and who is not).So for a specific user you can grant permissions, to others you as DBA can revoke the permission. So its a good way as a point wrt to DBAs a DBA you can know who are right persons to get the access.But such things are not that popular now, you can design your Application Database such that only authorized person can access it and not all.
So if you have only Security/Authorization as the point to use Stored Procedures instead of Conventional way of doing things, then Stored procedure might not be appropriate.
ok, this may be a little oversimplified (and possibly incomplete):
With a stored procedure:
you do not need to transmit the query to the database
the DBMS does not need to validate the query every time (validate in a sense of syntax, etc)
the DBMS does not need to optimize the query every time (remember, SQL is declarative, therefore, the DBMS has to generate an optimized query execution plan)

Amending the CodeIgniter Active Record Query command?

I am developing a Codeigniter (2.0.2) Application, which will utilise a Master database for all write operations (INSERT/UPDATE/DELETE) and a read replica for all read operations (SELECT).
Now I know I can access two different database objects within the code to route the individual requests to the specific database server, but i'm thinking there has a better way, automated way. I'll be using MySQL and Active Record, and also want to build in Memcache checking - although it won't be used immediately, I'd like the option there for the future, built in at this stage.
I'm thinking if its possible to add a hook/library of some kind to intercept the $this->db->query so that the following happens:
1) SQL Query received
2) Check if SELECT query
2a) If SELECT, see if Memcache is active, if so encode SQL and check Memcache for response.
2b) If no memcache response, or Memcache is not active, execute query as normal through READ MySQL server.
3) Query was NOT select, so execute query as normal through the WRITE MySQL server.
4) Return response.
I'm sure that looking at this, it should be quite simple to do, but no matter how I look at it i'm just not seeing a potential answer - but there's got to be one! Can anyone help/assist?
In addition, I also want the ability to be able to log all write SQL commands for troubleshooting, presumably the best way is to introduce 3a) Write SQL command to plain text file ... into the above scheme. I don't believe MySQL actually logs the non-SELECT queries in anyway ... does it?
That type of behavior is a little bit beyond the normal scope of CI. Unfortunately, your best bet is to manually extend the database drivers, specifically override the function simple_query or _execute (simple_query is a wrapper around _execute which simply ensures initialization). That is really the only place where you can guarantee that you can catch all of the queries and branch the logic accordingly. (You may also want to override close as that is the cleanup script)
(Personally, I would have a the SELECT DB load a secondary DB into itself and just call $write_db->simple_query conditionally, that seems like it would be the least trouble).

CodeIgniter - only connect to database if there is a query to run

At the moment I load the database class in my autoload which automatically creates a connection to mysql. If there are no queries it will have still created a connection.
For performance I only want to connect to mysql if a query has been run.
What would be the best way to achieve this?
I am thinking of writing a model function that all queries run through which detects if the database has been connected to or not, and simply calls $this->load->database() if not before running $this->db->query().
The problem with this is that I would have to change all of my $this->db->query() references in my code which is a pain.
Ideally I would like to extend the $this->db->query() function to support this.
Any ideas?
You can modify the autoinit property of your database config
$db['mydb']['autoinit'] = false;
This will cause you database class to not initialize (which include connecting to the server) when instantiated, it will instead happen when the first query occurs.
See the database configuration page

Can I call DB:connect without affecting the currently active DB?

I'm trying to merge to php code bases which each use a different DB. Can I call DB::connect which changing which DB is considered active? Or can I save the active DB and restore it after calling connect?
Edit: The problem is one code base uses mysql_query() without providing $link_identifier, and I don't want to change all the calls, but I still want to be able to open a 2nd DB connection. Right now it works depending on the order in which I connect to the DBs, which is a pain.
DB::connect creates a connection resource. You can connect to many different databases/servers at the same time. The connection resource contains the database being used. Just store the returned connection reference in different variables and you will be fine.
Connecting to more than one database at the same time is actually very common. For example, connecting to a slave DB for SELECTs and master DB for INSERTs, UPDATEs and DELETEs.
When you create a new connection to the DB, a resource link is usually returned or stored as a member of the DB wrapper class or whatever. You MUST use this link (stored in a variable, for instance) each time you call query functions, etc. If you do not specify a link, the last opened link will be used instead which could be disastrous. If you are diligent about using the correct created link, however, then there will be no problem at all.

Categories