source: tags/2.1.5/bin/module_maker/sql.cli.php @ 377

Last change on this file since 377 was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

File size: 7.1 KB
Line 
1#!/usr/local/bin/php -q
2<?php
3/**
4 * The Strangecode Codebase - a general application development framework for PHP
5 * For details visit the project site: <http://trac.strangecode.com/codebase/>
6 * Copyright 2001-2010 Strangecode, LLC
7 *
8 * This file is part of The Strangecode Codebase.
9 *
10 * The Strangecode Codebase is free software: you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License as published by the
12 * Free Software Foundation, either version 3 of the License, or (at your option)
13 * any later version.
14 *
15 * The Strangecode Codebase is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * details.
19 *
20 * You should have received a copy of the GNU General Public License along with
21 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/**
25 * sql.cli.php
26 */
27
28include_once dirname(__FILE__) . '/_config.inc.php';
29
30$op = null;
31$valid_ops = array('sortorder', 'insert', 'update', 'delete', 'search', 'filter');
32
33// Test arguments.
34if (isset($_SERVER['argv'][2])) {
35    // Second arg is db table.
36    $db_tbl = $_SERVER['argv'][2];
37} else {
38    die(sprintf("Usage: %s site_directory db_table [operation]\nValid operations include: %s", basename($_SERVER['argv'][0]), join(', ', $valid_ops)));
39}
40
41// Test for operation.
42if (isset($_SERVER['argv'][3])) {
43    // Optional third arg is op.
44    $op = $_SERVER['argv'][3];
45    // Make sure op is valid.
46    if (!in_array($op, $valid_ops)) {
47        die(basename($_SERVER['argv'][0]) . " Warning: Operation '$op' is not something I know how to do Please select one of: " . join(", ", $valid_ops) . "\n");
48    }
49}
50
51// Get DB tables.
52$qid = $db->query("SHOW TABLES");
53while (list($row) = mysql_fetch_row($qid)) {
54    $tables[] = $row;
55}
56
57// Make sure requested table is in database.
58if (!in_array($db_tbl, $tables)) {
59    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
60}
61
62// Make sure op is valid.
63if (isset($op) && !in_array($op, $valid_ops)) {
64    die(basename($_SERVER['argv'][0]) . " Warning: Operation '$op' is not something I know how to do Please select one of: " . join(", ", $valid_ops) . "\n");
65}
66
67// Get DB table column info.
68$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
69while ($row = mysql_fetch_row($qid)) {
70    $cols[] = $row;
71}
72
73$sort_columns = '';
74$primary_key = '__///__';
75
76// Loop through columns
77if (is_array($cols) && !empty($cols)) {
78    foreach ($cols as $col) {
79
80        // Human readable.
81        $field = $col[0];
82        $type = preg_replace('/^(\w+).*$/', '\\1', $col[1]);
83        $is_primary_key = ('PRI' == $col[3]);
84
85        $sort_columns .= "\$so->setColumn('$field', '$field ASC', '$field DESC');\n";
86
87        if ($is_primary_key) {
88            // This is the primary key. Deal with separately.
89            $primary_key = $field;
90        } else if ('set' == $type) {
91            // Set types usually need to be converted to comma-delimited lists.
92            $c[$field] = "'\" . escapedList(array_keys(\$frm['$field'])) . \"'";
93        } else if ('featured' == $field || 'publish' == $field || preg_match("/enum\('true'\)/", $col[1])) {
94            // Toggle types.
95            $c[$field] = "'\" . isset(\$frm['$field']) . \"'";
96        } else if ('added_by_user_id' == $field || 'modified_by_user_id' == $field) {
97            // Expects a user_id.
98            $c[$field] = "'\" . \$db->escapeString(\$auth->get('user_id')) . \"'";
99        } else if ('added_datetime' == $field || 'modified_datetime' == $field) {
100            // DB record insertion datetime.
101            $c[$field] = "NOW()";
102        } else if (preg_match('/date_|_date/', $field)) {
103            // This is a date field. Convert to SQL date.
104            $c[$field] = "'\" . \$db->escapeString(strToSQLDate(\$frm['$field'])) . \"'";
105        } else {
106            // Default. Just insert data.
107            $c[$field] = "'\" . \$db->escapeString(\$frm['$field']) . \"'";
108        }
109    }
110
111} else {
112    die(basename($_SERVER['argv'][0]) . " Warning: $db_tbl does not have any columns.\n");
113}
114
115
116echo isset($op) ? '' : "\n\n\n";
117
118// Insert SQL.
119if (!isset($op) || 'insert' == $op) {
120$insert_skip_columns = array('modified_datetime', 'modified_by_user_id');
121$insert_c = array();
122foreach ($c as $k=>$v) {
123    if (in_array($k, $insert_skip_columns)) {
124        continue;
125    }
126    $insert_c[$k] = $v;
127}
128$db_keys = join(",\n            ", array_keys($insert_c));
129$db_vals = join(",\n            ", $insert_c);
130echo <<<E_O_F
131    // Insert record data.
132    \$db->query("
133        INSERT INTO $db_tbl (
134            $db_keys
135        ) VALUES (
136            $db_vals
137        )
138    ");
139E_O_F;
140}
141
142echo isset($op) ? '' : "\n\n\n";
143
144// Update SQL.
145if (!isset($op) || 'update' == $op) {
146$update_skip_columns = array('added_datetime', 'added_by_user_id');
147$comma = '';
148$key_eq_val = '';
149foreach ($c as $k=>$v) {
150    if (in_array($k, $update_skip_columns)) {
151        continue;
152    }
153    $key_eq_val .= $comma . "\n            $k = $v";
154    $comma = ',';
155}
156echo <<<E_O_F
157    // Update record data.
158    \$db->query("
159        UPDATE $db_tbl SET$key_eq_val
160        WHERE $primary_key = '" . \$db->escapeString(\$frm['$primary_key']) . "'
161    ");
162E_O_F;
163}
164
165echo isset($op) ? '' : "\n\n\n";
166
167// Delete SQL.
168if (!isset($op) || 'delete' == $op) {
169$where_clause = '';
170$delete_skip_columns = array();
171$delim = 'WHERE';
172if (!empty($primary_key)) {
173    $where_clause = "            $delim $primary_key = '\" . \$db->escapeString(\$frm['$primary_key']) . \"'\n";
174    $delim = 'AND';
175}
176foreach ($c as $k=>$ignore) {
177    if (in_array($k, $delete_skip_columns)) {
178        continue;
179    }
180    $where_clause .= "            $delim $k = '\" . \$db->escapeString(\$frm['$k']) . \"'\n";
181    $delim = 'AND';
182}
183echo <<<E_O_F
184        // Delete record data.
185        \$db->query("
186            DELETE FROM $db_tbl
187$where_clause        ");
188E_O_F;
189}
190
191echo isset($op) ? '' : "\n\n\n";
192
193// SortOrder methods SQL.
194if (!isset($op) || 'sortorder' == $op) {
195    echo "// Instantiate a sorting object with the default sort and order. Add SQL for each column.\n";
196    echo "\$so = new SortOrder('$db_tbl.$primary_key', 'DESC');\n";
197    echo "\$so->setColumn('$db_tbl.$primary_key', '$db_tbl.$primary_key ASC', '$db_tbl.$primary_key DESC');\n";
198    foreach ($c as $k=>$v) {
199        echo "\$so->setColumn('$db_tbl.$k', '$db_tbl.$k ASC', '$db_tbl.$k DESC');\n";
200    }
201}
202
203echo isset($op) ? '' : "\n\n\n";
204
205// Search SQL
206if (!isset($op) || 'search' == $op) {
207$search_skip_columns = array('added_datetime', 'added_by_user_id', 'modified_datetime', 'modified_by_user_id', 'publish', 'featured');
208$search_columns = $db_tbl . '.' . join(" LIKE '%\" . \$db->escapeString(\$qry_words[\$i]) . \"%'\n                    OR $db_tbl.", array_diff(array_keys($c), $search_skip_columns));
209echo <<<E_O_F
210            \$where_clause .= (empty(\$where_clause) ? 'WHERE' : 'AND') . "
211                (
212                    $search_columns LIKE '%" . \$db->escapeString(\$qry_words[\$i]) . "%'
213                )
214            ";
215E_O_F;
216}
217
218
219echo isset($op) ? '' : "\n\n\n";
220?>
Note: See TracBrowser for help on using the repository browser.