Browse Source

sp generation

develop
Robin Thoni 8 years ago
parent
commit
d87d104e08
4 changed files with 135 additions and 202 deletions
  1. 67
    118
      src/Generator/LuGenerator.php
  2. 22
    80
      src/Generator/templates/sp.php.twig
  3. 14
    4
      test/generate.php
  4. 32
    0
      test/test.php

+ 67
- 118
src/Generator/LuGenerator.php View File

@@ -2,6 +2,8 @@
2 2
 
3 3
 namespace Luticate\Generator;
4 4
 
5
+use Luticate\Utils\DataAccess\AbstractDbDataAccess;
6
+use Luticate\Utils\DataAccess\PgSqlDataAccess;
5 7
 use PDO;
6 8
 use Twig_Autoloader;
7 9
 use Twig_Environment;
@@ -58,17 +60,16 @@ class LuGenerator {
58 60
         $this->_config = $config;
59 61
     }
60 62
 
61
-    public function __construct()
63
+    public function __construct($database)
62 64
     {
63
-        $dsn = getenv("DB_CONNECTION") . ":dbname=" . getenv("DB_DATABASE") . ";host="
64
-            . getenv("DB_HOST") . ";port=" . getenv("DB_PORT");
65
-        $this->_pdo = new PDO($dsn, getenv("DB_USERNAME"), getenv("DB_PASSWORD"));
65
+        $dsn = $database["driver"] . ":dbname=" . $database["database"] . ";host="
66
+            . $database["host"] . ";port=" . $database["port"];
67
+        $this->_pdo = new PDO($dsn, $database["username"], $database["password"]);
66 68
     }
67 69
 
68
-    protected function printError($query, $message)
70
+    protected function printError($message)
69 71
     {
70 72
         echo $message . "\n";
71
-        var_dump($query->errorInfo());
72 73
         var_dump($this->_pdo->errorInfo());
73 74
         return null;
74 75
     }
@@ -108,60 +109,15 @@ class LuGenerator {
108 109
         $content = $template->render($twig_vars);
109 110
         file_put_contents($destFile, $content);
110 111
     }
