Create entity tables in the database.

@param string $etype The entity type to create a table for. If this is
blank, the default tables are created.
16964
private function createTables($etype = null) {
    $this->checkReadOnlyMode();
    $this->query("SAVEPOINT 'tablecreation';");
    try {
      if (isset($etype)) {
        $etype = '_'.SQLite3::escapeString($etype);

        // Create the entity table.
        $this->query("CREATE TABLE IF NOT EXISTS \"{$this->prefix}entities{$etype}\" (\"guid\" INTEGER PRIMARY KEY ASC NOT NULL REFERENCES \"{$this->prefix}guids\"(\"guid\") ON DELETE CASCADE, \"tags\" TEXT, \"cdate\" REAL NOT NULL, \"mdate\" REAL NOT NULL);");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}entities{$etype}_id_cdate\" ON \"{$this->prefix}entities{$etype}\" (\"cdate\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}entities{$etype}_id_mdate\" ON \"{$this->prefix}entities{$etype}\" (\"mdate\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}entities{$etype}_id_tags\" ON \"{$this->prefix}entities{$etype}\" (\"tags\");");
        // Create the data table.
        $this->query("CREATE TABLE IF NOT EXISTS \"{$this->prefix}data{$etype}\" (\"guid\" INTEGER NOT NULL REFERENCES \"{$this->prefix}entities{$etype}\"(\"guid\") ON DELETE CASCADE, \"name\" TEXT NOT NULL, \"value\" TEXT NOT NULL, PRIMARY KEY(\"guid\", \"name\"));");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}data{$etype}_id_guid\" ON \"{$this->prefix}data{$etype}\" (\"guid\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}data{$etype}_id_name\" ON \"{$this->prefix}data{$etype}\" (\"name\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}data{$etype}_id_value\" ON \"{$this->prefix}data{$etype}\" (\"value\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}data{$etype}_id_guid__name_user\" ON \"{$this->prefix}data{$etype}\" (\"guid\") WHERE \"name\" = 'user';");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}data{$etype}_id_guid__name_group\" ON \"{$this->prefix}data{$etype}\" (\"guid\") WHERE \"name\" = 'group';");
        // Create the comparisons table.
        $this->query("CREATE TABLE IF NOT EXISTS \"{$this->prefix}comparisons{$etype}\" (\"guid\" INTEGER NOT NULL REFERENCES \"{$this->prefix}entities{$etype}\"(\"guid\") ON DELETE CASCADE, \"name\" TEXT NOT NULL, \"eq_true\" INTEGER, \"eq_one\" INTEGER, \"eq_zero\" INTEGER, \"eq_negone\" INTEGER, \"eq_emptyarray\" INTEGER, \"string\" TEXT, \"int\" INTEGER, \"float\" REAL, \"is_int\" INTEGER, PRIMARY KEY(\"guid\", \"name\"));");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}comparisons{$etype}_id_guid\" ON \"{$this->prefix}comparisons{$etype}\" (\"guid\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}comparisons{$etype}_id_name\" ON \"{$this->prefix}comparisons{$etype}\" (\"name\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}comparisons{$etype}_id_name__eq_true\" ON \"{$this->prefix}comparisons{$etype}\" (\"name\") WHERE \"eq_true\" = 1;");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}comparisons{$etype}_id_name__not_eq_true\" ON \"{$this->prefix}comparisons{$etype}\" (\"name\") WHERE \"eq_true\" = 0;");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}comparisons{$etype}_id_int\" ON \"{$this->prefix}comparisons{$etype}\" (\"int\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}comparisons{$etype}_id_float\" ON \"{$this->prefix}comparisons{$etype}\" (\"float\");");
        // Create the references table.
        $this->query("CREATE TABLE IF NOT EXISTS \"{$this->prefix}references{$etype}\" (\"guid\" INTEGER NOT NULL REFERENCES \"{$this->prefix}entities{$etype}\"(\"guid\") ON DELETE CASCADE, \"name\" TEXT NOT NULL, \"reference\" INTEGER NOT NULL, PRIMARY KEY(\"guid\", \"name\", \"reference\"));");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}references{$etype}_id_guid\" ON \"{$this->prefix}references{$etype}\" (\"guid\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}references{$etype}_id_name\" ON \"{$this->prefix}references{$etype}\" (\"name\");");
        $this->query("CREATE INDEX IF NOT EXISTS \"{$this->prefix}references{$etype}_id_reference\" ON \"{$this->prefix}references{$etype}\" (\"reference\");");
      } else {
        // Create the GUID table.
        $this->query("CREATE TABLE IF NOT EXISTS \"{$this->prefix}guids\" (\"guid\" INTEGER NOT NULL PRIMARY KEY ASC);");
        // Create the UID table.
        $this->query("CREATE TABLE IF NOT EXISTS \"{$this->prefix}uids\" (\"name\" TEXT PRIMARY KEY NOT NULL, \"cur_uid\" INTEGER NOT NULL);");
      }
    } catch (\Exception $e) {
      $this->query("ROLLBACK TO 'tablecreation';");

      throw $e;
    }
    $this->query("RELEASE 'tablecreation';");
    return true;
  }
