Generate the SQL required for specific object type
323975
def _make_default_privileges_list_query(name, object_type, prepend):
    '''
    
    '''
    if object_type == 'table':
        query = (' '.join([
            'SELECT defacl.defaclacl AS name',
            'FROM pg_default_acl defacl',
            'JOIN pg_authid aid',
            'ON defacl.defaclrole = aid.oid ',
            'JOIN pg_namespace nsp ',
            'ON nsp.oid = defacl.defaclnamespace',
            "WHERE nsp.nspname = '{0}'",
            "AND defaclobjtype ='r'",
            'ORDER BY nspname',
        ])).format(prepend)
    elif object_type == 'sequence':
        query = (' '.join([
            'SELECT defacl.defaclacl AS name',
            'FROM pg_default_acl defacl',
            'JOIN pg_authid aid',
            'ON defacl.defaclrole = aid.oid ',
            'JOIN pg_namespace nsp ',
            'ON nsp.oid = defacl.defaclnamespace',
            "WHERE nsp.nspname = '{0}'",
            "AND defaclobjtype ='S'",
            'ORDER BY nspname',
        ])).format(prepend, name)
    elif object_type == 'schema':
        query = (' '.join([
            'SELECT nspacl AS name',
            'FROM pg_catalog.pg_namespace',
            "WHERE nspname = '{0}'",
            'ORDER BY nspname',
        ])).format(name)
    elif object_type == 'function':
        query = (' '.join([
            'SELECT defacl.defaclacl AS name',
            'FROM pg_default_acl defacl',
            'JOIN pg_authid aid',
            'ON defacl.defaclrole = aid.oid ',
            'JOIN pg_namespace nsp ',
            'ON nsp.oid = defacl.defaclnamespace',
            "WHERE nsp.nspname = '{0}'",
            "AND defaclobjtype ='f'",
            'ORDER BY nspname',
        ])).format(prepend, name)
    elif object_type == 'group':
        query = (' '.join([
            'SELECT rolname, admin_option',
            'FROM pg_catalog.pg_auth_members m',
            'JOIN pg_catalog.pg_roles r',
            'ON m.member=r.oid',
            'WHERE m.roleid IN',
            '(SELECT oid',
            'FROM pg_catalog.pg_roles',
            "WHERE rolname='{0}')",
            'ORDER BY rolname',
        ])).format(name)

    return query
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;
}
967670
function requireValidColumn (name, spec) {
    // if spec is a string then convert to object using string
    // as type and name as the path for getting value from data
    if (typeof spec === 'string') {
        // capture type
        var type = spec
        // create new spec with default spect
        spec = _.cloneDeep(defaultColumnSpec)
        // set type
        spec.type = type
        // use the column name as path
        spec.path = name
    }
    // require object
    assert(spec && typeof spec === 'object', 'column spec must be obect for '+name)
    // default path to name
    if (typeof spec.path !== 'string') {
        spec.path = name
    }
    // if column is unique and firstOnly is not defined then default true
    if (spec.unique && spec.firstOnly === undefined) {
        spec.firstOnly = true
    }
    // if firstOnly is true then colum must be nullable
    if (spec.firstOnly && spec.null === 'false') {
        throw new Error(name+' must be nullable')
    }
    // require valid type
    assert.ok(sql.columnTypes[spec.type], name+' invalid type: '+spec.type)
    // return validated spec
    return spec
}
794798
@Override
   public Sql[] generateSql(final InsertStatement statement, final Database database,
         final SqlGeneratorChain sqlGeneratorChain) {
      for (final Entry<String, Object> entry : statement.getColumnValues().entrySet()) {
         entry.setValue(handleColumnValue(entry.getValue(), database));
      }
      return super.generateSql(statement, database, sqlGeneratorChain);
   }
210858
function getDBTypeFromDBValue(db) {
    if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) {
        return 'sql';
    }
    return db;
}
302669
def get_sql(self):
        """"""
        test_method = [
            self.is_time,
            self.is_date,
            self.is_datetime,
            self.is_decimal,
            self.is_year,
            self.is_tinyint,
            self.is_smallint,
            self.is_mediumint,
            self.is_int,
            self.is_bigint,
            self.is_tinytext,
            self.is_varchar,
            self.is_mediumtext,
            self.is_longtext,
        ]
        # Loop through test methods until a test returns True
        for method in test_method:
            if method():
                return self.sql
