SQLPPPMapping creation
516152
@Override
    public SQLPPMapping createSQLPreProcessedMapping(ImmutableList<SQLPPTriplesMap> ppMappingAxioms,
                                                     MappingMetadata mappingMetadata)
            throws DuplicateMappingException {
        try {
            /**
             * Instantiation
             */
            Constructor constructor = findFirstConstructor(SQLPPMapping.class);
            return (SQLPPMapping) constructor.newInstance(ppMappingAxioms, mappingMetadata);
            /**
             * Exception management
             */
        } catch (InvocationTargetException e) {
            Throwable targetException = e.getTargetException();
            /**
             * Expected exception: rethrown
             */
            if (targetException instanceof DuplicateMappingException) {
                throw (DuplicateMappingException) targetException;
            }
            /**
             * Unexcepted: throw a unexpected RuntimeException.
             */
            throw new RuntimeException(targetException.getMessage());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
209025
def init():
    '''
    
    '''
    if not os.path.exists(__opts__['spm_cache_dir']):
        log.debug('Creating SPM cache directory at %s', __opts__['spm_db'])
        os.makedirs(__opts__['spm_cache_dir'])

    if not os.path.exists(__opts__['spm_db']):
        log.debug('Creating new package database at %s', __opts__['spm_db'])

    sqlite3.enable_callback_tracebacks(True)
    conn = sqlite3.connect(__opts__['spm_db'], isolation_level=None)

    try:
        conn.execute('SELECT count(*) FROM packages')
    except OperationalError:
        conn.execute('''CREATE TABLE packages (
            package text,
            version text,
            release text,
            installed text,
            os text,
            os_family text,
            dependencies text,
            os_dependencies text,
            os_family_dependencies text,
            summary text,
            description text
        )''')

    try:
        conn.execute('SELECT count(*) FROM files')
    except OperationalError:
        conn.execute('''CREATE TABLE files (
            package text,
            path text,
            size real,
            mode text,
            sum text,
            major text,
            minor text,
            linkname text,
            linkpath text,
            uname text,
            gname text,
            mtime text
        )''')

    return conn
523877
protected function bindNamedParameters(): void
    {
        foreach ($this->getValues() as $key => $value) {
            $value = $this->toScalar($value);
            $this->getWrappedStatement()->bindValue(sprintf(':%s', $key), $value, $this->getPdoType($value));
        }
    }
894539
def create_table(self, cursor, target, options):
        ""
        cursor.execute(
            self.create_sql[target].format(self.qualified_names[target]))
585578
static function factory($connection_params) {
		$class = '';
		$dsn = '';
		$user = null;
		$password = null;

		if (!empty($connection_params['user'])) {
			$user = $connection_params['user'];
		}

		if (!empty($connection_params['password'])) {
			$password = $connection_params['password'];
		}

		$options = array(
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
		);

		if (
			isset($connection_params['persistant']) &&
			(
				true === $connection_params['persistant']
				|| 1 === $connection_params['persistant']
				|| 'true' === $connection_params['persistant']
				|| '1' === $connection_params['persistant']
				|| 'on' === strtolower($connection_params['persistant'])
			)
		) {
			$options[PDO::ATTR_PERSISTENT] = true;
		}

		switch ($connection_params['driver']) {
			case 'access':

//				You may need to download the AccessDatabaseEngine.exe from Microsoft.
//
//				http://www.microsoft.com/en-us/download/details.aspx?id=23734 (2007)
//				http://www.microsoft.com/en-us/download/details.aspx?id=13255 (2010)
//
//				After the download finishes, and installs for your architecture (32 or 64 bit), You will need to create an ODBC connection.
//
//				Instead of creating an ODBC connection through your Administrative Tools, Data Sources (ODBC) interface, you will need to run
//				the 64-bit instance of Data Sources (ODBC). Run "c:\windows\sysWOW64\odbcad32.exe" -- without quotes. Then create the
//				connection to the database as you would on a 32 bit machine.

				$parts = array();
				if (!empty($connection_params['dbname'])) {
					if (!file_exists($connection_params['dbname'])) {
						throw new RuntimeException("Could not find database file: {$connection_params['dbname']}");
					}
					$parts[] = 'Dbq=' . addslashes($connection_params['dbname']);
				}
				if (!empty($connection_params['user'])) {
					$parts[] = 'Uid=' . $connection_params['user'];
					$user = null;
				}
				if (!empty($connection_params['password'])) {
					$parts[] = 'Pwd=' . $connection_params['password'];
					$password = null;
				}
				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = 'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' . implode(';', $parts);
				$class = 'DBAccess';
				break;

			case 'sqlite':
			case 'sqlite2':
				$dsn = $connection_params['driver'] . ':' . $connection_params['dbname'];
				$class = 'DBSQLite';
				break;

			case 'mysql':
				$parts = array();
				if (!empty($connection_params['host'])) {
					$parts[] = 'host=' . $connection_params['host'];
				}
				if (!empty($connection_params['port'])) {
					$parts[] = 'port=' . $connection_params['port'];
				}
				if (!empty($connection_params['unix_socket'])) {
					$parts[] = 'unix_socket=' . $connection_params['unix_socket'];
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = 'mysql:' . implode(';', $parts);
				$class = 'DBMySQL';
				break;

			case 'oracle':
			case 'oci':
				$parts = array();
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['charset'])) {
					$parts[] = 'charset=' . $connection_params['charset'];
				}
				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = 'oci:' . implode(';', $parts);
				$class = 'DBOracle';
				break;

			case 'pgsql':
				$parts = array();
				if (!empty($connection_params['host'])) {
					$parts[] = 'host=' . $connection_params['host'];
				}
				if (!empty($connection_params['port'])) {
					$parts[] = 'port=' . $connection_params['port'];
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['user'])) {
					$parts[] = 'user=' . $connection_params['user'];
				}
				if (!empty($connection_params['password'])) {
					$parts[] = 'password=' . $connection_params['password'];
				}
				foreach ($parts as &$v) {
					$v = str_replace(' ', '\ ', $v);
				}
				$dsn = 'pgsql:' . implode(' ', $parts);
				$user = null;
				$password = null;
				$class = 'DBPostgres';
				break;

			case 'sqlsrv':
				if (!empty($connection_params['host'])) {
					$parts[] = 'server=' . $connection_params['host'];
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'database=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['charset'])) {
					$parts[] = 'charset=' . $connection_params['charset'];
				}
				if (!empty($connection_params['appname'])) {
					$parts[] = 'appname=' . $connection_params['appname'];
				}

				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = $connection_params['driver'] . ':' . implode(';', $parts);
				$class = 'DBMSSQL';
				break;
			case 'mssql':
			case 'sybase':
			case 'dblib':
				if (!empty($connection_params['host'])) {
					$host = 'host=' . $connection_params['host'];
					if (!empty($connection_params['port'])) {
						$host .= ':' . $connection_params['port'];
					}
					$parts[] = $host;
				}
				if (!empty($connection_params['dbname'])) {
					$parts[] = 'dbname=' . $connection_params['dbname'];
				}
				if (!empty($connection_params['charset'])) {
					$parts[] = 'charset=' . $connection_params['charset'];
				}
				if (!empty($connection_params['appname'])) {
					$parts[] = 'appname=' . $connection_params['appname'];
				}

				foreach ($parts as &$v) {
					$v = str_replace(';', '\;', $v);
				}
				$dsn = $connection_params['driver'] . ':' . implode(';', $parts);
				$class = 'DBMSSQL';
				break;

			default:
				throw new RuntimeException("Unsupported database driver: " . $connection_params['driver'] . ": Check your configuration file");
		}

		try {
			$conn = new $class($dsn, $user, $password, $options);
		} catch (Exception $e) {
			throw new RuntimeException($e->getMessage() . ' DSN: ' . $dsn);
		}

		if (!empty($connection_params['dbname'])) {
			$conn->dbName = $connection_params['dbname'];
		}
		$conn->driver = $connection_params['driver'];

		return $conn;
	}