1161523
def create_tables(c):
    """"""
    # auto_shape_types ---------------------
    c.execute(
        'DROP TABLE IF EXISTS auto_shape_types'
    )
    c.execute(
        'CREATE TABLE auto_shape_types (\n'
        '    id         integer,\n'
        '    prst       text,\n'
        '    const_name text,\n'
        '    base_name  text,\n'
        '    ms_name    text,\n'
        '    desc       text\n'
        ')\n'
    )
    c.execute(
        'DROP TABLE IF EXISTS adjustment_values'
    )
    c.execute(
        'CREATE TABLE adjustment_values (\n'
        '    prst     text,\n'
        '    seq_nmbr integer,\n'
        '    name     text,\n'
        '    val      integer\n'
        ')\n'
    )
824799
public function setLogType($type)
    {
        if (empty($type)) {
            $type = 'log';
        }

        $this->log_type = $type;
        $this->function = 'console.' . $this->log_type;
    }
1312617
private function createTables($etype = null) {
    $this->query('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
    if ($this->config['MySQL']['foreign_keys']) {
      $foreignKeyEntityTableGuid = " REFERENCES `{$this->prefix}guids`(`guid`) ON DELETE CASCADE";
      $foreignKeyDataTableGuid = " REFERENCES `{$this->prefix}entities{$etype}`(`guid`) ON DELETE CASCADE";
      $foreignKeyDataComparisonsTableGuid = " REFERENCES `{$this->prefix}entities{$etype}`(`guid`) ON DELETE CASCADE";
      $foreignKeyReferencesTableGuid = " REFERENCES `{$this->prefix}entities{$etype}`(`guid`) ON DELETE CASCADE";
    } else {
      $foreignKeyEntityTableGuid = '';
      $foreignKeyDataTableGuid = '';
      $foreignKeyDataComparisonsTableGuid = '';
      $foreignKeyReferencesTableGuid = '';
    }
    if (isset($etype)) {
      $etype = '_'.mysqli_real_escape_string($this->link, $etype);
      // Create the entity table.
      $this->query(
          "CREATE TABLE IF NOT EXISTS `{$this->prefix}entities{$etype}` (".
            "`guid` BIGINT(20) UNSIGNED NOT NULL{$foreignKeyEntityTableGuid}, ".
            "`tags` LONGTEXT, ".
            "`cdate` DECIMAL(18,6) NOT NULL, ".
            "`mdate` DECIMAL(18,6) NOT NULL, ".
            "PRIMARY KEY (`guid`), ".
            "INDEX `id_cdate` USING BTREE (`cdate`), ".
            "INDEX `id_mdate` USING BTREE (`mdate`), ".
            "FULLTEXT `id_tags` (`tags`) ".
          ") ENGINE {$this->config['MySQL']['engine']} ".
          "CHARACTER SET utf8 COLLATE utf8_bin;"
      );
      // Create the data table.
      $this->query(
          "CREATE TABLE IF NOT EXISTS `{$this->prefix}data{$etype}` (".
            "`guid` BIGINT(20) UNSIGNED NOT NULL{$foreignKeyDataTableGuid}, ".
            "`name` TEXT NOT NULL, ".
            "`value` LONGTEXT NOT NULL, ".
            "PRIMARY KEY (`guid`,`name`(255)), ".
            "INDEX `id_name` USING HASH (`name`(255)), ".
            "INDEX `id_name_value` USING BTREE (`name`(255), `value`(512))".
            ") ENGINE {$this->config['MySQL']['engine']} ".
          "CHARACTER SET utf8 COLLATE utf8_bin;"
      );
      // Create the data comparisons table.
      $this->query(
          "CREATE TABLE IF NOT EXISTS `{$this->prefix}comparisons{$etype}` (".
            "`guid` BIGINT(20) UNSIGNED NOT NULL".
              "{$foreignKeyDataComparisonsTableGuid}, ".
            "`name` TEXT NOT NULL, ".
            "`eq_true` BOOLEAN, ".
            "`eq_one` BOOLEAN, ".
            "`eq_zero` BOOLEAN, ".
            "`eq_negone` BOOLEAN, ".
            "`eq_emptyarray` BOOLEAN, ".
            "`string` LONGTEXT, ".
            "`int` BIGINT, ".
            "`float` DOUBLE, ".
            "`is_int` BOOLEAN NOT NULL, ".
            "PRIMARY KEY (`guid`, `name`(255)), ".
            "INDEX `id_name` USING HASH (`name`(255))".
          ") ENGINE {$this->config['MySQL']['engine']} ".
          "CHARACTER SET utf8 COLLATE utf8_bin;"
      );
      // Create the references table.
      $this->query(
          "CREATE TABLE IF NOT EXISTS `{$this->prefix}references{$etype}` (".
            "`guid` BIGINT(20) UNSIGNED NOT NULL".
              "{$foreignKeyDataComparisonsTableGuid}, ".
            "`name` TEXT NOT NULL, ".
            "`reference` BIGINT(20) UNSIGNED NOT NULL, ".
            "PRIMARY KEY (`guid`, `name`(255), `reference`), ".
            "INDEX `id_name_reference` USING BTREE (`name`(255), `reference`)".
          ") ENGINE {$this->config['MySQL']['engine']} ".
          "CHARACTER SET utf8 COLLATE utf8_bin;"
      );
    } else {
      // Create the GUID table.
      $this->query(
          "CREATE TABLE IF NOT EXISTS `{$this->prefix}guids` (".
            "`guid` BIGINT(20) UNSIGNED NOT NULL, ".
            "PRIMARY KEY (`guid`)".
          ") ENGINE {$this->config['MySQL']['engine']} ".
          "CHARACTER SET utf8 COLLATE utf8_bin;"
      );
      // Create the UID table.
      $this->query(
          "CREATE TABLE IF NOT EXISTS `{$this->prefix}uids` (".
            "`name` TEXT NOT NULL, ".
            "`cur_uid` BIGINT(20) UNSIGNED NOT NULL, ".
            "PRIMARY KEY (`name`(100))".
          ") ENGINE {$this->config['MySQL']['engine']} ".
          "CHARACTER SET utf8 COLLATE utf8_bin;"
      );
    }
    return true;
  }
793292
protected function db_init() {
        global $CFG;

        require_once($CFG->libdir.'/adodb/adodb.inc.php');

        // Connect to the external database (forcing new connection).
        $extdb = ADONewConnection($this->get_config('dbtype'));
        if ($this->get_config('debugdb')) {
            $extdb->debug = true;
            ob_start(); // Start output buffer to allow later use of the page headers.
        }

        // The dbtype my contain the new connection URL, so make sure we are not connected yet.
        if (!$extdb->IsConnected()) {
            $result = $extdb->Connect($this->get_config('dbhost'), $this->get_config('dbuser'), $this->get_config('dbpass'), $this->get_config('dbname'), true);
            if (!$result) {
                return null;
            }
        }

        $extdb->SetFetchMode(ADODB_FETCH_ASSOC);
        if ($this->get_config('dbsetupsql')) {
            $extdb->Execute($this->get_config('dbsetupsql'));
        }
        return $extdb;
    }
338422
private function createDatabase()
    {
        $em       = $this->entityManager;
        $metadata = $em->getMetadataFactory()->getAllMetadata();

        $schemaTool = new SchemaTool($em);
        $schemaTool->createSchema($metadata);
    }
1211511
public function make(string $type)
    {
        if (isset($this->iocContainerArray[$type])) {
            $type = $this->iocContainerArray[$type];

            return $type();
        }
        throw new ClientException('No type registered with that name');
    }
737322
public function initTypes()
    {
        $names = $this->generateTypesNames();
        foreach ($names as $name) {
            $object = $this->getNewType($name);
            $this->addType($object);
        }
    }
261195
private void createTables() throws SQLException, BlockStoreException {
        Statement s = conn.get().createStatement();
        // create all the database tables
        for (String sql : getCreateTablesSQL()) {
            if (log.isDebugEnabled()) {
                log.debug("DatabaseFullPrunedBlockStore : CREATE table [SQL= {0}]", sql);
            }
            s.executeUpdate(sql);
        }
        // create all the database indexes
        for (String sql : getCreateIndexesSQL()) {
            if (log.isDebugEnabled()) {
                log.debug("DatabaseFullPrunedBlockStore : CREATE index [SQL= {0}]", sql);
            }
            s.executeUpdate(sql);
        }
        s.close();

        // insert the initial settings for this store
        PreparedStatement ps = conn.get().prepareStatement(getInsertSettingsSQL());
        ps.setString(1, CHAIN_HEAD_SETTING);
        ps.setNull(2, Types.BINARY);
        ps.execute();
        ps.setString(1, VERIFIED_CHAIN_HEAD_SETTING);
        ps.setNull(2, Types.BINARY);
        ps.execute();
        ps.setString(1, VERSION_SETTING);
        ps.setBytes(2, "03".getBytes());
        ps.execute();
        ps.close();
        createNewStore(params);
    }
405410
@Override
	public SqlContext createBatchInsertContext(final SqlAgent agent, final TableMetadata metadata,
			final Class<? extends Object> entityType) {
		return agent.contextWith(buildInsertSQL(metadata, entityType, agent.getSqlConfig(), false))
				.setSqlId(createSqlId(metadata, entityType));
	}
825038
public function setupDatabase()
    {
        $dbHandler = $this->getDbHandler();

        $dbHandler->getDbConnection()->exec('drop database `' . $dbHandler->getDbName() . '`');
        $dbHandler->getDbConnection()->exec('create database `' . $dbHandler->getDbName() . '` collate ' . $dbHandler->getCharsetMode() . '_general_ci');

        $baseEditionPathProvider = new EditionPathProvider(new EditionRootPathProvider(new EditionSelector(EditionSelector::COMMUNITY)));

        $dbHandler->import($baseEditionPathProvider->getDatabaseSqlDirectory() . "/database_schema.sql");
        $dbHandler->import($baseEditionPathProvider->getDatabaseSqlDirectory() . "/initial_data.sql");

        $output = new ConsoleOutput();
        $output->setVerbosity(ConsoleOutputInterface::VERBOSITY_QUIET);

        $utilities = new Utilities();
        $utilities->executeExternalDatabaseMigrationCommand($output);

        $this->callShellDbViewsRegenerate();
    }
1023119
public function createTables() {
        $answer = strtoupper($this->in('Existing tables will be deleted, continue?', array('Y', 'N')));

        if ($answer === 'N') {
            return false;
        }

        $schemas = glob(CakePlugin::path($this->plugin) . '/Config/Schema/*.sql');
        $executed = 0;
        $tables = array();

        // Loop over schemas and execute queries
        $this->out('<success>Creating tables...</success>');

        foreach ($schemas as $schema) {
            $table = $this->tablePrefix . str_replace('.sql', '', basename($schema));
            $tables[] = $table;

            $executed += $this->executeSchema($schema);
            $this->out($table);
        }

        // Rollback if a failure occurs
        if ($executed != count($schemas)) {
            $this->out('<error>Failed to create database tables; rolling back</error>');

            foreach ($tables as $table) {
                $this->db->execute(sprintf('DROP TABLE `%s`;', $table));
            }

            return false;
        }

        $this->out('<success>Tables created successfully, proceeding...</success>');
        return true;
    }
937223
private function makeEntityQuery(
      $options,
      $selectors,
      $etypeDirty,
      $subquery = false
  ) {
    $fullQueryCoverage = true;
    $sort = $options['sort'] ?? 'cdate';
    $etype = '_'.mysqli_real_escape_string($this->link, $etypeDirty);
    $queryParts = $this->iterateSelectorsForQuery($selectors, function ($value) use ($options, $etypeDirty, &$fullQueryCoverage) {
      $subquery = $this->makeEntityQuery(
          $options,
          [$value],
          $etypeDirty,
          true
      );
      $fullQueryCoverage = $fullQueryCoverage && $subquery['fullCoverage'];
      return $subquery['query'];
    }, function (&$curQuery, $key, $value, $typeIsOr, $typeIsNot) use ($etype, &$fullQueryCoverage) {
      $clauseNot = $key[0] === '!';
      // Any options having to do with data only return if the
      // entity has the specified variables.
      foreach ($value as $curValue) {
        switch ($key) {
          case 'guid':
          case '!guid':
            foreach ($curValue as $curGuid) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`guid`=\''.(int) $curGuid.'\'';
            }
            break;
          case 'tag':
          case '!tag':
            if ($typeIsNot xor $clauseNot) {
              if ($typeIsOr) {
                foreach ($curValue as $curTag) {
                  if ($curQuery) {
                    $curQuery .= ' OR ';
                  }
                  $curQuery .= 'ie.`tags` NOT REGEXP \' '.
                      mysqli_real_escape_string($this->link, $curTag).
                      ' \'';
                }
              } else {
                $curQuery .= 'ie.`tags` NOT REGEXP \' ('.
                    mysqli_real_escape_string(
                        $this->link,
                        implode('|', $curValue)
                    ).') \'';
              }
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $groupQuery = '';
              foreach ($curValue as $curTag) {
                $groupQuery .= ($typeIsOr ? ' ' : ' +').
                    '"'.mysqli_real_escape_string($this->link, $curTag).'"';
              }
              $curQuery .= 'MATCH (ie.`tags`) AGAINST (\''.
                  $groupQuery.'\' IN BOOLEAN MODE)';
            }
            break;
          case 'isset':
          case '!isset':
            foreach ($curValue as $curVar) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'data',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curVar).
                      '\' AND `value`!=\'N;\'',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'ref':
          case '!ref':
            $guids = [];
            if (is_array($curValue[1])) {
              if (key_exists('guid', $curValue[1])) {
                $guids[] = (int) $curValue[1]['guid'];
              } else {
                foreach ($curValue[1] as $curEntity) {
                  if (is_object($curEntity)) {
                    $guids[] = (int) $curEntity->guid;
                  } elseif (is_array($curEntity)) {
                    $guids[] = (int) $curEntity['guid'];
                  } else {
                    $guids[] = (int) $curEntity;
                  }
                }
              }
            } elseif (is_object($curValue[1])) {
              $guids[] = (int) $curValue[1]->guid;
            } else {
              $guids[] = (int) $curValue[1];
            }
            foreach ($guids as $curQguid) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'references',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `reference`='.
                      mysqli_real_escape_string($this->link, (int) $curQguid),
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'strict':
          case '!strict':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`cdate`='.((float) $curValue[1]);
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`mdate`='.((float) $curValue[1]);
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              if (is_callable([$curValue[1], 'toReference'])) {
                $svalue = serialize($curValue[1]->toReference());
              } else {
                $svalue = serialize($curValue[1]);
              }
              $curQuery .= $this->makeDataPart(
                  'data',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `value`=\''.
                      mysqli_real_escape_string($this->link, $svalue).'\'',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'like':
          case '!like':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`cdate` LIKE \''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\')';
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`mdate` LIKE \''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\')';
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `string` LIKE \''.
                      mysqli_real_escape_string($this->link, $curValue[1]).
                      '\'',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'ilike':
          case '!ilike':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`cdate` LIKE LOWER(\''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\'))';
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`mdate` LIKE LOWER(\''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\'))';
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND LOWER(`string`) LIKE LOWER(\''.
                      mysqli_real_escape_string($this->link, $curValue[1]).
                      '\')',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'pmatch':
          case '!pmatch':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`cdate` REGEXP \''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\')';
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`mdate` REGEXP \''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\')';
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `string` REGEXP \''.
                      mysqli_real_escape_string($this->link, $curValue[1]).
                      '\'',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'ipmatch':
          case '!ipmatch':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`cdate` REGEXP LOWER(\''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\'))';
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  '(ie.`mdate` REGEXP LOWER(\''.
                  mysqli_real_escape_string($this->link, $curValue[1]).
                  '\'))';
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND LOWER(`string`) REGEXP LOWER(\''.
                      mysqli_real_escape_string($this->link, $curValue[1]).
                      '\')',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'gt':
          case '!gt':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`cdate`>'.((float) $curValue[1]);
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`mdate`>'.((float) $curValue[1]);
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND ((`is_int`=TRUE AND `int` > '.
                      ((int) $curValue[1]).') OR ('.
                      '`is_int`=FALSE AND `float` > '.
                      ((float) $curValue[1]).'))',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'gte':
          case '!gte':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`cdate`>='.((float) $curValue[1]);
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`mdate`>='.((float) $curValue[1]);
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND ((`is_int`=TRUE AND `int` >= '.
                      ((int) $curValue[1]).') OR ('.
                      '`is_int`=FALSE AND `float` >= '.
                      ((float) $curValue[1]).'))',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'lt':
          case '!lt':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`cdate`<'.((float) $curValue[1]);
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`mdate`<'.((float) $curValue[1]);
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND ((`is_int`=TRUE AND `int` < '.
                      ((int) $curValue[1]).') OR ('.
                      '`is_int`=FALSE AND `float` < '.
                      ((float) $curValue[1]).'))',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          case 'lte':
          case '!lte':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`cdate`<='.((float) $curValue[1]);
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie.`mdate`<='.((float) $curValue[1]);
              break;
            } else {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND ((`is_int`=TRUE AND `int` <= '.
                      ((int) $curValue[1]).') OR ('.
                      '`is_int`=FALSE AND `float` <= '.
                      ((float) $curValue[1]).'))',
                  $typeIsNot xor $clauseNot
              );
            }
            break;
          // Cases after this point contains special values where
          // it can be solved by the query, but if those values
          // don't match, just check the variable exists.
          case 'equal':
          case '!equal':
          case 'data':
          case '!data':
            if ($curValue[0] === 'cdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie."cdate"='.((float) $curValue[1]);
              break;
            } elseif ($curValue[0] === 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= (($typeIsNot xor $clauseNot) ? 'NOT ' : '').
                  'ie."mdate"='.((float) $curValue[1]);
              break;
            } elseif ($curValue[1] === true || $curValue[1] === false) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `eq_true`='.($curValue[1] ? 'TRUE' : 'FALSE'),
                  $typeIsNot xor $clauseNot
              );
              break;
            } elseif ($curValue[1] === 1) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `eq_one`=TRUE',
                  $typeIsNot xor $clauseNot
              );
              break;
            } elseif ($curValue[1] === 0) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `eq_zero`=TRUE',
                  $typeIsNot xor $clauseNot
              );
              break;
            } elseif ($curValue[1] === -1) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `eq_negone`=TRUE',
                  $typeIsNot xor $clauseNot
              );
              break;
            } elseif ($curValue[1] === []) {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'comparisons',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).
                      '\' AND `eq_emptyarray`=TRUE',
                  $typeIsNot xor $clauseNot
              );
              break;
            }
            // Fall through.
          case 'match':
          case '!match':
          case 'array':
          case '!array':
            if (!($typeIsNot xor $clauseNot) && $curValue[0] !== 'cdate' && $curValue[0] !== 'mdate') {
              if ($curQuery) {
                $curQuery .= $typeIsOr ? ' OR ' : ' AND ';
              }
              $curQuery .= $this->makeDataPart(
                  'data',
                  $etype,
                  '`name`=\''.
                      mysqli_real_escape_string($this->link, $curValue[0]).'\'',
                  $typeIsNot xor $clauseNot
              );
            }
            $fullQueryCoverage = false;
            break;
        }
      }
    });

    switch ($sort) {
      case 'guid':
        $sort = '`guid`';
        break;
      case 'mdate':
        $sort = '`mdate`';
        break;
      case 'cdate':
      default:
        $sort = '`cdate`';
        break;
    }
    if (isset($options['reverse']) && $options['reverse']) {
      $sort .= ' DESC';
    }

    if ($queryParts) {
      if ($subquery) {
        $query = "((".implode(') AND (', $queryParts)."))";
      } else {
        $limit = "";
        if ($fullQueryCoverage && key_exists('limit', $options)) {
          $limit = " LIMIT ".((int) $options['limit']);
        }
        $offset = "";
        if ($fullQueryCoverage && key_exists('offset', $options)) {
          $offset = " OFFSET ".((int) $options['offset']);
        }
        $query =
          "SELECT e.`guid`, e.`tags`, e.`cdate`, e.`mdate`, ".
            "d.`name`, d.`value` ".
          "FROM `{$this->prefix}entities{$etype}` e ".
          "LEFT JOIN `{$this->prefix}data{$etype}` d ON e.`guid`=d.`guid` ".
          "INNER JOIN (".
            "SELECT ie.`guid` FROM `{$this->prefix}entities{$etype}` ie ".
            "WHERE (".
              implode(') AND (', $queryParts).
            ") ".
            "ORDER BY ie.{$sort}{$limit}{$offset}".
          ") f ON e.`guid`=f.`guid` ".
          "ORDER BY e.{$sort};";
      }
    } else {
      if ($subquery) {
        $query = '';
      } else {
        $limit = "";
        if (key_exists('limit', $options)) {
          $limit = " LIMIT ".((int) $options['limit']);
        }
        $offset = "";
        if (key_exists('offset', $options)) {
          $offset = " OFFSET ".((int) $options['offset']);
        }
        if ($limit || $offset) {
          $query =
            "SELECT e.`guid`, e.`tags`, e.`cdate`, e.`mdate`, ".
              "d.`name`, d.`value` ".
            "FROM `{$this->prefix}entities{$etype}` e ".
            "LEFT JOIN `{$this->prefix}data{$etype}` d ON e.`guid`=d.`guid` ".
            "INNER JOIN (".
              "SELECT ie.`guid` ".
              "FROM `{$this->prefix}entities{$etype}` ie ".
              "ORDER BY ie.{$sort}{$limit}{$offset}".
            ") f ON e.`guid`=f.`guid` ".
            "ORDER BY e.{$sort};";
        } else {
          $query =
            "SELECT e.`guid`, e.`tags`, e.`cdate`, e.`mdate`, ".
              "d.`name`, d.`value` ".
            "FROM `{$this->prefix}entities{$etype}` e ".
            "LEFT JOIN `{$this->prefix}data{$etype}` d ON e.`guid`=d.`guid` ".
            "ORDER BY e.{$sort};";
        }
      }
    }

    return [
      'fullCoverage' => $fullQueryCoverage,
      'limitOffsetCoverage' => $fullQueryCoverage,
      'query' => $query
    ];
  }
180774
public function initialize(Entity\Entity $entity)
    {
        $this->setupContenttype($entity);
        $this->setupContainer($entity);
    }
1313558
private function initialize()
    {
        $this->pdo->exec(
            'CREATE TABLE IF NOT EXISTS `'.$this->table.'` '
            .'(id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED, INDEX(channel) USING HASH, INDEX(level) USING HASH, INDEX(time) USING BTREE)'
        );

        //Read out actual columns
        $actualFields = array();
        $rs = $this->pdo->query('SELECT * FROM `'.$this->table.'` LIMIT 0');
        for ($i = 0; $i < $rs->columnCount(); $i++) {
            $col = $rs->getColumnMeta($i);
            $actualFields[] = $col['name'];
        }

        //Calculate changed entries
        $removedColumns = array_diff(
            $actualFields,
            $this->additionalFields,
            $this->defaultfields
        );
        $addedColumns = array_diff($this->additionalFields, $actualFields);

        //Remove columns
        if (!empty($removedColumns)) {
            foreach ($removedColumns as $c) {
                $this->pdo->exec('ALTER TABLE `'.$this->table.'` DROP `'.$c.'`;');
            }
        }

        //Add columns
        if (!empty($addedColumns)) {
            foreach ($addedColumns as $c) {
                $this->pdo->exec('ALTER TABLE `'.$this->table.'` add `'.$c.'` TEXT NULL DEFAULT NULL;');
            }
        }

        // merge default and additional field to one array
        $this->defaultfields = array_merge($this->defaultfields, $this->additionalFields);

        $this->initialized = true;
    }
1349237
public function setDataType($dataType)
    {
        $formDefinition = $this->getRootForm();
        $formDefinition->getProcessingRule($this->getIdentifier())->setDataType($dataType);
    }
983452
private function createTable()
    {
        $stmt = 'CREATE TABLE IF NOT EXISTS "' . $this->name;
        $stmt.= '" ("' . $this->keyColumnName . '" TEXT PRIMARY KEY, "';
        $stmt.= $this->valueColumnName . '" TEXT);';
        $this->db->exec($stmt);
    }