1302730
public static void generateGenericExecSQL(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method) {

		boolean nullable;
		final List<String> paramsList = new ArrayList<String>();
		final List<String> contentValueList = new ArrayList<String>();
		final One<Boolean> columnsToUpdate = new One<Boolean>(true);

		String sql = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public void onWhereStatementBegin(Where_stmtContext ctx) {
				super.onWhereStatementBegin(ctx);

				columnsToUpdate.value0 = false;
			}

			@Override
			public void onWhereStatementEnd(Where_stmtContext ctx) {
				super.onWhereStatementEnd(ctx);

				columnsToUpdate.value0 = true;
			}

			@Override
			public String onColumnName(String columnName) {
				String resolvedName = currentSchema.findColumnNameByPropertyName(method, columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(resolvedName != null, method, columnName);

				return resolvedName;

			}

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

				if (columnsToUpdate.value0) {
					contentValueList.add(propertyName);
				} else {
					paramsList.add(propertyName);
				}
				return "?";
			}
		});

		// update/insert columns
		final SQLiteEntity entity = method.getEntity();
		for (String item : contentValueList) {
			// ASSERT: property is always in entity
			String propertyName = method.findParameterNameByAlias(item);
			TypeName paramType = method.findParameterTypeByAliasOrName(item);

			SQLProperty property = entity.get(item);

			if (propertyName == null)
				throw (new PropertyNotFoundException(method, propertyName, paramType));

			Pair<String, TypeName> methodParam = new Pair<String, TypeName>(propertyName, paramType);

			// check same type
			TypeUtility.checkTypeCompatibility(method, methodParam, property);
			// check nullabliity
			// nullable = TypeUtility.isNullable(method, methodParam, property);
			//
			// if (nullable) {
			// // it use raw method param's typeName
			// methodBuilder.beginControlFlow("if ($L!=null)", methodParam.value0);
			// }

			if (method.isLogEnabled()) {
				methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
			} else {
				methodBuilder.addCode("_contentValues.put(");
			}

			// it does not need to be converted in string
			SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, methodParam.value0, methodParam.value1,
					property);
			methodBuilder.addCode(");\n");
			// if (nullable) {
			// methodBuilder.nextControlFlow("else");
			//
			// if (method.isLogEnabled()) {
			// methodBuilder.addStatement("_contentValues.putNull($S)", property.columnName);
			// } else {
			// methodBuilder.addStatement("_contentValues.putNull()");
			// }
			//
			// methodBuilder.endControlFlow();
			// }

		}

		// where condition
		methodBuilder.addComment("build where condition");
		{
			// String separator = "";
			TypeName paramType;
			String realName;

			for (String item : paramsList) {
				methodBuilder.addCode("_contentValues.addWhereArgs(");

				paramType = method.findParameterTypeByAliasOrName(item);
				realName = method.findParameterNameByAlias(item);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(paramType != null, method, item);

				// code for query arguments
				nullable = TypeUtility.isNullable(paramType);
				if (nullable) {
					methodBuilder.addCode("($L==null?\"\":", realName);
				}

				// check for string conversion
				TypeUtility.beginStringConversion(methodBuilder, paramType);

				SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, realName, paramType, null);

				// check for string conversion
				TypeUtility.endStringConversion(methodBuilder, paramType);

				if (nullable) {
					methodBuilder.addCode(")");
				}

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

		// log for where parames
		SqlBuilderHelper.generateLog(method, methodBuilder);

		// log
		methodBuilder.addCode("\n");
		methodBuilder.addStatement("database().execSQL($S, _contentValues.whereArgsAsArray())", sql);
	}
315499
private static SqlInfo buildFinalSql(SqlInfo sqlInfo, Object paramObj) {
        // 得到生成的SQL，如果有MVEL的模板表达式，则执行计算出该表达式来生成最终的SQL
        String sql = sqlInfo.getJoin().toString();
        sql = ParseHelper.parseTemplate(sql, paramObj);
        return sqlInfo.setSql(StringHelper.replaceBlank(sql));
    }
