Skip to content

Commit

Permalink
docs
Browse files Browse the repository at this point in the history
  • Loading branch information
rodber committed Jan 12, 2024
1 parent d831080 commit 7537dcd
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 24 deletions.
81 changes: 69 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,82 @@
[![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=chevere_sql2p&metric=sqale_index)](https://sonarcloud.io/dashboard?id=chevere_sql2p)
[![CodeFactor](https://www.codefactor.io/repository/github/chevere/sql2p/badge)](https://www.codefactor.io/repository/github/chevere/sql2p)

## Quick start
## Summary

SQL2P generates [Parameters](https://chevere.org/library/parameter) for MySQL schemas.

From a `CREATE TABLE` statement like this:

```SQL
CREATE TABLE `invoice` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`client_id` INT UNSIGNED NOT NULL,
`datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`details` LONGTEXT NULL,
`quantity` INT UNSIGNED NOT NULL,
`rate` DECIMAL(10,2) NOT NULL,
`total` DECIMAL(19,4) GENERATED ALWAYS AS (quantity*rate),
PRIMARY KEY (`id`)
ENGINE = InnoDB;
```

It generates the following PHP code:

```php
use Chevere\Parameter\Interfaces\ArrayParameterInterface;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\datetime;
use function Chevere\Parameter\float;
use function Chevere\Parameter\int;
use function Chevere\Parameter\null;
use function Chevere\Parameter\string;
use function Chevere\Parameter\union;

function invoiceTable(): ArrayParameterInterface
{
return arrayp(
id: int(min: 0),
client_id: int(min: 0),
datetime: datetime(),
details: union(
null(),
string()
),
quantity: int(min: 0),
rate: float(),
total: float()
);
}
```

## Installing

SQL2P is available through [Packagist](https://packagist.org/packages/chevere/sql2p) and the repository source is at [chevere/sql2p](https://github.com/chevere/sql2p).

```sh
composer require chevere/sql2p
```

## Creating SQL2P

Create a `SQL2P` instance by passing the SQL and a [WriterInterface](https://chevere.org/packages/writer) instance. On instance creation the SQL is parsed and the writer is used to write the generated code.

```php
use Chevere\SQL2P\SQL2P;
use Chevere\Writer\StreamWriter;
use function Chevere\Filesystem\fileForPath;
use function Chevere\Writer\streamFor;

$sql = fileForPath(__DIR__ . '/schema.sql')->getContents();
$output = fileForPath(__DIR__ . '/sql2p.php');
$output->createIfNotExists();
$stream = streamFor($output->path()->__toString(), 'w');
$writer = new StreamWriter($stream);
$head = <<<PHP
declare(strict_types=1);

namespace SmartCrop\Schema;
$schema = __DIR__ . '/schema.sql';
$output = __DIR__ . '/sql2p.php';
$header = <<<PHP
namespace MyNamespace;
PHP;
$sql2p = new SQL2P($sql, $writer, $head);
$sql = file_get_contents($schema);
file_put_contents($output, '');
$stream = streamFor($output, 'w');
$writer = new StreamWriter($stream);
$sql2p = new SQL2P($sql, $writer, $header);
$count = count($sql2p);
echo <<<PLAIN
[{$count} tables] {$output->path()}
Expand All @@ -46,7 +103,7 @@ PLAIN;

## Documentation

Documentation is available at [chevere.org](https://chevere.org/).
Documentation is available at [chevere.org](https://chevere.org/packages/sql2p).

## License

Expand Down
26 changes: 15 additions & 11 deletions src/SQL2P.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ final class SQL2P implements Countable
public const HEADER = <<<'PHP'
<?php
%HEAD%
%HEADER%
use Chevere\Parameter\Interfaces\ArrayParameterInterface;
use function Chevere\Parameter\arrayp;
Expand All @@ -66,19 +66,23 @@ final class SQL2P implements Countable

private int $count = 0;

/**
* @param string $sql SQL to parse containing CREATE TABLE statements
* @param string $header Header to use after the opening PHP tag `<?php`
*/
public function __construct(
string $sql,
private WriterInterface $writer,
private string $head = '',
private WriterInterface $output,
private string $header = '',
) {
$header = str_replace('%HEAD%', $this->head, self::HEADER);
$this->writer->write($header);
$header = str_replace('%HEADER%', $this->header, self::HEADER);
$this->output->write($header);
$parser = new SQLParser();
$tables = $parser->parse($sql);
foreach ($tables as $table) {
$this->writeTable($table);
}
$this->writer->write(
$this->output->write(
<<<PHP
// @codeCoverageIgnoreEnd
Expand All @@ -97,7 +101,7 @@ private function writeTable(array $table): void
{
$tableName = $table['name'];
$nameCamel = $this->snakeToCamel($tableName) . 'Table';
$this->writer->write(
$this->output->write(
<<<PHP
function {$nameCamel}(): ArrayParameterInterface
Expand All @@ -109,10 +113,10 @@ function {$nameCamel}(): ArrayParameterInterface
foreach ($columns as $pos => $column) {
$this->writeColumn($tableName, $column);
if ($pos !== count($columns) - 1) {
$this->writer->write(',');
$this->output->write(',');
}
}
$this->writer->write(
$this->output->write(
<<<PHP
);
Expand Down Expand Up @@ -157,7 +161,7 @@ private function writeColumn(string $table, array $column): void
}
}
$arguments = implode(', ', $arguments);
$code = match ($column['null']) {
$code = match ($column['null'] ?? false) {
true => <<<PHP
union(
null(),
Expand All @@ -168,7 +172,7 @@ private function writeColumn(string $table, array $column): void
{$function}({$arguments})
PHP
};
$this->writer->write(
$this->output->write(
<<<PHP
{$columnName}: {$code}
Expand Down
3 changes: 2 additions & 1 deletion tests/src/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ CREATE TABLE IF NOT EXISTS `company_employee` (
`comments_made_total` INT NOT NULL DEFAULT 0,
`login_method` ENUM('email', 'badge') NULL DEFAULT NULL,
`email` VARCHAR(255) NULL DEFAULT NULL,
`deleted_at` TIMESTAMP NULL DEFAULT NULL
`hours_total` DECIMAL(19,4) GENERATED ALWAYS AS (seconds_total/3600),
`deleted_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1 change: 1 addition & 0 deletions tests/src/sql2p.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ enum('email', 'badge')
null(),
string(regex: "/^.{0,255}$/")
),
hours_total: float(),
deleted_at: union(
null(),
int()
Expand Down

0 comments on commit 7537dcd

Please sign in to comment.