Generates the SQL fragment defining a given column.
339013
function columnToSQL(col) {
	var sql = "`" + col.name + "` ";

	sql += nrutil.typeToSQL(col.type);

	if (col['additional']) {
		sql += ' ' + col['additional'];
	}

	if (!col['allow_null']) {
		sql += " NOT NULL";
	}

	if (col['default_value'] !== undefined) {
		var def = col['default_value']

		sql += " DEFAULT " + nrutil.serialize(def);
	}

	if (col.type == 'primary_key') {
		sql += " PRIMARY KEY AUTO_INCREMENT";
	}

	return sql;
}
642125
@Override
	public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {
		//ASSERT: returnType is a supported type
		
		// no column or too many columns
		AssertKripton.assertTrueOrInvalidMethodSignException(fieldList.size() == 1, method, "only one field can be defined as result for this method");				

		ParameterizedTypeName returnListName = (ParameterizedTypeName) method.getReturnClass();;

		TypeName collectionClass;
		ClassName listClazzName = returnListName.rawType;
		TypeName elementName = returnListName.typeArguments.get(0);

		collectionClass = SqlUtility.defineCollection(listClazzName);

		methodBuilder.addCode("\n");
		
		if (TypeUtility.isTypeEquals(collectionClass, TypeUtility.typeName(ArrayList.class))) {			
			methodBuilder.addStatement("$T<$T> resultList=new $T<$T>(_cursor.getCount())", collectionClass, elementName, collectionClass, elementName);
		} else {			
			methodBuilder.addStatement("$T<$T> resultList=new $T<$T>()", collectionClass, elementName, collectionClass, elementName);
		}
		methodBuilder.addCode("\n");
		
		SQLTransform t=SQLTransformer.lookup(returnListName);

		//@formatter:off
		methodBuilder.addCode("\n");
			methodBuilder.beginControlFlow("if (_cursor.moveToFirst())");
				methodBuilder.addCode("\n");
				methodBuilder.beginControlFlow("do\n");
					methodBuilder.beginControlFlow("if (!_cursor.isNull(0))");
						methodBuilder.addCode("resultList.add(");
						t.generateReadValueFromCursor(methodBuilder, method.getParent(), elementName, "_cursor", "0");
						methodBuilder.addCode(");\n");
					methodBuilder.nextControlFlow("else");
						methodBuilder.addCode("resultList.add(null);\n");		
					methodBuilder.endControlFlow();
				methodBuilder.endControlFlow("while (_cursor.moveToNext())");
			methodBuilder.endControlFlow();
			methodBuilder.addCode("return resultList;\n");
		methodBuilder.endControlFlow();
		//@formatter:on

	}
887327
private function compileColumnQuery()
    {
        $searchColumns = $this->queryConfiguration->searchColumns();

        foreach ($searchColumns as $i => $col) {
            $column = $this->getColumnFromName($col->columnName());

            if (!isset($column))
                continue;

            $this->createQueryForColumn($column, $col->searchValue());
        }
    }
205258
@Override
    public void setGeneratedColumnInfo(int generate, ResultMetaData meta) {

        // can support INSERT_SELECT also
        if (type != StatementTypes.INSERT) {
            return;
        }

        int colIndex = baseTable.getIdentityColumnIndex();

        if (colIndex == -1) {
            return;
        }

        switch (generate) {

            case ResultConstants.RETURN_NO_GENERATED_KEYS :
                return;

            case ResultConstants.RETURN_GENERATED_KEYS_COL_INDEXES :
                int[] columnIndexes = meta.getGeneratedColumnIndexes();

                if (columnIndexes.length != 1) {
                    return;
                }

                if (columnIndexes[0] != colIndex) {
                    return;
                }

            // $FALL-THROUGH$
            case ResultConstants.RETURN_GENERATED_KEYS :
                generatedIndexes = new int[]{ colIndex };
                break;

            case ResultConstants.RETURN_GENERATED_KEYS_COL_NAMES :
                String[] columnNames = meta.getGeneratedColumnNames();

                if (columnNames.length != 1) {
                    return;
                }

                if (baseTable.findColumn(columnNames[0]) != colIndex) {
                    return;
                }

                generatedIndexes = new int[]{ colIndex };
                break;
        }

        generatedResultMetaData =
            ResultMetaData.newResultMetaData(generatedIndexes.length);

        for (int i = 0; i < generatedIndexes.length; i++) {
            ColumnSchema column = baseTable.getColumn(generatedIndexes[i]);

            generatedResultMetaData.columns[i] = column;
        }

        generatedResultMetaData.prepareData();
    }
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);
		}
	}