580479
@Override
	public synchronized RecordParam insert(String site, String type, String name, int used, String flags,
			String values) throws DatabaseException {
    	SqlPreparedStatementWrapper psInsert = null;
        try {
        	psInsert = DbSQL.getSingleton().getPreparedStatement("param.ps.insert");
			psInsert.getPs().setString(1, site);
			psInsert.getPs().setString(2, type);
			psInsert.getPs().setString(3, name);
			psInsert.getPs().setInt(4, used);
			psInsert.getPs().setString(5, flags);
			psInsert.getPs().setString(6, values);
			psInsert.getPs().executeUpdate();
			
			long id;
			try (ResultSet rs = psInsert.getLastInsertedId()) {
				rs.next();
				id = rs.getLong(1);
			}
			return read(id);
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psInsert);
		}
    }
1240790
function createApplication(name, owner_uuid, opts, callback) {
    assert.string(name, 'name');
    assert.string(owner_uuid, 'owner_uuid');

    if (typeof (opts) === 'function') {
        callback = opts;
        opts = {};
    }

    opts.name = name;
    opts.owner_uuid = owner_uuid;

    return (this.post('/applications', opts, callback));
}
317403
public void generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType,
			List<SQLProperty> listUsedProperty, ModelProperty primaryKey) {
		// transform JQL to SQL
		String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnName(String columnName) {
				Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);

				SQLProperty tempProperty = property.iterator().next();
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String resolvedParamName = method.findParameterNameByAlias(bindParameterName);

				return SqlAnalyzer.PARAM_PREFIX + resolvedParamName + SqlAnalyzer.PARAM_SUFFIX;
			}

		});

		// generate javadoc and result
		{
			String beanNameParameter = method.findParameterAliasByName(method.getParameters().get(0).value0);

			methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
			methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sqlInsert);
			methodBuilder.addJavadoc(
					"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\n",
					beanNameParameter, primaryKey.getName());
			methodBuilder.addJavadoc("\n");

			// list of inserted fields
			methodBuilder.addJavadoc("<p><strong>Inserted columns:</strong></p>\n");
			methodBuilder.addJavadoc("<dl>\n");
			for (SQLProperty property : listUsedProperty) {
				methodBuilder.addJavadoc("\t<dt>$L</dt>", property.columnName);
				methodBuilder.addJavadoc("<dd>is mapped to <strong>$L</strong></dd>\n",
						SqlAnalyzer.PARAM_PREFIX + method.findParameterAliasByName(method.getParameters().get(0).value0)
								+ "." + method.findParameterNameByAlias(property.getName()) + SqlAnalyzer.PARAM_SUFFIX);
			}
			methodBuilder.addJavadoc("</dl>\n\n");

			// update bean have only one parameter: the bean to update
			for (Pair<String, TypeName> param : method.getParameters()) {
				methodBuilder.addJavadoc("@param $L", param.value0);
				methodBuilder.addJavadoc("\n\tis mapped to parameter <strong>$L</strong>\n",
						method.findParameterAliasByName(param.value0));
			}

			InsertRawHelper.generateJavaDocReturnType(methodBuilder, returnType);
		}
	}
444687
public static function install()
    {
        global $PPHP;
        $db = $PPHP['db'];

        echo "    Installing users...\n";
        $db->begin();
        $customs = '';
        if (isset($PPHP['config']['users']['fields'])) {
            foreach ($PPHP['config']['users']['fields'] as $name => $definition) {
                $customs .= "                {$name} {$definition},\n";
            };
        };
        $db->exec(
            "
            CREATE TABLE IF NOT EXISTS 'users' (
                id           INTEGER PRIMARY KEY AUTOINCREMENT,
                email        VARCHAR(255) NOT NULL DEFAULT '',
                active       BOOL NOT NULL DEFAULT '1',
                passwordHash VARCHAR(255) NOT NULL DEFAULT '*',
                onetimeHash  VARCHAR(255) NOT NULL DEFAULT '*',
                onetimeTime  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                onetimeMax   INTEGER NOT NULL DEFAULT '0',
                {$customs}
                name         VARCHAR(255) NOT NULL DEFAULT ''
            )
            "
        );
        $db->exec(
            "
            CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email
            ON users (email)
            "
        );
        if (!$db->selectAtom("SELECT id FROM users WHERE id='1'")) {
            echo "Creating admin user...\n";
            $email = strtolower(readline("E-mail address: "));
            $pass1 = true;
            $pass2 = false;
            while ($pass1 !== $pass2) {
                if ($pass1 !== true) {
                    echo "  * Password confirmation mis-match.\n";
                };
                $pass1 = readline("Password: ");
                $pass2 = readline("Password again: ");
            };
            $db->exec(
                "
                INSERT INTO users
                (id, email, passwordHash, name)
                VALUES
                (1, ?, ?, ?)
                ",
                array(
                    $email,
                    password_hash($pass1, PASSWORD_DEFAULT),
                    'Administrator'
                )
            );
        };
        if (!$db->selectAtom("SELECT id FROM users WHERE id='0'")) {
            // Yes it's auto-increment, but we need clean foreign keys and a
            // default "system" to be 0.
            $db->exec(
                "
                INSERT INTO users (id, active, email, name)
                VALUES (?, ?, ?)
                ",
                array(
                    0,
                    0,
                    '*',
                    'System'
                )
            );
        };
        $db->commit();
        echo "    done!\n";
    }
