source: trunk/bin/module_maker/sql.cli.php @ 323

Last change on this file since 323 was 323, checked in by quinn, 16 years ago

CSS fixes for admin2.inc.css, fixed preselectd but in printSelectForm.

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