All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ollie.query.Insert Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (C) 2014 Michael Pardo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ollie.query;

import android.text.TextUtils;
import ollie.Model;
import ollie.Ollie;

public final class Insert extends QueryBase {
	private Insert() {
		super(null, null);
	}

	public static  Into into(Class table) {
		return new Into(new Insert(), table);
	}

	@Override
	public String getPartSql() {
		return "INSERT";
	}

	public static final class Into extends QueryBase {
		private Into(Query parent, Class table) {
			super(parent, table);
		}

		public Columns columns(String... columns) {
			return new Columns(this, mTable, columns);
		}

		public Values values(Object... args) {
			return new Values(this, mTable, args);
		}

		@Override
		protected String getPartSql() {
			StringBuilder builder = new StringBuilder();
			builder.append("INTO ");
			builder.append(Ollie.getTableName(mTable));
			return builder.toString();
		}
	}

	public static final class Columns extends QueryBase {
		private String[] mColumns;

		public Columns(Query parent, Class table, String[] columns) {
			super(parent, table);
			mColumns = columns;
		}

		public Values values(Object... args) {
			if (mColumns.length != args.length) {
				throw new MalformedQueryException("Number of columns does not match number of values.");
			}
			return new Values(this, mTable, args);
		}

		@Override
		protected String getPartSql() {
			StringBuilder builder = new StringBuilder();
			if (mColumns != null && mColumns.length > 0) {
				builder.append("(").append(TextUtils.join(", ", mColumns)).append(")");
			}
			return builder.toString();
		}
	}

	public static final class Values extends ExecutableQueryBase {
		private Object[] mValuesArgs;

		private Values(Query parent, Class table, Object[] args) {
			super(parent, table);
			mValuesArgs = args;
		}

		@Override
		protected String getPartSql() {
			StringBuilder builder = new StringBuilder();
			builder.append("VALUES(");
			for (int i = 0; i < mValuesArgs.length; i++) {
				if (i > 0) {
					builder.append(", ");
				}
				builder.append("?");
			}
			builder.append(")");
			return builder.toString();
		}

		@Override
		protected String[] getPartArgs() {
			return toStringArray(mValuesArgs);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy