Payment terms related functions moved to separate file, common function for calculati...
[fa-stable.git] / includes / db / sql_functions.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 //
13 //      General database functions common for all modules.
14 //
15 //-------------------------------------------------------------------
16 // Multilevel transaction control.
17 //
18 $transaction_level = 0;
19 $transaction_data = null;
20
21 function begin_transaction($func=null, $args=null)
22 {
23         global $transaction_level, $transaction_data, $SysPrefs;
24
25         if (!$transaction_level) {
26                 if ($SysPrefs->db_trail) {
27                         $bt = debug_backtrace();
28                         $user = $_SESSION["wa_current_user"]->user;
29                         $transaction_data = array(
30                                 'user' => $_SESSION["wa_current_user"]->user,
31                                 'msg'=> basename($bt[count($bt)-1]['file']).'@'.$bt[count($bt)-1]['line'], // call start point
32                                 'entry' => $func,
33                                 'data' => serialize($args),
34                         );
35                 }
36                 db_query("BEGIN", "could not start a transaction");
37         }
38         $transaction_level++;
39 }
40
41 function commit_transaction()
42 {
43         global $transaction_level, $transaction_data, $SysPrefs, $db_last_inserted_id, $db;
44
45         $transaction_level--;
46
47         if (!$transaction_level) {
48                 // FIXME: if logged to table remember to preserve last_insert_id!
49                 if ($SysPrefs->db_trail == 1) {
50                         $last_insert = $db_last_inserted_id;
51                         $db_last_inserted_id = mysqli_insert_id($db);   // preserve in case trail insert is done
52                         $sql = "INSERT INTO ".TB_PREF."db_trail (user, msg, entry, data) VALUES ("
53                                         ."'".$transaction_data['user']."','".$transaction_data['msg']."','".$transaction_data['entry']."',"
54                                         .db_escape($transaction_data['data']).")";
55                         db_query($sql, 'cannot log user operation');
56                         $db_last_inserted_id = $last_insert;
57                 } elseif ($SysPrefs->db_trail == 2)
58                         error_log($transaction_data['msg'].'|'.$transaction_data['user'].'|'.$transaction_data['entry'].'|'.$transaction_data['data']);
59                 db_query("COMMIT", "could not commit a transaction");
60         }
61 }
62
63 /*
64         This function is called on end of script execution to cancel
65         all aborted transactions (if any)
66 */
67 function cancel_transaction()
68 {
69         global $transaction_level;
70
71         if ($transaction_level) {
72                 db_query("ROLLBACK", "could not cancel a transaction"); 
73         }
74         $transaction_level = 0;
75 }
76
77 //-----------------------------------------------------------------------------
78 //      Update record activity status.
79 //
80 function update_record_status($id, $status, $table, $key) {
81         $sql = "UPDATE ".TB_PREF.$table." SET inactive = "
82                 . ((int)$status)." WHERE $key=".db_escape($id);
83                 
84         db_query($sql, "Can't update record status");
85 }
86 //-----------------------------------------------------------------------------
87 //
88 //      Helper for sql subquery returning running totals from delta tables like stock_moves or bank_trans
89 //
90 //      $table - table name with optional WHERE clause
91 //  $column - delta column
92 //      $index  - comma delimited list of columns for total grouping and order
93 //  Returns running totals with respective index column
94 //
95 function running_total_sql($table, $column, $index)
96 {
97
98         return "SELECT daily.$index, daily.$column, (@total:=@total+daily.$column) total 
99                 FROM
100                         (SELECT $index, sum($column) $column FROM $table GROUP BY $index ORDER BY $index) daily,
101                         (SELECT @total:=0) total_var";
102 }
103
104 /*
105         Return number of records in tables, where some foreign key $id is used.
106         $id - searched key value
107         $tables - array of table names (without prefix); when table name is used as a key, then
108                 value is name of foreign key field. For numeric keys $stdkey field name is used.
109         $stdkey - standard name of foreign key.
110 */
111 function key_in_foreign_table($id, $tables, $stdkey)
112 {
113
114         if (!is_array($tables))
115                 $tables = array($tables);
116
117         $sqls = array();
118         foreach ($tables as $tbl => $key) {
119                 if (is_numeric($tbl)) {
120                         $tbl = $key;
121                         $key = $stdkey;
122                 }
123                 $sqls[] = "(SELECT COUNT(*) as cnt FROM `".TB_PREF."$tbl` WHERE `$key`=".db_escape($id).")\n";
124         }
125
126         $sql = "SELECT sum(cnt) FROM (". implode(' UNION ', $sqls).") as counts";
127
128         $result = db_query($sql, "check relations for ".implode(',',$tables)." failed");
129         $count = db_fetch($result);
130
131         return $count[0];
132 }
133