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

Last change on this file since 44 was 44, checked in by scdev, 18 years ago

${1}

File size: 6.0 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]\n", basename($_SERVER['argv'][0])));
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 " . addslashes($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] = "'\" . dbArrayToList(\$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            // Toggle types.
78            $c[$field] = "'\" . addslashes(\$auth->getVal('user_id')) . \"'";
79        } else if ('added_datetime' == $field || 'modified_datetime' == $field) {
80            // DB record insertion datetime.
81            $c[$field] = "NOW()";
82        } else {
83            // Default. Just insert data.
84            $c[$field] = "'\" . addslashes(\$frm['$field']) . \"'";
85        }
86    }
87
88} else {
89    die(basename($_SERVER['argv'][0]) . " Warning: $db_tbl does not have any columns.\n");
90}
91
92
93echo isset($op) ? '' : "\n\n\n";
94
95// Insert SQL.
96if (!isset($op) || 'insert' == $op) {
97$insert_skip_columns = array('modified_datetime', 'modified_by_user_id');
98$insert_c = array();
99foreach ($c as $k=>$v) {
100    if (in_array($k, $insert_skip_columns)) {
101        continue;
102    }
103    $insert_c[$k] = $v;
104}
105$db_keys = join(",\n            ", array_keys($insert_c));
106$db_vals = join(",\n            ", $insert_c);
107echo <<<E_O_F
108    // Insert record data.
109    DB::query("
110        INSERT INTO $db_tbl (
111            $db_keys
112        ) VALUES (
113            $db_vals
114        )
115    ");
116E_O_F;
117}
118
119echo isset($op) ? '' : "\n\n\n";
120
121// Update SQL.
122if (!isset($op) || 'update' == $op) {
123$update_skip_columns = array('added_datetime', 'added_by_user_id');
124$comma = '';
125$key_eq_val = '';
126foreach ($c as $k=>$v) {
127    if (in_array($k, $update_skip_columns)) {
128        continue;
129    }
130    $key_eq_val .= $comma . "\n            $k = $v";
131    $comma = ',';
132}
133echo <<<E_O_F
134    // Update record data.
135    DB::query("
136        UPDATE $db_tbl SET$key_eq_val
137        WHERE $primary_key = '" . addslashes(\$frm['$primary_key']) . "'
138    ");
139E_O_F;
140}
141
142echo isset($op) ? '' : "\n\n\n";
143
144// Delete SQL.
145if (!isset($op) || 'delete' == $op) {
146$where_clause = '';
147$delete_skip_columns = array();
148$delim = 'WHERE';
149if (!empty($primary_key)) {
150    $where_clause = "            $delim $primary_key = '\" . addslashes(\$frm['$primary_key']) . \"'\n";
151    $delim = 'AND';
152}
153foreach ($c as $k=>$ignore) {
154    if (in_array($k, $delete_skip_columns)) {
155        continue;
156    }
157    $where_clause .= "            $delim $k = '\" . addslashes(\$frm['$k']) . \"'\n";
158    $delim = 'AND';
159}
160echo <<<E_O_F
161        // Delete record data.
162        DB::query("
163            DELETE FROM $db_tbl
164$where_clause        ");
165E_O_F;
166}
167
168echo isset($op) ? '' : "\n\n\n";
169
170// SortOrder methods SQL.
171if (!isset($op) || 'sortorder' == $op) {
172    echo "// Instantiate a sorting object with the default sort and order. Add SQL for each column.\n";
173    echo "\$so = new SortOrder('$db_tbl.$primary_key', 'DESC');\n";
174    echo "\$so->setColumn('$db_tbl.$primary_key', '$db_tbl.$primary_key ASC', '$db_tbl.$primary_key DESC');\n";
175    foreach ($c as $k=>$v) {
176        echo "\$so->setColumn('$db_tbl.$k', '$db_tbl.$k ASC', '$db_tbl.$k DESC');\n";
177    }
178}
179
180echo isset($op) ? '' : "\n\n\n";
181
182// Search SQL
183if (!isset($op) || 'search' == $op) {
184$search_skip_columns = array('added_datetime', 'added_by_user_id', 'modified_datetime', 'modified_by_user_id', 'publish', 'featured');
185$search_columns = $db_tbl . '.' . join(" LIKE '%\" . addslashes(\$qry_words[\$i]) . \"%'\n                    OR $db_tbl.", array_diff(array_keys($c), $search_skip_columns));
186echo <<<E_O_F
187            \$where_clause .= (empty(\$where_clause) ? 'WHERE' : 'AND') . "
188                (
189                    $search_columns LIKE '%" . addslashes(\$qry_words[\$i]) . "%'
190                )
191            ";
192E_O_F;
193}
194
195
196echo isset($op) ? '' : "\n\n\n";
197?>
Note: See TracBrowser for help on using the repository browser.