1318030
function (sql) {
            var columns = this.__opts.columns, ret = "";
            if (columns && columns.length) {
                ret = " (" + columns.map(
                    function (c) {
                        return c.toString(this);
                    }, this).join(this._static.COMMA_SEPARATOR) + ")";
            }
            return ret;
        }
243413
private void generateSqlInfos() {
		try {
			String loadPathSlash = loadPath.toString().replaceAll("\\\\", "/");
			Enumeration<URL> root = Thread.currentThread().getContextClassLoader()
					.getResources(loadPathSlash);

			while (root.hasMoreElements()) {
				URI uri = root.nextElement().toURI();
				String scheme = uri.getScheme();
				if (SCHEME_FILE.equals(scheme)) {
					traverse(Paths.get(uri), detectChanges && true, false);
				} else if (SCHEME_JAR.equals(scheme)) {
					FileSystem fs = null;
					try {
						fs = FileSystems.getFileSystem(uri);
					} catch (FileSystemNotFoundException ex) {
						Map<String, String> env = new HashMap<>();
						env.put("create", "false");
						fs = FileSystems.newFileSystem(uri, env);
					}
					traverse(fs.getPath(loadPathSlash), false, false);
				}
			}
		} catch (IOException | URISyntaxException e) {
			log.error("Can't load sql files.", e);
		}
	}
120656
def compile(self, db):
        
        sql = self.expression
        if self.alias:
            sql += (' AS ' + db.quote_column(self.alias))
        return sql
232566
public static String buildSqlINSERT(String tableName, String[] columnNames, Object[] values) {
        if (columnNames.length != values.length) {
            throw new IllegalArgumentException(
                    "Number of columns must be equal to number of values.");
        }
        final String SQL_TEMPLATE = "INSERT INTO {0} ({1}) VALUES ({2})";
        final String SQL_PART_COLUMNS = StringUtils.join(columnNames, ',');
        final StringBuilder SQL_PART_VALUES = new StringBuilder();
        for (int i = 0; i < values.length; i++) {
            if (values[i] instanceof ParamExpression) {
                SQL_PART_VALUES.append(((ParamExpression) values[i]).getExpression());
            } else {
                SQL_PART_VALUES.append('?');
            }
            if (i < values.length - 1) {
                SQL_PART_VALUES.append(',');
            }
        }
        return MessageFormat.format(SQL_TEMPLATE, tableName, SQL_PART_COLUMNS, SQL_PART_VALUES);
    }
719442
public void generateWhereCondition(MethodSpec.Builder methodBuilder, SQLiteModelMethod method, SqlAnalyzer analyzer) {
		SQLiteEntity entity = method.getEntity();

		String beanParamName = method.getParameters().get(0).value0;
		SQLProperty property;
		boolean nullable;
		TypeName beanClass = typeName(entity.getElement());

		// methodBuilder.addStatement("$T<String>
		// _sqlWhereParams=getWhereParamsArray()", ArrayList.class);

		for (String item : analyzer.getUsedBeanPropertyNames()) {
			property = entity.findPropertyByName(item);
			// methodBuilder.addCode("_sqlWhereParams.add(");
			methodBuilder.addCode("_contentValues.addWhereArgs(");
			nullable = TypeUtility.isNullable(property);

			if (nullable && !(property.hasTypeAdapter())) {
				// transform null in ""
				methodBuilder.addCode("($L==null?\"\":", getter(beanParamName, beanClass, property));
			}

			// check for string conversion
			TypeUtility.beginStringConversion(methodBuilder, property);
			SQLTransformer.javaProperty2WhereCondition(methodBuilder, method, beanParamName, beanClass, property);
			// check for string conversion
			TypeUtility.endStringConversion(methodBuilder, property);

			if (nullable && !(property.hasTypeAdapter())) {
				methodBuilder.addCode(")");
			}

			methodBuilder.addCode(");\n");

		}
	}