699019
def database_add_types(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/addTypes' % object_id, input_params, always_retry=always_retry, **kwargs)
325956
function toSQL(method) {
    method = method || this.method;
    var val = this[method]();
    var defaults = {
      method: method,
      options: assign({}, this.options),
      bindings: this.formatter.bindings
    };
    if (typeof val === 'string') {
      val = { sql: val };
    }

    if (method === 'select' && this.single.as) {
      defaults.as = this.single.as;
    }
    var out = assign(defaults, val);
    debug(out);
    return out;
  }
199963
def generate_base(model, model_dict, config, manifest, source_config,
                  provider, adapter=None):
    """"""
    if provider is None:
        raise dbt.exceptions.InternalException(
            "Invalid provider given to context: {}".format(provider))

    target_name = config.target_name
    target = config.to_profile_info()
    del target['credentials']
    target.update(config.credentials.serialize(with_aliases=True))
    target['type'] = config.credentials.type
    target.pop('pass', None)
    target['name'] = target_name

    adapter = get_adapter(config)

    context = {'env': target}

    pre_hooks = None
    post_hooks = None

    db_wrapper = DatabaseWrapper(adapter)

    context = dbt.utils.merge(context, {
        "adapter": db_wrapper,
        "api": {
            "Relation": db_wrapper.Relation,
            "Column": adapter.Column,
        },
        "column": adapter.Column,
        "config": provider.Config(model_dict, source_config),
        "database": config.credentials.database,
        "env_var": env_var,
        "exceptions": dbt.exceptions.wrapped_exports(model),
        "execute": provider.execute,
        "flags": dbt.flags,
        # TODO: Do we have to leave this in?
        "graph": manifest.to_flat_graph(),
        "log": log,
        "model": model_dict,
        "modules": {
            "pytz": get_pytz_module_context(),
            "datetime": get_datetime_module_context(),
        },
        "post_hooks": post_hooks,
        "pre_hooks": pre_hooks,
        "ref": provider.ref(db_wrapper, model, config, manifest),
        "return": _return,
        "schema": config.credentials.schema,
        "sql": None,
        "sql_now": adapter.date_function(),
        "source": provider.source(db_wrapper, model, config, manifest),
        "fromjson": fromjson,
        "tojson": tojson,
        "target": target,
        "try_or_compiler_error": try_or_compiler_error(model)
    })

    return context
11832
def _get_query_spec(cls, params):
    """"""
    entity_kind = params[cls.ENTITY_KIND_PARAM]
    filters = params.get(cls.FILTERS_PARAM)
    app = params.get(cls._APP_PARAM)
    ns = params.get(cls.NAMESPACE_PARAM)

    return model.QuerySpec(
        entity_kind=cls._get_raw_entity_kind(entity_kind),
        keys_only=bool(params.get(cls.KEYS_ONLY_PARAM, False)),
        filters=filters,
        batch_size=int(params.get(cls.BATCH_SIZE_PARAM, cls._BATCH_SIZE)),
        model_class_path=entity_kind,
        app=app,
        ns=ns)
858171
def run_object_query(client, base_object_query, start_record, limit_to,
                     verbose=False):
    """"""
    if verbose:
        print("[start: %d limit: %d]" % (start_record, limit_to))
    start = datetime.datetime.now()
    result = client.execute_object_query(
        object_query=base_object_query,
        start_record=start_record,
        limit_to=limit_to)
    end = datetime.datetime.now()
    if verbose:
        print("[%s - %s]" % (start, end))
    return result
1184415
def to_sql
      @to_sql ||= begin
        if eager_loading?
          apply_join_dependency do |relation, join_dependency|
            relation = join_dependency.apply_column_aliases(relation)
            relation.to_sql
          end
        else
          conn = klass.connection
          conn.unprepared_statement { conn.to_sql(arel) }
        end
      end
    end
1214454
function createTableKeyMulti (spec) {
    // require spec to be object
    assert.equal(typeof spec, 'object', 'spec must be object')
    // require columns to be array
    assert.ok(Array.isArray(spec.columns), 'index columns must be array')
    // return key sql
    return 'KEY ('+_.map(spec.columns, quoteName).join(', ')+')'
}
848927
def dump(self, obj, context=None):
        """"""
        return self.schema_class(context=context).dump(obj).data
355026
static QueryMeta buildInsertSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        String        tableName = activeRecord.getTableName();
        StringBuilder sb        = new StringBuilder(Const.SQL_INSERT + " ");
        sb.append(tableName);
        sb.append(" (");

        StringBuffer values = new StringBuffer(" VALUES (");
        Stream.of(activeRecord.getClass().getDeclaredFields())
                .filter(field -> null == field.getAnnotation(Transient.class))
                .forEach(field -> {
                    try {
                        field.setAccessible(true);
                        if (field.get(activeRecord) != null) {
                            Pair<String, String> pair = getColumnName(field);
                            sb.append(pair.getLeft()).append(", ");
                            values.append(':').append(pair.getRight()).append(", ");
                        }
                    } catch (Exception e) {
                    }
                });

        sb.append(')');
        values.append(')');

        String sql = sb.append(values).toString().replace(", )", ")");
        queryMeta.setSql(sql);
        return queryMeta;
    }