111
-
112
-    public function getTables()
113
-    {
114
-        $tablesQuery = $this->_pdo->prepare("SELECT table_name
115
-FROM information_schema.tables
116
-WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')");
117
-        if ($tablesQuery->execute(array())) {
118
-            $tables = $tablesQuery->fetchAll();
119
-            echo "Found " . count($tables) . " tables\n";
120
-            return $tables;
121
-        }
122
-        else
123
-            return $this->printError($tablesQuery, "Failed to get tables");
124
-    }
125
-
126
-    public function getColumns($table_name)
127
-    {
128
-        $columnsQuery = $this->_pdo->prepare("SELECT column_name as name, data_type as data_type FROM information_schema.columns WHERE table_name = :table_name");
129
-        if ($columnsQuery->execute(array(":table_name" => $table_name)))
130
-        {
131
-            $columns = $columnsQuery->fetchAll();
132
-            echo "Found " . count($columns) . " columns in table " . $table_name . "\n";
133
-            return $columns;
134
-        }
135
-        else
136
-            return $this->printError($columnsQuery, "Failed to get columns from " . $table_name);
137
-    }
138
-
139
-    public function sqlTypeToPhpType($type)
140
-    {
141
-        if ($type == "character" || $type == "character varying" || $type == "char"
142
-            || $type == "varchar" || $type == "bytea") {
143
-            return "string";
144
-        }
145
-        if ($type == "bigint" || $type == "bigserial" || $type == "serial8" || $type == "serial2"
146
-            || $type == "serial4" || $type == "int8" || $type == "int2" || $type == "integer" || $type == "smallint") {
147
-            return "integer";
148
-        }
149
-        if ($type == "decimal" || $type == "real" || $type == "double precision" || $type == "float8") {
150
-            return "double";
151
-        }
152
-        if ($type == "bit" || $type == "bit varying" || $type == "varbit" || $type == "boolean" || $type == "bool") {
153
-            return "boolean";
154
-        }
155
-        return $type;
156
-    }
157
-
112
+    
158 113
     public function sqlTypesToPhpTypes($array)
159 114
     {
115
+        $db = $this->getDbDataAccess();
160 116
         foreach ($array as $key => $value)
161 117
         {
162 118
             $array[$key]["data_type"] = array(
163 119
                 "sql" => $array[$key]["data_type"],
164
-                "php" => $this->sqlTypeToPhpType($array[$key]["data_type"])
120
+                "php" => $db->sqlTypeToPhpType($array[$key]["data_type"])
165 121
             );
166 122
         }
167 123
         return $array;
@@ -177,61 +133,26 @@ WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'informat
177 133
         $this->buildTwig('dbo_array.php', $fileArray, $vars);
178 134
     }
179 135
 
180
-    public function getStoredProcedures()
136
+    public function generateSp($sp, $file, $spFile, $dboName, $dboFile, $dboFileArray)
181 137
     {
182
-        $spQuery = $this->_pdo->prepare("SELECT r.routine_name AS sp_name, r.data_type AS data_type, proc.proretset AS proretset, proc.prosrc AS prosrc
183
-FROM information_schema.routines r
184
-LEFT JOIN pg_catalog.pg_proc proc ON proc.proname = r.routine_name
185
-WHERE r.specific_schema='public'");
186
-        if ($spQuery->execute())
187
-        {
188
-            $sp = $spQuery->fetchAll();
189
-            echo "Found " . count($sp) . " stored procedures\n";
190
-            return $sp;
191
-        }
192
-        else
193
-            return $this->printError($spQuery, "Failed to get stored procedures");
194
-    }
195
-
196
-    public function getStoredProceduresArguments($sp)
197
-    {
198
-        $sp_name = $sp["sp_name"];
199
-        $spQuery = $this->_pdo->prepare("SELECT parameters.parameter_name as name, parameters.data_type, parameters.parameter_mode
200
-FROM information_schema.routines
201
-JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
202
-WHERE routines.specific_schema='public' AND routines.routine_name = :sp_name
203
-ORDER BY parameters.ordinal_position;");
204
-        if ($spQuery->execute(array("sp_name" => $sp_name)))
205
-        {
206
-            $sp_ = $spQuery->fetchAll();
207
-            $sps = array("in" => array(), "out" => array());
208
-            foreach ($sp_ as $p)
209
-                $sps[strtolower($p["parameter_mode"])][] = $p;
210
-            $out_count = count($sps['out']);
211
-            if ($out_count == 0)
212
-            {
213
-                $sps['out'][] = array(
214
-                    "name" => $sp_name,
215
-                    "data_type" => $sp["data_type"],
216
-                    "parameter_mode" => "OUT"
217
-                );
218
-                $out_count = 1;
219
-            }
220
-            echo "Found " . count($sps['in']) . " input arguments for stored procedure " . $sp_name . "\n";
221
-            echo "Found " . $out_count . " output arguments for stored procedure " . $sp_name . "\n";
222
-            return $sps;
138
+        file_put_contents($spFile, $sp["sp"]["prosrc"]);
139
+        $args = [];
140
+        $db = $this->getDbDataAccess();
141
+        foreach ($sp['args']['out'] as $arg) {
142
+            $args[] = [
143
+                "name" => $arg["name"],
144
+                "data_type" => [
145
+                    "php" => $db->sqlTypeToPhpType($arg["data_type"]),
146
+                    "sql" => $arg["data_type"]
147
+                ]
148
+            ];
223 149
         }
224
-        else
225
-            return $this->printError($spQuery, "Failed to get arguments for stored procedure " . $sp_name);
226
-    }
227
-
228
-    public function generateSp($sp, $args, $file, $spFile)
229
-    {
230
-        $vars = array(
231
-            "sp" => $sp,
232
-            "args" => $args
233
-        );
234
-        file_put_contents($spFile, $sp["prosrc"]);
150
+        $this->generateDbo($dboName, $args, $dboFile, $dboFileArray);
151
+        $vars = [
152
+            "args" => $sp["args"],
153
+            "sp" => $sp["sp"],
154
+            "dboName" =>  $dboName
155
+        ];
235 156
         $this->buildTwig('sp.php', $file, $vars);
236 157
     }
237 158
 
@@ -310,16 +231,14 @@ ORDER BY parameters.ordinal_position;");
310 231
 
311 232
         $tables = $this->getTables();
312 233
         if (!is_null($tables)) {
313
-            foreach ($tables as $table) {
314
-                $table_name = $table["table_name"];
234
+            echo "Found " . count($tables) . " tables\n";
235
+            foreach ($tables as $table_name => $columns) {
315 236
                 if ($this->matchIgnore("tables", $table_name)) {
316 237
                     echo "Table $table_name ignored\n";
317 238
                     continue;
318 239
                 }
319
-                $columns = $this->getColumns($table_name);
320
-                if (is_null($columns))
321
-                    continue;
322 240
                 $columns = $this->sqlTypesToPhpTypes($columns);
241
+                echo "Found " . count($columns) . " columns in table " . $table_name . "\n";
323 242
                 $baseName = LuStringUtils::snakeToCamelCase($table_name, true);
324 243
                 $dboName = $baseName . "Dbo";
325 244
                 $dataAccessName = $baseName . "DataAccess";
@@ -338,24 +257,54 @@ ORDER BY parameters.ordinal_position;");
338 257
                     $controller_dir . $controllerName . ".php");
339 258
             }
340 259
         }
260
+        else {
261
+            $this->printError("Failed to get tables");
262
+        }
341 263
         $sps = $this->getStoredProcedures();
342 264
         if (!is_null($sps)) {
343
-            foreach ($sps as $sp)
265
+            echo "Found " . count($sps) . " stored procedures\n";
266
+            foreach ($sps as $sp_name => $sp)
344 267
             {
345
-                $sp_name = $sp["sp_name"];
346 268
                 if ($this->matchIgnore("sp", $sp_name)) {
347 269
                     echo "Stored procedure $sp_name ignored\n";
348 270
                     continue;
349 271
                 }
350
-                $args = $this->getStoredProceduresArguments($sp);
351
-                if (is_null($args))
352
-                    continue;
272
+                $args = $sp["args"];
273
+                echo "Found " . count($args['in']) . " input and " .
274
+                    count($args['out']) . " output arguments in stored procedure " . $sp_name . "\n";
353 275
                 $args["in"] = $this->sqlTypesToPhpTypes($args["in"]);
354 276
                 $args["out"] = $this->sqlTypesToPhpTypes($args["out"]);
355 277
                 $sp_model_name = LuStringUtils::snakeToCamelCase($sp_name, true);
356
-                $this->generateSp($sp, $args, $sp_dir . $sp_model_name . ".php", $sp_src_dir . $sp_name . ".sql");
278
+                $dboName = $sp_model_name . "Dbo";
279
+                $this->generateSp($sp, $sp_dir . $sp_model_name . ".php", $sp_src_dir . $sp_name . ".sql", $dboName,
280
+                    $dbo_dir . $dboName . ".php", $dbo_dir . $dboName . "Array.php");
357 281
             }
358 282
         }
283
+        else {
284
+            $this->printError("Failed to get stored procedures");
285
+        }
286
+    }
287
+
288
+    public function getStoredProcedures()
289
+    {
290
+        return $this->getDbDataAccess()->getStoredProceduresFull($this->_pdo);
291
+    }
292
+
293
+    public function getTables()
294
+    {
295
+        return $this->getDbDataAccess()->getTablesFull($this->_pdo);
296
+    }
297
+
298
+    /**
299
+     * @return AbstractDbDataAccess|null
300
+     */
301
+    public function getDbDataAccess()
302
+    {
303
+        $driver = $this->_pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
304
+        if ($driver == "pgsql") {
305
+            return new PgSqlDataAccess();
306
+        }
307
+        return null;
359 308
     }
360 309
 }
361 310
 

+ 22
- 80
src/Generator/templates/sp.php.twig View File

@@ -7,30 +7,15 @@
7 7
 
8 8
 namespace {{ sp_namespace.as_it }};
9 9
 
10
-use Luticate\Utils\LuSpDbo;
11
-use Luticate\Utils\LuMultipleDbo;
12
-use Luticate\Utils\LuStringUtils;
13
-use Illuminate\Support\Facades\DB;
14
-
15
-class {{ sp.sp_name.camel_upper }} extends LuSpDbo {
16
-
17
-    /**
18
-    * @param $dam
19
-    * @return \{{ sp_namespace.as_it }}\{{ sp.sp_name.camel_upper }}|null
20
-    */
21
-    protected static function damToDbo($dam)
22
-    {
23
-        if (is_null($dam))
24
-            return null;
25
-        $dbo = new {{ sp.sp_name.camel_upper }}();
26
-
27
-{% for arg in args.out %}
28
-        $dbo->set{{ arg.name.camel_upper }}(LuStringUtils::convertJsonString($dam->{{ arg.name.as_it }}));
29
-{% endfor %}
30
-
31
-        return $dbo;
32
-    }
10
+use Luticate\Utils\DataAccess\LuStoredProcedure;
11
+use Luticate\Utils\Dbo\LuMultipleDbo;
12
+use Luticate\Utils\Business\LuStringUtils;
13
+use Luticate\Utils\Business\LuArrayUtils;
14
+use Illuminate\Database\Capsule\Manager as Capsule;
15
+use {{ dbo_namespace.as_it }}\{{ dboName.camel_upper }};
16
+use {{ dbo_namespace.as_it }}\{{ dboName.camel_upper }}Array;
33 17
 
18
+class {{ sp.sp_name.camel_upper }} extends LuStoredProcedure {
34 19
 {% set spcall %}{{ sp.sp_name.as_it }}({% for arg in args.in %}:{{ arg.name.as_it }}{{ loop.last ? "" : ", " }}{% endfor %}){% endset %}
35 20
 {% set argsarray %}{% for arg in args.in %}":{{ arg.name.as_it }}" => ${{ arg.name.as_it }}{{ loop.last ? "" : ", " }}{% endfor %}{% endset %}
36 21
 
@@ -38,18 +23,22 @@ class {{ sp.sp_name.camel_upper }} extends LuSpDbo {
38 23
 {% for arg in args.in %}
39 24
     * @param ${{ arg.name.as_it }} {{ arg.data_type.php.as_it }}
40 25
 {% endfor %}
41
-    * @return \{{ sp_namespace.as_it }}\{{ sp.sp_name.camel_upper }}{% if sp.proretset %}[]{% endif %};
26
+    * @return {{ dboName.camel_upper }}{% if sp.proretset %}[]{% endif %}
42 27
     */
43 28
     public static function execute({% for arg in args.in %}${{ arg.name.as_it }}{{ loop.last ? "" : ", " }}{% endfor %})
44 29
     {
45
-        $values = DB::select('SELECT {% for arg in args.out %}to_json(data.{{ arg.name.as_it }}) AS {{ arg.name.as_it }}{{ loop.last ? "" : ", " }}{% endfor %} FROM {{ spcall }} data', array({{ argsarray }}));
30
+        $values = static::getConnection()->select('SELECT {% for arg in args.out %}to_json(data.{{ arg.name.as_it }}) AS {{ arg.name.as_it }}{{ loop.last ? "" : ", " }}{% endfor %} FROM {{ spcall }} data', array({{ argsarray }}));
31
+
46 32
 {% if sp.proretset %}
47 33
         $dboValues = array();
48
-        foreach ($values as $value)
49
-            $dboValues[] = self::damToDbo($value);
34
+        foreach ($values as $value) {
35
+            $json = LuArrayUtils::objectToArray($value);
36
+            $dboValues[] = {{ dboName.camel_upper }}::jsonDeserialize($json);
37
+        }
50 38
         return $dboValues;
51 39
 {% else %}
52
-        return self::damToDbo($values[0]);
40
+        $json = LuArrayUtils::objectToArray($values[0]);
41
+        return {{ dboName.camel_upper }}::jsonDeserialize($json);
53 42
 {% endif %}
54 43
     }
55 44
 
@@ -60,67 +49,20 @@ class {{ sp.sp_name.camel_upper }} extends LuSpDbo {
60 49
 {% endfor %}
61 50
     * @param $page int The page number, 0 based
62 51
     * @param $perPage int The number of items per page
63
-    * @return \Luticate\Utils\LuMultipleDbo;
52
+    * @return LuMultipleDbo
64 53
     */
65 54
     public static function getMultipleJson({% for arg in args.in %}${{ arg.name.as_it }}, {% endfor %}$page, $perPage)
66 55
     {
67
-        $values = DB::select('SELECT (SELECT count(*) FROM {{ spcall }}) as count, (SELECT json_agg(q) FROM (SELECT * FROM {{ spcall }} OFFSET (:page::int * :perPage::int) LIMIT :perPage) q) as data',
56
+        $values = static::getConnection()->select('SELECT (SELECT count(*) FROM {{ spcall }}) as count, (SELECT json_agg(q) FROM (SELECT * FROM {{ spcall }} OFFSET (:page::int * :perPage::int) LIMIT :perPage) q) as data',
68 57
             array({{ argsarray }}, ":page" => $page, ":perPage" => $perPage));
69 58
         $value = $values[0];
70 59
         if (is_null($value->data))
71 60
         {
72 61
             $value->data = '[]';
73 62
         }
74
-        $data = LuStringUtils::convertJsonString($value->data);
75
-        return new LuMultipleDbo($value->count, $data);
63
+        $json = LuStringUtils::convertJsonString($value->data);
64
+        $data = {{ dboName.camel_upper }}Array::jsonDeserialize($json);
65
+        return new LuMultipleDbo($value->count, $data->getArray());
76 66
     }
77 67
 {% endif %}
78
-
79
-    public function jsonSerialize()
80
-    {
81
-        return array(
82
-{% for arg in args.out %}
83
-            "{{ arg.name.camel_upper }}" => $this->_{{ arg.name.camel_lower }}{{ loop.last ? "" : "," }}
84
-{% endfor %}
85
-        );
86
-    }
87
-
88
-    public static function jsonDeserialize($json)
89
-    {
90
-        $dbo = new {{ sp.sp_name.camel_upper }}();
91
-{% for arg in args.out %}
92
-        if (isset($json["{{ arg.name.camel_upper }}"])) {
93
-            $dbo->set{{ arg.name.camel_upper }}($json["{{ arg.name.camel_upper }}"]);
94
-        }
95
-{% endfor %}
96
-        return $dbo;
97
-    }
98
-
99
-    public static function generateSample()
100
-    {
101
-        $dbo = new {{ sp.sp_name.camel_upper }}();
102
-{% for arg in args.out %}
103
-        $dbo->set{{ arg.name.camel_upper }}({% if arg.data_type.php.as_it == "double" %}42.42{%
104
-elseif arg.data_type.php.as_it == "integer" %}42{%
105
-elseif arg.data_type.php.as_it == "boolean" %}true{%
106
-else %}"sample string"{% endif %});
107
-{% endfor %}
108
-        return $dbo;
109
-    }
110
-
111
-{% for arg in args.out %}
112
-
113
-    /**
114
-    * @var {{ arg.data_type.php.as_it }}
115
-    */
116
-    protected $_{{ arg.name.camel_lower }};
117
-    public function get{{ arg.name.camel_upper }}()
118
-    {
119
-        return $this->_{{ arg.name.camel_lower }};
120
-    }
121
-    public function set{{ arg.name.camel_upper }}($value)
122
-    {
123
-        $this->_{{ arg.name.camel_lower }} = $value;
124
-    }
125
-{% endfor %}
126 68
 }

+ 14
- 4
test/generate.php View File

@@ -10,9 +10,19 @@ use Luticate\Generator\LuGenerator;
10 10
 
11 11
 require_once('../vendor/autoload.php');
12 12
 
13
-Dotenv::load("..");
13
+$config = ['databases' => [
14
+    [
15
+        'name'      => 'mydb',
16
+        'driver'    => 'pgsql',
17
+        'host'      => '172.17.0.1',
18
+        'port'      => 5432,
19
+        'database'  => 'intra_betaclean',
20
+        'username'  => 'dev',
21
+        'password'  => 'dev'
22
+    ]
23
+]];
14 24
 
15
-$gen = new LuGenerator();
25
+$gen = new LuGenerator($config['databases'][0]);
16 26
 
17 27
 echo "\n\nDEFAULT\n\n";
18 28
 
@@ -20,8 +30,8 @@ $gen->run();
20 30
 
21 31
 $gen->setConfig(array("dbo" =>
22 32
     array(
23
-        "namespace" => 'Luticate\Package\DBO',
24
-        "folder" => 'generated/Package/DBO'
33
+        "namespace" => 'Luticate\Package\Dbo',
34
+        "folder" => 'generated/Package/Dbo'
25 35
     ),
26 36
     "models" =>
27 37
         array(

+ 32
- 0
test/test.php View File

@@ -0,0 +1,32 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: robin
5
+ * Date: 6/10/16
6
+ * Time: 3:09 PM
7
+ */
8
+
9
+
10
+use Luticate\Package\DataAccess\SP\SpGetAddresses;
11
+use Luticate\Utils\Controller\LuticateApplication;
12
+
13
+require_once "../vendor/autoload.php";
14
+
15
+require_once "generated/Package/DataAccess/SP/SpGetAddresses.php";
16
+require_once "generated/Package/Dbo/SpGetAddressesDbo.php";
17
+require_once "generated/Package/Dbo/SpGetAddressesDboArray.php";
18
+
19
+$config = ['databases' => [
20
+    [
21
+        'name'      => 'mydb',
22
+        'driver'    => 'pgsql',
23
+        'host'      => '172.17.0.1',
24
+        'database'  => 'intra_betaclean',
25
+        'username'  => 'dev',
26
+        'password'  => 'dev'
27
+    ]
28
+]];
29
+$app = new LuticateApplication($config);
30
+$app->setupDatabases();
31
+
32
+var_dump(SpGetAddresses::execute(""));

Loading…
Cancel
Save