1320741
protected final PrcManufacturingProcessGfr<RS>
    createPutPrcManufacturingProcessGfr(
      final Map<String, Object> pAddParam) throws Exception {
    PrcManufacturingProcessGfr<RS> proc = new PrcManufacturingProcessGfr<RS>();
    @SuppressWarnings("unchecked")
    IEntityProcessor<ManufacturingProcess, Long> procDlg =
      (IEntityProcessor<ManufacturingProcess, Long>)
        lazyGetPrcAccDocGetForReverse(pAddParam);
    proc.setPrcAccDocGetForReverse(procDlg);
    //assigning fully initialized object:
    this.processorsMap
      .put(PrcManufacturingProcessGfr.class.getSimpleName(), proc);
    return proc;
  }
731840
@Override
    protected void createHistPrincipalsTable(CmsSetupDb dbCon) throws SQLException {

        System.out.println(new Exception().getStackTrace()[0].toString());
        if (!dbCon.hasTableOrColumn(TABLE_CMS_HISTORY_PRINCIPALS, null)) {
            String createStatement = readQuery(QUERY_HISTORY_PRINCIPALS_CREATE_TABLE_MYSQL);
            Map<String, String> replacer = Collections.singletonMap("${tableEngine}", m_poolData.get("engine"));
            dbCon.updateSqlStatement(createStatement, replacer, null);
        } else {
            System.out.println("table " + TABLE_CMS_HISTORY_PRINCIPALS + " already exists");
        }
    }
1081736
def create_app(app_id, app_name, source_id, region, app_data):
    
    try:
        create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        conn = get_conn()
        c = conn.cursor()

        #check old app
        c.execute("SELECT count(*) FROM app WHERE name='{0}' ".format(app_name))
        old_app = c.fetchone()
        if old_app[0] > 0:
            print 'app name (%s) already existed, clear old app and container info ...' % app_name
            c.execute("DELETE FROM container WHERE app_id='{0}'".format(app_id))
            c.execute("DELETE FROM app WHERE name='{0}'".format(app_name))
            conn.commit()

        #insert new app
        c.execute("INSERT INTO app (id,name,source_id,region,state,create_at,change_at,app_data) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')"
            .format(app_id, app_name, source_id, region, constant.STATE_APP_RUNNING, create_at, create_at, app_data))
        conn.commit()
        conn.close()
        print 'create app %s succeed!' % app_id
    except Exception, e:
        raise RuntimeError('create app %s failed! %s' % (app_id,e))
997584
Optional<SQLPPMapping> loadPPMapping(Supplier<Optional<File>> mappingFileSupplier,
                                         Supplier<Optional<Reader>> mappingReaderSupplier,
                                         Supplier<Optional<Graph>> mappingGraphSupplier)
            throws MappingIOException, InvalidMappingException, DuplicateMappingException {

        if (options.ppMapping.isPresent()) {
            return options.ppMapping;
        }

        SQLMappingParser parser = getInjector().getInstance(SQLMappingParser.class);

        Optional<File> optionalMappingFile = mappingFileSupplier.get();
        if (optionalMappingFile.isPresent()) {
            return Optional.of(parser.parse(optionalMappingFile.get()));
        }

        Optional<Reader> optionalMappingReader = mappingReaderSupplier.get();
        if (optionalMappingReader.isPresent()) {
            return Optional.of(parser.parse(optionalMappingReader.get()));
        }
        Optional<Graph> optionalMappingGraph = mappingGraphSupplier.get();
        if (optionalMappingGraph.isPresent()) {
            return Optional.of(parser.parse(optionalMappingGraph.get()));
        }

        return Optional.empty();
    }