613653
@Override
	public void generate(TypeSpec.Builder classBuilder, boolean mapFields, SQLiteModelMethod method) {
		Set<JQLProjection> fieldList = JQLChecker.getInstance().extractProjections(method, method.jql.value, method.getEntity());

		// generate method code
		MethodSpec.Builder methodBuilder = generateMethodBuilder(method);

		generateCommonPart(method, classBuilder, methodBuilder, fieldList, true);
		methodBuilder.addComment("Specialized part - $L - BEGIN", this.getClass().getSimpleName());
		generateSpecializedPart(method, classBuilder, methodBuilder, fieldList, selectType.isMapFields());
		methodBuilder.addComment("Specialized part - $L - END", this.getClass().getSimpleName());

		if (!method.isPagedLiveData()) {
			// method ForLiveData do not have to be generated for paged live
			// data
			classBuilder.addMethod(methodBuilder.build());
		}

	}
675955
function generateTableInsertSQLList( $tableName, $tableDef, $dataEntries, $params, $withClosure = true )
    {
        $sqlList = eZDBSchemaInterface::generateTableInsertSQLList( $tableName, $tableDef, $dataEntries, $params, $withClosure );

        foreach ( $tableDef['fields'] as $fieldName => $fieldDef )
        {
            if ( $fieldDef['type'] == 'auto_increment' )
            {
                $sql = "SELECT setval('" . $tableName . "_{$fieldName}_seq',max(" . $fieldName . ")+1) FROM " . $tableName;
                if ( $withClosure )
                    $sql .= ";";
                $sqlList[] = $sql;
            }
        }
        return $sqlList;
    }
454944
public SQLXML getSQLXML(int columnIndex) throws SQLException {
        try {
            SQLXML xml = rsetImpl.getSQLXML(columnIndex); 
            if (xml != null && freeResourcesOnClose)
                xmls.add(xml); 
            return xml; 
        } catch (SQLException sqlX) {
            FFDCFilter.processException(
                                        sqlX, getClass().getName() + ".getSQLXML", "2115", this);
            throw WSJdbcUtil.mapException(this, sqlX);
        } catch (NullPointerException nullX) {
            // No FFDC code needed; we might be closed.
            throw runtimeXIfNotClosed(nullX);
        } catch (AbstractMethodError methError) {
            // No FFDC code needed; wrong JDBC level.
            throw AdapterUtil.notSupportedX("ResultSet.getSQLXML", methError);
        } catch (RuntimeException runX) {
            FFDCFilter.processException(
                                        runX, getClass().getName() + ".getSQLXML", "2131", this);
            if (tc.isDebugEnabled())
                Tr.debug(this, tc, "getSQLXML", runX);
            throw runX;
        } catch (Error err) {
            FFDCFilter.processException(
                                        err, getClass().getName() + ".getSQLXML", "2138", this);
            if (tc.isDebugEnabled())
                Tr.debug(this, tc, "getSQLXML", err);
            throw err;
        }
    }
575157
public String getColumnName(final int column) throws SQLException {
    String columnName = getColumnInformation(column).getOriginalName();
    if (returnTableAlias) {
      columnName = getColumnInformation(column).getName(); //for old mysql compatibility
    }

    if ("".equals(columnName)) {
      // odd things that are no columns, e.g count(*)
      columnName = getColumnLabel(column);
    }
    return columnName;
  }
