KD2 Framework  Check-in [46a273d71c]

Overview
Comment:Add support for ".import" command in import method
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | 7.3
Files: files | file ages | folders
SHA1: 46a273d71c6db6e196c60092a59cd66f087f2a8e
User & Date: bohwaz on 2021-06-28 11:34:02
Other Links: branch diff | manifest | tags
Context
2021-07-16
14:52
Implement multi-level transactions check-in: 26edf3d76d user: bohwaz tags: 7.3
2021-06-28
11:34
Add support for ".import" command in import method check-in: 46a273d71c user: bohwaz tags: 7.3
2021-05-26
19:44
Fix ZipWriter handling of UTF-8 filenames check-in: ee0bb0b61b user: bohwaz tags: 7.3
Changes

Modified src/lib/KD2/DB/SQLite3.php from [8bc9f2f3df] to [d3ed2b5a56].

595
596
597
598
599
600
601
602
603
604

605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624






















625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
				throw new \Exception('Cannot open blob with read/write. Only available from PHP 7.2.0');
			}

			return $this->db->openBlob($table, $column, $rowid, $dbname);
		}
	}

    /**
     * Import a file containing SQL commands
     * Allows to use the statement ".read other_file.sql" to load other files

     * @param  string $file Path to file containing SQL commands
     * @return boolean
     */
    public function import(string $file)
    {
        $sql = file_get_contents($file);
        $sql = str_replace("\r\n", "\n", $sql);
        $sql = preg_split("/\n{2,}/", $sql, -1, PREG_SPLIT_NO_EMPTY);

        $statement = '';
        $i = 0;

        $dir = realpath(dirname($file));

        foreach ($sql as $line) {
            $line = trim($line);

            // Sub-import statements
            if (preg_match('/^\.read (.+\.sql)$/', $line, $match)) {
                $this->import($dir . DIRECTORY_SEPARATOR . $match[1]);






















                $statement = '';
                continue;
            }

            $statement .= $line . "\n";

            if (substr($line, -1) !== ';') {
            	continue;
            }

            try {
                $this->exec($statement);
            }
            catch (\Exception $e) {
                throw new \Exception(sprintf("Error in '%s': %s\n%s", basename($file), $e->getMessage(), $statement), 0, $e);
            }

            $statement = '';
        }

        return true;
    }

    /**
     * Performs a foreign key check and throws an exception if any error is found
     * @return void
     * @throws \LogicException
     * @see https://www.sqlite.org/pragma.html#pragma_foreign_key_check
     */
    public function foreignKeyCheck(): void
    {
    	$result = $this->get('PRAGMA foreign_key_check;');

    	// No error
    	if (!count($result)) {
    		return;
    	}

    	$errors = [];
    	$tables = [];
    	$ref = null;

    	foreach ($result as $row) {
    		if (!array_key_exists($row->table, $tables)) {
    			$tables[$row->table] = $this->get(sprintf('PRAGMA foreign_key_list(%s);', $row->table));
    		}

    		// Findinf the referenced foreign key
    		foreach ($tables[$row->table] as $fk) {
    			if ($fk->id == $row->fkid) {
    				$ref = $fk;
    				break;
    			}
    		}

    		$errors[] = sprintf('%s (%s): row %d has an invalid reference to %s (%s)', $row->table, $ref->from, $row->rowid, $row->parent, $ref ? $ref->to : null);
    	}

    	throw new \LogicException(sprintf("Foreign key check: %d errors found\n", count($errors)) . implode("\n", $errors));
    }

    public function backup($destination, string $sourceDatabase = 'main' , string $destinationDatabase = 'main'): bool
    {
    	if (is_a($destination, self::class)) {
    		$destination = $destination->db;
    	}

    	return $this->db->backup($destination, $sourceDatabase, $destinationDatabase);
    }

	static public function getDatabaseDetailsFromString(string $source_string): array
	{
		if (substr($source_string, 0, 16) !== "SQLite format 3\0" || strlen($source_string) < 100) {
			return null;
		}








|
|
|
>
|
|
|
|
|
|
|
|

|
|

|

|
|

|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|

|

|
|
|

|
|
|
|
|
|

|
|

|
|

|
|
|
|
|
|
|
|
|

|
|
|
|

|
|
|

|
|
|
|

|
|
|
|
|
|
|

|
|

|
|

|
|
|
|
|

|
|







595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
				throw new \Exception('Cannot open blob with read/write. Only available from PHP 7.2.0');
			}

			return $this->db->openBlob($table, $column, $rowid, $dbname);
		}
	}

	/**
	 * Import a file containing SQL commands
	 * Allows to use the statement ".read other_file.sql" to load other files
	 * Also supported is the ".import file.csv table"
	 * @param  string $file Path to file containing SQL commands
	 * @return boolean
	 */
	public function import(string $file)
	{
		$sql = file_get_contents($file);
		$sql = str_replace("\r\n", "\n", $sql);
		$sql = preg_split("/\n{2,}/", $sql, -1, PREG_SPLIT_NO_EMPTY);

		$statement = '';
		$i = 0;

		$dir = realpath(dirname($file));

		foreach ($sql as $line) {
			$line = trim($line);

			// Sub-import statements
			if (preg_match('/^\.read (.+\.sql)$/', $line, $match)) {
				$this->import($dir . DIRECTORY_SEPARATOR . $match[1]);
				$statement = '';
				continue;
			}
			elseif (preg_match('/^\.import (.+\.csv) (\w+)$/', $line, $match)) {
				$fp = fopen($dir . DIRECTORY_SEPARATOR . $match[1], 'r');
				$st = null;

				while ($row = fgetcsv($fp)) {
					if (null === $st) {
						$columns = substr(str_repeat('?, ', count($row)), 0, -2);
						$st = $this->db->prepare(sprintf('INSERT INTO %s VALUES (%s);', $this->quoteIdentifier($match[2]), $columns));
					}

					foreach ($row as $i => $value) {
						$st->bindValue($i + 1, $value);
					}

					$st->execute();
					$st->reset();
					$st->clear();
				}

				$statement = '';
				continue;
			}

			$statement .= $line . "\n";

			if (substr($line, -1) !== ';') {
				continue;
			}

			try {
				$this->exec($statement);
			}
			catch (\Exception $e) {
				throw new \Exception(sprintf("Error in '%s': %s\n%s", basename($file), $e->getMessage(), $statement), 0, $e);
			}

			$statement = '';
		}

		return true;
	}

	/**
	 * Performs a foreign key check and throws an exception if any error is found
	 * @return void
	 * @throws \LogicException
	 * @see https://www.sqlite.org/pragma.html#pragma_foreign_key_check
	 */
	public function foreignKeyCheck(): void
	{
		$result = $this->get('PRAGMA foreign_key_check;');

		// No error
		if (!count($result)) {
			return;
		}

		$errors = [];
		$tables = [];
		$ref = null;

		foreach ($result as $row) {
			if (!array_key_exists($row->table, $tables)) {
				$tables[$row->table] = $this->get(sprintf('PRAGMA foreign_key_list(%s);', $row->table));
			}

			// Findinf the referenced foreign key
			foreach ($tables[$row->table] as $fk) {
				if ($fk->id == $row->fkid) {
					$ref = $fk;
					break;
				}
			}

			$errors[] = sprintf('%s (%s): row %d has an invalid reference to %s (%s)', $row->table, $ref->from, $row->rowid, $row->parent, $ref ? $ref->to : null);
		}

		throw new \LogicException(sprintf("Foreign key check: %d errors found\n", count($errors)) . implode("\n", $errors));
	}

	public function backup($destination, string $sourceDatabase = 'main' , string $destinationDatabase = 'main'): bool
	{
		if (is_a($destination, self::class)) {
			$destination = $destination->db;
		}

		return $this->db->backup($destination, $sourceDatabase, $destinationDatabase);
	}

	static public function getDatabaseDetailsFromString(string $source_string): array
	{
		if (substr($source_string, 0, 16) !== "SQLite format 3\0" || strlen($source_string) < 100) {
			return null;
		}