37688
protected MappingAndDBMetadata convertPPMapping(SQLPPMapping ppMapping, Optional<RDBMetadata> optionalDBMetadata,
                                                  OBDASpecInput specInput,
                                                  Optional<Ontology> optionalOntology,
                                                  ExecutorRegistry executorRegistry)
            throws MetaMappingExpansionException, DBMetadataExtractionException, MappingOntologyMismatchException,
            InvalidMappingSourceQueriesException, UnknownDatatypeException {


        RDBMetadata dbMetadata = extractDBMetadata(ppMapping, optionalDBMetadata, specInput);

        log.debug("DB Metadata: \n{}", dbMetadata);

        log.debug(dbMetadata.printKeys());

        SQLPPMapping expandedPPMapping = expandPPMapping(ppMapping, settings, dbMetadata);

        // NB: may also add views in the DBMetadata (for non-understood SQL queries)
        MappingWithProvenance provMapping = ppMappingConverter.convert(expandedPPMapping, dbMetadata, executorRegistry);
        dbMetadata.freeze();

        MappingWithProvenance filledProvMapping = mappingDatatypeFiller.inferMissingDatatypes(provMapping, dbMetadata);

        MappingWithProvenance canonizedMapping = canonicalTransformer.transform(filledProvMapping);

        validateMapping(optionalOntology, canonizedMapping);

        return new MappingAndDBMetadataImpl(canonizedMapping.toRegularMapping(), dbMetadata);
    }
906954
protected void createUserDataTable(CmsSetupDb dbCon) throws SQLException {

        System.out.println(new Exception().getStackTrace()[0].toString());
        String createStatement = readQuery(QUERY_CREATE_TABLE_USERDATA);
        dbCon.updateSqlStatement(createStatement, null, null);
    }
981955
def create_insert():
    
    insert = upkey("insert").setResultsName("action")

    # VALUES
    attrs = Group(delimitedList(var)).setResultsName("attrs")
    value_group = Group(Suppress("(") + delimitedList(value) + Suppress(")"))
    values = Group(delimitedList(value_group)).setResultsName("list_values")
    values_insert = Suppress("(") + attrs + Suppress(")") + upkey("values") + values

    # KEYWORDS
    keyword = Group(var + Suppress("=") + value)
    item = Group(Suppress("(") + delimitedList(keyword) + Suppress(")"))
    keyword_insert = delimitedList(item).setResultsName("map_values")

    return insert + into + table + (values_insert | keyword_insert) + Optional(throttle)
1043708
private void processProjectProperties() throws SQLException
   {
      //
      // Process common attributes
      //
      List<Row> rows = getRows("select * from " + m_schema + "project where proj_id=?", m_projectID);
      m_reader.processProjectProperties(rows, m_projectID);

      //
      // Process PMDB-specific attributes
      //
      rows = getRows("select * from " + m_schema + "prefer where prefer.delete_date is null");
      if (!rows.isEmpty())
      {
         Row row = rows.get(0);
         ProjectProperties ph = m_reader.getProject().getProjectProperties();
         ph.setCreationDate(row.getDate("create_date"));
         ph.setLastSaved(row.getDate("update_date"));
         ph.setMinutesPerDay(Double.valueOf(row.getDouble("day_hr_cnt").doubleValue() * 60));
         ph.setMinutesPerWeek(Double.valueOf(row.getDouble("week_hr_cnt").doubleValue() * 60));
         ph.setWeekStartDay(Day.getInstance(row.getInt("week_start_day_num")));

         processDefaultCurrency(row.getInteger("curr_id"));
      }

      processSchedulingProjectProperties();
   }