479290
@Override
	public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder,
			MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {		
		SQLiteEntity entity = method.getEntity();

		ParameterizedTypeName listenerType = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class),
				TypeName.get(entity.getElement().asType()));

		// List<SQLProperty> fields = fieldList.value1;
		TypeName entityClass = typeName(entity.getElement());

		int counter = SqlBuilderHelper.countParameterOfType(method, listenerType);
		if (counter == 0) {
			// non listener found
			throw (new InvalidMethodSignException(method, "there is no parameter of type \"ReadCursorListener\""));
		}
		if (counter > 1) {
			// more than one listener found
			throw (new InvalidMethodSignException(method,
					"there are more than one parameter of type \"ReadCursorListener\""));
		}

		String listenerName = SqlSelectBuilder.getNameParameterOfType(method, listenerType);

		
		// immutable management
		if (entity.isImmutablePojo()) {
			methodBuilder.addStatement("$T resultBean=null", entityClass);
			methodBuilder.addCode("\n");			
			methodBuilder.addComment("initialize temporary variable for immutable POJO");
			ImmutableUtility.generateImmutableVariableInit(entity, methodBuilder);
		} else {
			methodBuilder.addStatement("$T resultBean=new $T()", entityClass, entityClass);
		}

		methodBuilder.beginControlFlow("if (_cursor.moveToFirst())");

		// generate index from columns
		methodBuilder.addCode("\n");
		{
			int i = 0;
			for (JQLProjection a : fieldList) {
				SQLProperty item = a.property;

				methodBuilder.addStatement("int index$L=_cursor.getColumnIndex($S)", (i++), item.columnName);
				if (item.hasTypeAdapter()) {
					methodBuilder.addStatement("$T $LAdapter=$T.getAdapter($T.class)",
							item.typeAdapter.getAdapterTypeName(), item.getName(), SQLTypeAdapterUtils.class,
							item.typeAdapter.getAdapterTypeName());
				}
			}
		}
		methodBuilder.addCode("\n");
		methodBuilder.addCode("int rowCount=_cursor.getCount();\n");

		methodBuilder.beginControlFlow("do\n");

		// reset mapping
		methodBuilder.addCode("// reset mapping\n");
		{
			int i = 0;
			for (SQLProperty item : entity.getCollection()) {
				if (item.isNullable()) {
					SQLTransformer.resetBean(methodBuilder, entityClass, "resultBean", item, "_cursor",
							"index" + i + "");
					methodBuilder.addCode(";");
					methodBuilder.addCode("\n");
				} else {
					methodBuilder.addCode("// " + item.getName() + " does not need reset (it will be taken from db)\n");
				}
				i++;
			}
		}
		methodBuilder.addCode("\n");

		// generate mapping
		methodBuilder.addCode("// generate mapping\n");
		{
			int i = 0;
			for (JQLProjection a : fieldList) {
				SQLProperty item = a.property;
				if (item.isNullable()) {
					methodBuilder.addCode("if (!_cursor.isNull(index$L)) { ", i);
				}
				SQLTransformer.cursor2Java(methodBuilder, typeName(entity.getElement()), item, "resultBean", "_cursor",
						"index" + i + "");
				methodBuilder.addCode(";");
				if (item.isNullable()) {
					methodBuilder.addCode(" }");
				}
				methodBuilder.addCode("\n");

				i++;
			}
		}
		methodBuilder.addCode("\n");
		
		// immutable management
		if (entity.isImmutablePojo()) {
			methodBuilder.addComment("define immutable POJO");
			ImmutableUtility.generateImmutableEntityCreation(entity, methodBuilder, "resultBean", false);
		} 

		methodBuilder.addCode("$L.onRead(resultBean, _cursor.getPosition(), rowCount);\n", listenerName);
		methodBuilder.endControlFlow("while (_cursor.moveToNext())");

		// close try { open cursor
		methodBuilder.endControlFlow();

		// close method
		methodBuilder.endControlFlow();

	}
1254726
private void generateColumnsArray(Finder<SQLProperty> entity) {
		// generate columns array
		Builder sp = FieldSpec.builder(ArrayTypeName.of(String.class), "COLUMNS", Modifier.STATIC, Modifier.PRIVATE,
				Modifier.FINAL);
		String s = "";
		StringBuilder buffer = new StringBuilder();
		for (SQLProperty property : entity.getCollection()) {
			buffer.append(s + "COLUMN_" + columnNameToUpperCaseConverter.convert(property.getName()));
			s = ", ";
		}
		classBuilder.addField(sp.addJavadoc("Columns array\n").initializer("{" + buffer.toString() + "}").build());
		classBuilder.addMethod(MethodSpec.methodBuilder("columns").addModifiers(Modifier.PUBLIC)
				.addJavadoc("Columns array\n").addAnnotation(Override.class).returns(ArrayTypeName.of(String.class))
				.addStatement("return COLUMNS").build());

		classBuilder.addMethod(MethodSpec.methodBuilder("name").addModifiers(Modifier.PUBLIC).addJavadoc("table name\n")
				.addAnnotation(Override.class).returns(TypeName.get(String.class)).addStatement("return TABLE_NAME")
				.build());
	}
768942
public void createGenerator (Connection conn, String tableName, String columnName, int initValue)
        throws SQLException
    {
        if (initValue == 1) {
            return; // that's the default! yay, do nothing
        }

        String seqname = "\"" + tableName + "_" + columnName + "_seq\"";
        Statement stmt = conn.createStatement();
        try {
            stmt.executeQuery("select setval('" + seqname + "', " + initValue + ", false)");
        } finally {
            JDBCUtil.close(stmt);
        }
        log("Initial value of " + seqname  + " set to " + initValue + ".");
    }