schema
schema.paths = [ dirpath , path, ... ]
seeds = [ script path ]
data_source
data_source{ ds id } = {
dsn => ...,
user => ,
pass =>
connection_options => { ... pdo connection options },
query_options => {
quote_column => true,
quote_table => true,
}
}
bootstrap = [ script path, script path ]
$config->load();
$config->init();
$config->initForBuild(); // for build command.
public function init(ConfigLoader $config) { $this->config = $config; foreach ($config->getDataSources() as $sourceId => $ds) { $this->addDataSource($sourceId, $ds); } }
public function buildConfigSeeds(ConfigLoader $config) { if ($seeds = $config->getSeedScripts()) { foreach ($seeds as $seed) { $this->buildScriptSeed($seed); } } }
public function getConfigLoader($required = true) { if (!$this->config) { $this->config = ConfigLoader::getInstance(); $this->config->loadFromSymbol(true); // force loading if (!$this->config->isLoaded() && $required) { throw new RuntimeException("ConfigLoader did not loaded any config file. Can't initialize the settings."); } } return $this->config; }
public static function createNeutralConfigLoader() { $config = ConfigLoader::getInstance(); $config->loaded = true; $config->setConfigStash(array('schema' => array('auto_id' => true))); return $config; }
public function setUp() { $annnotations = $this->getAnnotations(); $configLoader = ConfigLoader::getInstance(); $configLoader->loadFromSymbol(true); $configLoader->setDefaultDataSourceId($this->getDriverType()); $connManager = ConnectionManager::getInstance(); $connManager->init($configLoader); try { $dbh = $connManager->getConnection($this->getDriverType()); } catch (PDOException $e) { if ($this->allowConnectionFailure) { $this->markTestSkipped(sprintf("Can not connect to database by data source '%s' message:'%s' config:'%s'", $this->getDriverType(), $e->getMessage(), var_export($configLoader->getDataSource($this->getDriverType()), true))); return; } else { echo sprintf("Can not connect to database by data source '%s' message:'%s' config:'%s'", $this->getDriverType(), $e->getMessage(), var_export($configLoader->getDataSource($this->getDriverType()), true)); throw $e; } } $driver = $connManager->getQueryDriver($this->getDriverType()); $this->assertInstanceOf('SQLBuilder\\Driver\\BaseDriver', $driver, 'QueryDriver object OK'); // Rebuild means rebuild the database for new tests $rebuild = true; $basedata = true; if (isset($annnotations['method']['rebuild'][0]) && $annnotations['method']['rebuild'][0] == 'false') { $rebuild = false; } if (isset($annnotations['method']['basedata'][0]) && $annnotations['method']['basedata'][0] == 'false') { $basedata = false; } if ($rebuild) { $builder = SqlBuilder::create($driver, array('rebuild' => true)); $this->assertNotNull($builder); // $schemas = ClassUtils::schema_classes_to_objects($this->getModels()); $schemas = ClassUtils::schema_classes_to_objects($this->getModels()); foreach ($schemas as $schema) { $sqls = $builder->build($schema); $this->assertNotEmpty($sqls); foreach ($sqls as $sql) { $dbh->query($sql); } } if ($basedata) { $runner = new SeedBuilder($this->config, $this->logger); foreach ($schemas as $schema) { $runner->buildSchemaSeeds($schema); } if ($scripts = $this->config->getSeedScripts()) { foreach ($scripts as $script) { $runner->buildScriptSeed($script); } } } } }
/** * Returns schema objects. * * @return array schema objects */ public static function findSchemasByArguments(ConfigLoader $loader, $args, $logger = null) { if (count($args) && !file_exists($args[0])) { $classes = array(); // it's classnames foreach ($args as $class) { // call class loader to load if (class_exists($class, true)) { $classes[] = $class; } else { if ($logger) { $logger->warn("{$class} not found."); } else { echo ">>> {$class} not found.\n"; } } } return ClassUtils::schema_classes_to_objects($classes); } else { $finder = new SchemaFinder(); if (count($args) && file_exists($args[0])) { $finder->paths = $args; foreach ($args as $file) { if (is_file($file)) { require_once $file; } } } elseif ($paths = $loader->getSchemaPaths()) { $finder->setPaths($paths); } $finder->find(); // load class from class map if ($classMap = $loader->getClassMap()) { foreach ($classMap as $file => $class) { if (!is_numeric($file) && is_string($file)) { require $file; } } } return SchemaLoader::loadDeclaredSchemas(); } }
public function register(Kernel $kernel, $options = array()) { // TODO: move to generate prepare... $loader = \LazyRecord\ConfigLoader::getInstance(); if (!$loader->loaded) { $loader->load($this->config); $loader->init(); // init data source and connection } $kernel->db = function () { return ConnectionManager::getInstance()->getConnection('default'); }; }
public function register($kernel, $options = array()) { $config = $kernel->config->stashes['database']; $loader = \LazyRecord\ConfigLoader::getInstance(); if (!$loader->loaded) { $loader->load($config); $loader->init(); // init data source and connection } $kernel->db = function () { return ConnectionManager::getInstance()->getConnection(); }; }
public function schemaProvider() { $loader = \LazyRecord\ConfigLoader::getInstance(); $loader->loadFromArray(array('bootstrap' => array('tests/bootstrap.php'), 'schema' => array('auto_id' => 1, 'paths' => array('tests/TestApp')), 'data_sources' => array('default' => array('dsn' => 'sqlite::memory:', 'user' => NULL, 'pass' => NULL), 'pgsql' => array('dsn' => 'pgsql:host=localhost;dbname=testing', 'user' => 'postgres')))); // force loading $g = $this->createSchemaGenerator(); $schemas = array(); $schemas[] = [$g, new \TestApp\Model\UserSchema()]; $schemas[] = [$g, new \AuthorBooks\Model\AddressSchema()]; $schemas[] = [$g, new \AuthorBooks\Model\BookSchema()]; $schemas[] = [$g, new \TestApp\Model\IDNumberSchema()]; $schemas[] = [$g, new \TestApp\Model\NameSchema()]; return $schemas; }
public function execute() { $logger = $this->getLogger(); $options = $this->getOptions(); $this->logger->debug("Loading config"); $loader = ConfigLoader::getInstance(); $loader->loadFromSymbol(true); $loader->initForBuild(); $this->logger->debug("Initializing schema generator..."); $generator = new SchemaGenerator($loader, $logger); $args = func_get_args(); $classes = Utils::findSchemasByArguments($loader, $args, $this->logger); foreach ($classes as $class) { $rfc = new ReflectionClass($class); $this->logger->info(sprintf(" %-50s %s", $class, $rfc->getFilename())); } $logger->info('Done'); }
/** * Build schema */ protected function build(array $options = array()) { $this->schema($options); // postSchema is added for mixin that needs all schema information, for example LocalizeMixin foreach ($this->mixinSchemas as $mixin) { $mixin->postSchema(); } $this->primaryKey = $this->findPrimaryKey(); // if the primary key is not define, we should append the default primary key => id // AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY if (null === $this->primaryKey) { if ($config = ConfigLoader::getInstance()) { if ($config->hasAutoId() && !isset($this->columns['id'])) { $this->insertAutoIdColumn(); } } } }
public function insertIntoDataSource($schema) { $connManager = LazyRecord\ConnectionManager::getInstance(); $configLoader = ConfigLoader::getInstance(); $configLoader->loadFromSymbol(true); $connManager->init($configLoader); $pdo = $connManager->getConnection(self::getCurrentDriverType()); $this->assertInstanceOf('PDO', $pdo); $queryDriver = $connManager->getQueryDriver(self::getCurrentDriverType()); $builder = SqlBuilder::create($queryDriver, array('rebuild' => true)); $builder->build($schema); $sqls = $builder->build($schema); $this->assertNotEmpty($sqls); foreach ($sqls as $sql) { $this->assertQueryOK($pdo, $sql); } $this->assertTableExists($pdo, $schema->getTable()); }
public function __construct() { $this['config_loader'] = function ($c) { $config = ConfigLoader::getInstance(); $config->loadFromSymbol(true); // force loading if ($config->isLoaded()) { $config->initForBuild(); } return $config; }; $this['logger'] = function ($c) { return Console::getInstance()->getLogger(); }; $this['schema_finder'] = function ($c) { $finder = new SchemaFinder(); $finder->paths = $c['config_loader']->getSchemaPaths() ?: []; return $finder; }; }
public function execute($configFile = null) { /** * $ lazy bulid-conf config/lazy.yml phifty/config/lazy.yml * * build/lazy/config.php # is generated */ if (!$configFile) { $possiblePaths = array('db/config/site_database.yml', 'db/config/database.yml', 'config/database.yml', 'config/site_database.yml'); foreach ($possiblePaths as $path) { if (file_exists($path)) { $this->logger->info("Found default config file: {$path}"); $configFile = $path; ConfigLoader::compile($configFile); } } } if (!$configFile) { throw new Exception("config file path is required."); } $this->logger->info("Building config from {$configFile}"); $dir = dirname($configFile); ConfigLoader::compile($configFile); // make master config link $loader = ConfigLoader::getInstance(); if (file_exists($loader->symbolFilename)) { $this->logger->info('Cleaning up symbol link'); unlink($loader->symbolFilename); } if (file_exists('.lazy.php')) { $this->logger->info('Cleaning up symbol link'); unlink('.lazy.php'); } $this->logger->info("Making link => " . $loader->symbolFilename); if (cross_symlink($configFile, $loader->symbolFilename) === false) { $this->logger->error("Config linking failed."); } $this->logger->info("Done."); }
public function execute($configFile = null) { /* * $ lazy bulid-conf config/lazy.yml phifty/config/lazy.yml * * build/lazy/config.php # is generated */ if (!$configFile && $this->options->{'search'}) { $possiblePaths = array('db/config/site_database.yml', 'db/config/database.yml', 'config/database.yml', 'config/site_database.yml'); foreach ($possiblePaths as $path) { if (file_exists($path)) { $this->logger->info("Found default config file: {$path}"); $configFile = $path; ConfigLoader::compile($configFile); } } } if (!$configFile) { throw new Exception('config file is required.'); } $this->logger->info("Building config from {$configFile}"); $dir = dirname($configFile); ConfigLoader::compile($configFile, $this->options->force); // make master config link $loader = ConfigLoader::getInstance(); $cleanup = [$loader->symbolFilename, '.lazy.php', '.lazy.yml']; foreach ($cleanup as $symlink) { if (file_exists($symlink)) { $this->logger->debug('Cleaning up symbol link: ' . $symlink); unlink($symlink); } } $this->logger->info('Creating symbol link: ' . $loader->symbolFilename . ' -> ' . $configFile); if (cross_symlink($configFile, $loader->symbolFilename) === false) { $this->logger->error('Config linking failed.'); } $this->logger->info('Done'); }
/** * Returns schema objects. * * @return array schema objects */ public static function findSchemasByArguments(ConfigLoader $loader, array $args, Logger $logger = null) { $classes = array_filter($args, function ($class) { return class_exists($class, true); }); if (!empty($classes)) { return ClassUtils::schema_classes_to_objects(array_unique($classes)); } $paths = array_filter($args, 'file_exists'); if (empty($paths)) { $paths = $loader->getSchemaPaths(); } if (!empty($paths)) { $finder = new SchemaFinder($paths); $finder->find(); } // load class from class map if ($classMap = $loader->getClassMap()) { foreach ($classMap as $file => $class) { if (is_numeric($file)) { continue; } require_once $file; } } return SchemaLoader::loadDeclaredSchemas(); }
public function createSchemaGenerator() { $g = new \LazyRecord\Schema\SchemaGenerator(ConfigLoader::getInstance(), Logger::getInstance()); $g->forceUpdate = true; return $g; }
public function testSetConfigStash() { $config = new ConfigLoader(); $config->setLoaded(true); $config->setConfigStash(array('schema' => array('auto_id' => true))); }
<?php $loader = (require "vendor/autoload.php"); require "tests/model_helpers.php"; mb_internal_encoding('UTF-8'); error_reporting(E_ALL); $loader->add(null, 'tests'); $loader->add(null, 'tests/src'); use LazyRecord\Schema\SchemaGenerator; use LazyRecord\ConfigLoader; use CLIFramework\Logger; $config = ConfigLoader::getInstance(); $config->loadFromSymbol(true); $config->initForBuild(); $logger = new Logger(); $logger->quiet(); $logger->info("Building schema class files..."); // build schema class files $schemas = array(new \AuthorBooks\Model\AddressSchema(), new \AuthorBooks\Model\AuthorBookSchema(), new \AuthorBooks\Model\AuthorSchema(), new \AuthorBooks\Model\BookSchema(), new \AuthorBooks\Model\PublisherSchema(), new \AuthorBooks\Model\TagSchema(), new \MetricApp\Model\MetricValueSchema(), new \PageApp\Model\PageSchema(), new \StoreApp\Model\StoreSchema(), new \TestApp\Model\EdmSchema(), new \TestApp\Model\IDNumberSchema(), new \TestApp\Model\NameSchema(), new \TestApp\Model\PostSchema(), new \TestApp\Model\TableSchema(), new \TestApp\Model\UserSchema(), new \TestApp\Model\WineCategorySchema(), new \TestApp\Model\WineSchema()); $g = new \LazyRecord\Schema\SchemaGenerator($config, $logger); $g->setForceUpdate(true); $g->generate($schemas, true); // $logger->info("Starting tests...");
public static function getCacheInstance() { if (self::$_cacheInstance) { return self::$_cacheInstance; } return self::$_cacheInstance = ConfigLoader::getInstance()->getCacheInstance(); }
public function testLoadFromSymbol() { $config = new ConfigLoader(); $config->loadFromSymbol(); $this->assertTrue($config->loaded); }
public function execute() { $logger = $this->getLogger(); $configFile = $this->options->config ?: 'db/config/database.yml'; if (file_exists($configFile)) { $logger->info("Config file {$configFile} already exists."); return; } $driver = $this->options->driver ?: $this->ask('Database driver [sqlite]', array('sqlite', 'pgsql', 'mysql', null)) ?: 'sqlite'; $dbName = $this->options->database ?: $this->ask('Database name [:memory:]') ?: ':memory:'; $logger->info("Using {$driver} driver"); $logger->info("Using database {$dbName}"); $user = ''; $password = ''; if ($driver != 'sqlite') { // FIXME: fix DSN for sqlite, "sqlite:mydb.sqlite3" doesn't require dbname= ... $user = $this->options->username ?: $this->ask('Database user'); $password = $this->options->password ?: $this->ask('Database password'); } $logger->info('Creating config file skeleton...'); $content = <<<EOS --- bootstrap: - vendor/autoload.php schema: # Insert auto-increment primary key to every schema classes auto_id: true # Customize your schema class loader # # loader: custom_schema_loader.php # Customize your schema paths # paths: # - src data_source: default: master nodes: master: driver: {$driver} database: {$dbName} user: {$user} pass: {$password} EOS; if (file_put_contents($configFile, $content) !== false) { $logger->info("Config file is generated: {$configFile}"); $logger->info('Please run build-conf to compile php format config file.'); } $this->logger->info("Building config from {$configFile}"); $dir = dirname($configFile); ConfigLoader::compile($configFile, true); // make master config link $loader = ConfigLoader::getInstance(); $cleanup = [$loader->symbolFilename, '.lazy.php', '.lazy.yml']; foreach ($cleanup as $symlink) { if (file_exists($symlink)) { $this->logger->debug('Cleaning up symbol link: ' . $symlink); unlink($symlink); } } $this->logger->info('Creating symbol link: ' . $loader->symbolFilename . ' -> ' . $configFile); if (cross_symlink($configFile, $loader->symbolFilename) === false) { $this->logger->error('Config linking failed.'); } $this->logger->info('Done'); }
public function __construct($name = NULL, array $data = array(), $dataName = '') { parent::__construct($name, $data, $dataName); if (!extension_loaded('pdo')) { $this->markTestSkipped('pdo extension is required for model testing'); return; } // free and override default connection ConnectionManager::getInstance()->free(); $configLoader = ConfigLoader::getInstance(); $configLoader->loadFromSymbol(true); $configLoader->setDefaultDataSourceId($this->getDriverType()); $connManager = ConnectionManager::getInstance(); $connManager->init($configLoader); // $config = self::createNeutralConfigLoader(); $this->setConfig($configLoader); $this->logger = new Logger(); $this->logger->setQuiet(); if (method_exists($this, 'getModels')) { /* $generator = new SchemaGenerator($this->config, $this->logger); $schemas = ClassUtils::schema_classes_to_objects($this->getModels()); $classMap = $generator->generate($schemas); */ } }